<?php
/**
 * Test the EXACT query from server_session_check.php for server 6
 */

include 'config.php';

$server_id = 6;

echo "<h2>Testing Exact Query from server_session_check.php</h2>";
echo "<pre>";

// This is the EXACT query now used in server_session_check.php (with LEFT JOIN)
$tables_sql = "SELECT 
                ta.id,
                ta.table_id,
                ta.server_id,
                ta.status as assignment_status,
                ta.number_of_guests,
                ta.assigned_at,
                rt.table_number,
                rt.capacity,
                rt.floor,
                rt.section,
                rt.status as table_status
               FROM table_assignments ta
               LEFT JOIN restaurant_tables rt ON ta.table_id = rt.id
               WHERE ta.server_id = " . intval($server_id) . " 
               AND ta.status = 'assigned'
               ORDER BY rt.table_number";

echo "Query:\n" . $tables_sql . "\n\n";

$result = $conn->query($tables_sql);
if (!$result) {
    echo "ERROR: " . $conn->error . "\n";
} else {
    echo "Rows returned: " . $result->num_rows . "\n\n";
    
    if ($result->num_rows > 0) {
        echo "=== Query Results ===\n";
        while ($row = $result->fetch_assoc()) {
            echo json_encode($row, JSON_PRETTY_PRINT) . "\n";
        }
    } else {
        echo "No rows returned. Debugging...\n\n";
        
        // Debug step 1: Check if ANY assignments exist for this server
        echo "--- Step 1: Check if ANY assignments exist for server " . $server_id . " ---\n";
        $check = $conn->query("SELECT id, table_id, status FROM table_assignments WHERE server_id = " . $server_id);
        echo "Total assignments for server " . $server_id . ": " . $check->num_rows . "\n";
        if ($check->num_rows > 0) {
            while ($row = $check->fetch_assoc()) {
                echo "  Assignment ID:" . $row['id'] . " Table:" . $row['table_id'] . " Status:" . $row['status'] . "\n";
            }
        }
        
        // Debug step 2: Check if any have status='assigned'
        echo "\n--- Step 2: Check assignments with status='assigned' ---\n";
        $check = $conn->query("SELECT id, table_id, status FROM table_assignments WHERE server_id = " . $server_id . " AND status = 'assigned'");
        echo "Assigned status count: " . $check->num_rows . "\n";
        if ($check->num_rows > 0) {
            while ($row = $check->fetch_assoc()) {
                echo "  Assignment ID:" . $row['id'] . " Table:" . $row['table_id'] . "\n";
            }
        }
        
        // Debug step 3: Check restaurant_tables exist
        echo "\n--- Step 3: Check if restaurant_tables are populated ---\n";
        $check = $conn->query("SELECT COUNT(*) as total FROM restaurant_tables");
        $data = $check->fetch_assoc();
        echo "Total restaurant tables: " . $data['total'] . "\n";
    }
}

echo "</pre>";
?>
