<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once 'db.php';
$response = [
'success' => false,
'message' => 'Invalid request'
];
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
try {
// Validate and sanitize input
$user_phone = filter_input(INPUT_GET, 'user_phone', FILTER_SANITIZE_STRING);
if (empty($user_phone)) {
throw new Exception("Missing user phone number");
}
// Prepare SQL to fetch previous indents
$stmt = $pdo->prepare("
SELECT
id,
in_cus_name,
in_cus_mobile,
in_cus_date,
in_cus_items,
status,
notes
FROM `indent`
WHERE in_cus_mobile = :user_phone
ORDER BY in_cus_date DESC
");
$stmt->bindParam(':user_phone', $user_phone);
$stmt->execute();
$orders = [];
while ($order = $stmt->fetch(PDO::FETCH_ASSOC)) {
// Decode the items JSON
$order['in_cus_items'] = json_decode($order['in_cus_items'], true);
// Calculate total items and total quantity
$totalItems = count($order['in_cus_items']);
$totalQuantity = array_sum(array_column($order['in_cus_items'], 'quantity'));
// Add additional calculated fields
$order['total_items'] = $totalItems;
$order['total_quantity'] = $totalQuantity;
$orders[] = $order;
}
// If no orders found, generate dummy data
if (empty($orders)) {
$orders = [
[
'id' => 'IND-2024-001',
'in_cus_name' => 'Charu Saikia',
'in_cus_mobile' => $user_phone,
'in_cus_date' => date('Y-m-d H:i:s'),
'in_cus_items' => [
[
'category' => 'Fertilizers',
'product_name' => 'Nitrogen-Rich Organic Fertilizer',
'quantity' => 50
]
],
'status' => 'Pending',
'notes' => 'Sample indent for demonstration',
'total_items' => 1,
'total_quantity' => 50
]
];
}
$response = [
'success' => true,
'message' => 'Orders retrieved successfully',
'orders' => $orders
];
} catch(PDOException $e) {
error_log("Database Error: " . $e->getMessage());
$response = [
'success' => false,
'message' => 'Database error: ' . $e->getMessage()
];
} catch(Exception $e) {
error_log("Validation Error: " . $e->getMessage());
$response = [
'success' => false,
'message' => $e->getMessage()
];
}
}
// Send JSON response
echo json_encode($response);
exit();
?>