<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(false, 'Invalid request method', [], 405);
}

$auth = new Auth();
if (!$auth->check()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$restaurantId = $auth->restaurantId();
if (!$restaurantId) {
    jsonResponse(false, 'No restaurant associated', [], 403);
}

$db = Database::getInstance();
$pdo = $db->getConnection();

$typeFilter = $_GET['type'] ?? '';
$statusFilter = $_GET['status'] ?? '';

$sql = "SELECT o.id, o.restaurant_id, o.table_id, o.order_number, o.order_type,
               o.customer_name, o.customer_phone, o.order_notes, o.subtotal,
               o.discount, o.tax, o.service_charge, o.delivery_charge,
               o.grand_total, o.payment_method, o.payment_status, o.order_status,
               o.created_at, o.updated_at,
               t.table_number, t.table_name
        FROM orders o
        LEFT JOIN tables t ON o.table_id = t.id
        WHERE o.restaurant_id = ?
        AND o.order_status IN ('new', 'confirmed', 'preparing', 'ready')
        AND o.is_demo = 0";

$params = [$restaurantId];

if ($typeFilter && in_array($typeFilter, ['dine_in', 'takeaway', 'delivery'])) {
    $sql .= " AND o.order_type = ?";
    $params[] = $typeFilter;
}

if ($statusFilter && in_array($statusFilter, ['new', 'confirmed', 'preparing', 'ready'])) {
    $sql .= " AND o.order_status = ?";
    $params[] = $statusFilter;
}

$sql .= " ORDER BY o.created_at ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

foreach ($orders as &$order) {
    $itemStmt = $pdo->prepare(
        "SELECT id, order_id, menu_item_id, item_name, variation_name,
                quantity, unit_price, variation_price, addons_total, item_total, item_notes
         FROM order_items WHERE order_id = ?"
    );
    $itemStmt->execute([$order['id']]);
    $items = $itemStmt->fetchAll();

    foreach ($items as &$item) {
        $addonStmt = $pdo->prepare(
            "SELECT id, order_item_id, addon_name, addon_price
             FROM order_item_addons WHERE order_item_id = ?"
        );
        $addonStmt->execute([$item['id']]);
        $addons = $addonStmt->fetchAll();
        $item['addons'] = $addons;
    }
    unset($item);

    $order['items'] = $items;
    $order['status'] = $order['order_status'];
}
unset($order);

jsonResponse(true, 'Orders loaded', ['orders' => $orders]);
