<?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();

function normalizeTableNumber($tableNumber) {
    $upper = strtoupper(trim((string)$tableNumber));
    return preg_replace('/[^A-Z0-9]/', '', $upper);
}

function extractTableDigits($tableNumber) {
    return preg_replace('/\D+/', '', (string)$tableNumber);
}

function findMappedRestaurantTableId($conn, $onlineTableNumber, $floorLevel = null, $section = null) {
    $onlineRaw = trim((string)$onlineTableNumber);
    if ($onlineRaw === '') {
        return 0;
    }

    $exactSql = "SELECT id FROM restaurant_tables WHERE table_number = '" . $conn->real_escape_string($onlineRaw) . "' LIMIT 1";
    $exactRes = $conn->query($exactSql);
    if ($exactRes && $exactRes->num_rows > 0) {
        return intval($exactRes->fetch_assoc()['id']);
    }

    $normOnline = normalizeTableNumber($onlineRaw);
    $digitsOnline = ltrim(extractTableDigits($onlineRaw), '0');

    $candidateSql = "SELECT id, table_number, floor_level, section FROM restaurant_tables";
    $candidateRes = $conn->query($candidateSql);
    if (!$candidateRes || $candidateRes->num_rows === 0) {
        return 0;
    }

    $bestId = 0;
    $bestScore = -1;
    while ($row = $candidateRes->fetch_assoc()) {
        $candidateNorm = normalizeTableNumber($row['table_number'] ?? '');
        $candidateDigits = ltrim(extractTableDigits($row['table_number'] ?? ''), '0');

        $isMatch = false;
        if ($candidateNorm !== '' && $candidateNorm === $normOnline) {
            $isMatch = true;
        } elseif ($digitsOnline !== '' && $candidateDigits !== '' && $digitsOnline === $candidateDigits) {
            $isMatch = true;
        }

        if (!$isMatch) {
            continue;
        }

        $score = 0;
        if ($floorLevel !== null && intval($row['floor_level']) === intval($floorLevel)) {
            $score += 2;
        }
        if ($section !== null && trim((string)$section) !== '' && strcasecmp(trim((string)$row['section']), trim((string)$section)) === 0) {
            $score += 1;
        }

        if ($score > $bestScore) {
            $bestScore = $score;
            $bestId = intval($row['id']);
        }
    }

    return $bestId;
}

// Backward-compatible migration support for online table server assignment fields.
$checkOnlineServerCol = $conn->query("SHOW COLUMNS FROM online_table_bookings LIKE 'assigned_server_id'");
if (!$checkOnlineServerCol || $checkOnlineServerCol->num_rows === 0) {
    @$conn->query("ALTER TABLE online_table_bookings ADD COLUMN assigned_server_id INT NULL AFTER online_table_id");
}
$checkOnlineLinkedCol = $conn->query("SHOW COLUMNS FROM online_table_bookings LIKE 'linked_assignment_id'");
if (!$checkOnlineLinkedCol || $checkOnlineLinkedCol->num_rows === 0) {
    @$conn->query("ALTER TABLE online_table_bookings ADD COLUMN linked_assignment_id INT NULL AFTER assigned_server_id");
}

// 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'],
            'table_source' => 'restaurant'
        ];
    }
} 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'];
}

// Include online booking tables assigned to this server.
$online_sql = "SELECT
                MIN(otb.id) AS assignment_id,
                MIN(otb.online_table_id) AS table_id,
                MIN(otb.allocated_at) AS assigned_at,
                GROUP_CONCAT(ot.table_number ORDER BY ot.table_number SEPARATOR ', ') AS table_number,
                SUM(ot.current_capacity) AS current_capacity,
                MIN(ot.floor_level) AS floor_level,
                MIN(ot.section) AS section,
                MAX(ot.status) AS table_status,
                MAX(b.guests) AS booking_guests,
                b.id AS booking_id,
                b.booking_date,
                b.slot_time,
                b.meal_type
               FROM online_table_bookings otb
               INNER JOIN online_tables ot ON ot.id = otb.online_table_id
               INNER JOIN bookings b ON b.id = otb.booking_id
               WHERE otb.assigned_server_id = " . intval($server_id) . "
               AND otb.allocation_status = 'allocated'
               AND b.status IN ('pending', 'confirmed', 'checked_in')
               GROUP BY b.id, b.booking_date, b.slot_time, b.meal_type
               ORDER BY b.slot_time, b.id";

$online_result = $conn->query($online_sql);
if ($online_result && $online_result->num_rows > 0) {
    while ($online = $online_result->fetch_assoc()) {
        $capacity = intval($online['current_capacity'] ?? 0);
        $guest_count = intval($online['booking_guests'] ?? 0);
        $remaining_seats = max(0, $capacity - $guest_count);
        $assigned_tables[] = [
            'id' => intval($online['table_id']),
            'table_id' => intval($online['table_id']),
            'assignment_id' => intval($online['assignment_id']),
            'table_number' => $online['table_number'],
            'capacity' => $capacity,
            'booking_id' => intval($online['booking_id'] ?? 0),
            'floor' => intval($online['floor_level'] ?? 0),
            'section' => $online['section'],
            'status' => 'assigned',
            'number_of_guests' => $guest_count,
            'assigned_seats' => $guest_count,
            'remaining_seats' => $remaining_seats,
            'assigned_at' => $online['assigned_at'],
            'table_source' => 'online',
            'booking_date' => $online['booking_date'],
            'slot_time' => $online['slot_time'],
            'meal_type' => $online['meal_type']
        ];
    }
}

// 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'])) {
        $source = isset($assigned_table['table_source']) ? $assigned_table['table_source'] : 'restaurant';
        if ($source === 'online' && !empty($assigned_table['booking_id'])) {
            $unique_table_ids[$source . '_booking:' . (int)$assigned_table['booking_id']] = true;
        } else {
            $unique_table_ids[$source . ':' . (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);
?>
