<?php
header('Content-Type: application/json');
require_once 'config.php';

$customer_id = $_GET['customer_id'] ?? '';

if (!$customer_id) {
    echo json_encode(['success' => false, 'message' => 'Missing customer_id']);
    exit;
}

// Get the latest pending order for this customer
// Example for get_current_order.php
$stmt = $conn->prepare("SELECT id, total_amount, status FROM orders WHERE customer_id = ? AND status IN ('Pending','Preparing','Confirmed','Out for Delivery') ORDER BY created_at DESC LIMIT 1");
$stmt->bind_param("s", $customer_id);
$stmt->execute();
$result = $stmt->get_result();
$order = $result->fetch_assoc();
$stmt->close();

if ($order) {
    // Get order items
    $stmt2 = $conn->prepare("SELECT name, quantity FROM order_items WHERE order_id = ?");
    $stmt2->bind_param("i", $order['id']);
    $stmt2->execute();
    $result2 = $stmt2->get_result();
    $items = [];
    while ($row = $result2->fetch_assoc()) {
        $items[] = $row['name'] . ' x' . $row['quantity'];
    }
    $stmt2->close();
    $order['items'] = implode(', ', $items);
}

echo json_encode([
    'success' => true,
    'order' => $order
]);
