<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

$status = trim($db->real_escape_string($_GET['status'] ?? ''));

$query = "SELECT * FROM orders";

// If the status is empty or explicitly set to 'all', fetch everything completely
if (!empty($status) && strtolower($status) !== 'all') {
    $query .= " WHERE status = '$status'";
}
$query .= " ORDER BY id DESC";

$ordersResult = $db->query($query);
$responseOrders = [];

if ($ordersResult) {
    while ($order = $ordersResult->fetch_assoc()) {
        $order_id = $order['id'];
        
        $itemsResult = $db->query("SELECT * FROM order_items WHERE order_id = $order_id");
        $items = [];
        
        if ($itemsResult) {
            while ($item = $itemsResult->fetch_assoc()) {
                $items[] = $item;
            }
        }
        
        $order['items'] = $items;
        $responseOrders[] = $order;
    }
}

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