<?php
require_once '../db.php';

header('Content-Type: application/json');

try {
    // Get table ID from request
    $table_id = isset($_GET['table_id']) ? intval($_GET['table_id']) : 0;
    
    if (!$table_id) {
        throw new Exception('Table ID is required');
    }
    
    // Fetch orders for the specific table
    $query = "
        SELECT 
            ho.id,
            ho.customer_name,
            ho.order_mode,
            ho.total_amount,
            ho.created_at,
            ho.order_taker_id,
            (SELECT COUNT(*) FROM kds_orders ko WHERE ko.table_number = dt.table_name AND ko.order_status NOT IN ('served', 'ready')) as active_kds_orders
        FROM hold_orders ho
        LEFT JOIN dinein_tables dt ON ho.table_id = dt.id
        WHERE ho.table_id = ? 
        ORDER BY ho.created_at DESC
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $table_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orders = [];
    while ($order = $result->fetch_assoc()) {
        // Fetch order items for each order
        $items_query = "
            SELECT 
                hi.item_name,
                hi.quantity,
                hi.unit_price as price,
                hi.modifiers,
                hi.remarks
            FROM hold_items hi
            WHERE hi.hold_id = ?
            ORDER BY hi.id
        ";
        
        $items_stmt = $conn->prepare($items_query);
        $items_stmt->bind_param('i', $order['id']);
        $items_stmt->execute();
        $items_result = $items_stmt->get_result();
        
        $items = [];
        while ($item = $items_result->fetch_assoc()) {
            $items[] = $item;
        }
        
        $order['items'] = $items;
        $order['status'] = 'held'; // Default status since it's in hold_orders
        
        // Check if this table has running orders (active KDS orders)
        $order['has_running_orders'] = $order['active_kds_orders'] > 0;
        
        $orders[] = $order;
    }
    
    echo json_encode([
        'success' => true,
        'orders' => $orders
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>
