<?php
// Get real-time table status for POS dine-in modal
header('Content-Type: application/json');

include '../db.php';

try {
    // Get all tables with their current status and hold order info
    $query = "
        SELECT 
            dt.id,
            dt.table_name,
            dt.seats,
            dt.status,
            df.name as floor_name,
            CASE 
                WHEN EXISTS (SELECT 1 FROM hold_orders ho WHERE ho.table_id = dt.id) THEN 'occupied'
                ELSE dt.status
            END as calculated_status,
            COUNT(ho.id) as hold_orders_count,
            SUM(ho.total_amount) as total_hold_amount
        FROM dinein_tables dt
        LEFT JOIN dinein_floors df ON dt.floor_id = df.id
        LEFT JOIN hold_orders ho ON dt.id = ho.table_id
        WHERE dt.is_active = 1
        GROUP BY dt.id, dt.table_name, dt.seats, dt.status, df.name
        ORDER BY df.name, dt.table_name
    ";
    
    $result = $conn->query($query);
    
    $tables = [];
    while ($row = $result->fetch_assoc()) {
        $tables[] = [
            'id' => $row['id'],
            'table_name' => $row['table_name'],
            'seats' => $row['seats'],
            'status' => $row['calculated_status'],
            'floor_name' => $row['floor_name'],
            'hold_orders_count' => intval($row['hold_orders_count']),
            'total_hold_amount' => floatval($row['total_hold_amount'] ?? 0)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'tables' => $tables,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>
