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

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

if (!$customer_id) {
    echo json_encode(['success' => false, 'message' => 'Customer ID is required', 'orders' => []]);
    exit;
}

// Fetch orders for this customer
$stmt = $conn->prepare("SELECT id, total_amount, created_at FROM orders WHERE customer_id = ? ORDER BY created_at DESC");
$stmt->bind_param("s", $customer_id);
$stmt->execute();
$result = $stmt->get_result();

$orders = [];
while ($order = $result->fetch_assoc()) {
    // Fetch order items for this order
    $item_stmt = $conn->prepare("SELECT name, quantity FROM order_items WHERE order_id = ?");
    $item_stmt->bind_param("i", $order['id']);
    $item_stmt->execute();
    $item_result = $item_stmt->get_result();

    $items = [];
    while ($item = $item_result->fetch_assoc()) {
        $items[] = $item['name'] . ' x' . $item['quantity'];
    }
    $order['items'] = implode(', ', $items);

    $orders[] = $order;
    $item_stmt->close();
}
$stmt->close();

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