<?php
/**
 * Server Session Check API
 * Verifies if server is logged in and returns session data
 */

session_start();
require 'config.php';

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

// Check if server is logged in
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    sendResponse(false, 'Not authenticated', null);
}

// Optional: Check session timeout (30 minutes of inactivity)
$session_timeout = 30 * 60; // 30 minutes
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
    session_destroy();
    http_response_code(401);
    sendResponse(false, 'Session expired', null);
}

// Update last activity time
$_SESSION['last_activity'] = time();

// Verify server still exists and is active in database
$server_id = $_SESSION['server_id'];
$sql = "SELECT id, name, phone, employee_id, status, is_online FROM servers WHERE id = " . intval($server_id);
$result = $conn->query($sql);

if ($result->num_rows === 0) {
    session_destroy();
    http_response_code(401);
    sendResponse(false, 'Server not found', null);
}

$server = $result->fetch_assoc();

// Get assigned tables for this server
$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.current_capacity,
                rt.floor_level,
                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";
               
$tables_result = $conn->query($tables_sql);

// Debug: Log query result
error_log("Query for server " . $server_id . ": " . $tables_sql);
if (!$tables_result) {
    error_log("Query failed: " . $conn->error);
} else {
    error_log("Query returned " . $tables_result->num_rows . " rows");
}

$assigned_tables = [];
$debug_info = [];

if ($tables_result && $tables_result->num_rows > 0) {
    $rows = [];
    $table_guest_totals = [];

    while ($table = $tables_result->fetch_assoc()) {
        // Skip if table_number is null (table might not exist)
        if ($table['table_number'] === null) {
            $debug_info[] = "Skipped assignment ID " . $table['id'] . " - references non-existent table: " . $table['table_id'];
            continue;
        }

        $rows[] = $table;
        $table_id = intval($table['table_id']);
        $guest_count = intval($table['number_of_guests'] ?? 0);
        if (!isset($table_guest_totals[$table_id])) {
            $table_guest_totals[$table_id] = 0;
        }
        $table_guest_totals[$table_id] += $guest_count;
    }

    foreach ($rows as $table) {
        $table_id = intval($table['table_id']);
        $capacity = intval($table['current_capacity'] ?? 0);
        $guest_count = intval($table['number_of_guests'] ?? 0);
        $table_total_guests = intval($table_guest_totals[$table_id] ?? 0);
        $remaining_seats = max(0, $capacity - $table_total_guests);

        // Map the response to match expected format
        $assigned_tables[] = [
            'id' => $table_id,  // Backward compatibility for older frontend code
            'table_id' => $table_id,
            'assignment_id' => (int)$table['id'],
            'table_number' => $table['table_number'],
            'capacity' => $capacity,  // Map current_capacity to capacity
            'floor' => $table['floor_level'],          // Map floor_level to floor
            'section' => $table['section'],
            'status' => $table['assignment_status'],
            'number_of_guests' => $guest_count,
            'assigned_seats' => $guest_count,
            'remaining_seats' => $remaining_seats,
            'assigned_at' => $table['assigned_at']
        ];
    }
} else {
    // Debug: No results from query
    $debug_info[] = "Query returned 0 rows";
    
    // Check if there are ANY assignments at all
    $check_any = $conn->query("SELECT COUNT(*) as total FROM table_assignments WHERE server_id = " . intval($server_id));
    $any_data = $check_any->fetch_assoc();
    $debug_info[] = "Total assignments for server: " . $any_data['total'];
    
    // Check assigned status
    $check_assigned = $conn->query("SELECT COUNT(*) as total FROM table_assignments WHERE server_id = " . intval($server_id) . " AND status = 'assigned'");
    $assigned_data = $check_assigned->fetch_assoc();
    $debug_info[] = "Assignments with status='assigned': " . $assigned_data['total'];
}

// Get real order stats for server dashboard counters
$stats_sql = "SELECT
                SUM(CASE WHEN status IN ('pending', 'confirmed', 'preparing', 'ready') THEN 1 ELSE 0 END) as active_orders_count,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_orders_count
              FROM dine_in_orders
              WHERE server_id = " . intval($server_id);
$stats_result = $conn->query($stats_sql);
$order_stats = [
    'active_orders_count' => 0,
    'completed_orders_count' => 0
];
if ($stats_result && $stats_result->num_rows > 0) {
    $stats_row = $stats_result->fetch_assoc();
    $order_stats['active_orders_count'] = intval($stats_row['active_orders_count'] ?? 0);
    $order_stats['completed_orders_count'] = intval($stats_row['completed_orders_count'] ?? 0);
}

// Count unique physical tables (not assignment rows) for the stat card.
$unique_table_ids = [];
foreach ($assigned_tables as $assigned_table) {
    if (isset($assigned_table['table_id'])) {
        $unique_table_ids[(int)$assigned_table['table_id']] = true;
    }
}
$assigned_tables_count = count($unique_table_ids);

// Return session data
$response_data = [
    'id' => $server['id'],
    'name' => $server['name'],
    'phone' => $server['phone'],
    'employee_id' => $server['employee_id'],
    'status' => $server['status'],
    'is_online' => (bool) $server['is_online'],
    'assigned_tables' => $assigned_tables,
    'assigned_tables_count' => $assigned_tables_count,
    'active_orders_count' => $order_stats['active_orders_count'],
    'completed_orders_count' => $order_stats['completed_orders_count'],
    '_debug' => $debug_info  // Include debug info for troubleshooting
];

sendResponse(true, 'Session valid', $response_data);
?>
