<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET /api/customer/orders — logged-in customer's orders
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') jsonError('Method not allowed', 405);

$authUser = requireAuth();
$authUserId = $authUser['id'] ?? $authUser['user_id'] ?? null;
$db       = getDB();

$stmt = $db->prepare(
    'SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC'
);
$stmt->execute([$authUserId]);
$orders = $stmt->fetchAll();

// Attach items to each order
$iStmt = $db->prepare('SELECT * FROM order_items WHERE order_id = ?');
foreach ($orders as &$order) {
    $iStmt->execute([$order['id']]);
    $order['items'] = $iStmt->fetchAll();
}

jsonResponse($orders);
