<?php
/**
 * Manager Servers API
 * Handles server data access for managers
 */

session_start();
require 'config.php';

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

function hasColumn($table, $column) {
    global $conn;
    $tableEsc = $conn->real_escape_string($table);
    $columnEsc = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `" . $tableEsc . "` LIKE '" . $columnEsc . "'");
    return ($res && $res->num_rows > 0);
}

// Check manager authentication
// Accept manager_id from session or from GET parameter (for client-side authentication)
$manager_id = null;

if (isset($_SESSION['manager_id'])) {
    $manager_id = $_SESSION['manager_id'];
} elseif (isset($_GET['manager_id'])) {
    $manager_id = intval($_GET['manager_id']);
    // Validate the manager exists
    $validateRes = $conn->query("SELECT id FROM managers WHERE id = " . $manager_id . " LIMIT 1");
    if (!$validateRes || $validateRes->num_rows === 0) {
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access'
        ]);
        exit;
    }
} else {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

@$conn->query("ALTER TABLE servers ADD COLUMN max_active_orders INT NOT NULL DEFAULT 1 AFTER shift_end");

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';
    
    if ($action === 'list') {
        try {
            $supports_online = hasColumn('online_table_bookings', 'assigned_server_id');
            $onlineCountExpr = "0";
            if ($supports_online) {
                $onlineCountExpr = "(SELECT COUNT(*) FROM online_table_bookings otb
                                     LEFT JOIN bookings b ON b.id = otb.booking_id
                                     WHERE otb.assigned_server_id = servers.id
                                     AND otb.allocation_status = 'allocated'
                                     AND (b.id IS NULL OR b.status IN ('pending', 'confirmed', 'checked_in')))";
            }

            $sql = "SELECT id, name, employee_id, phone, status, shift_start, shift_end, rating, created_at, is_online,
                           COALESCE(max_active_orders, 1) AS max_active_orders,
                           (
                               (SELECT COUNT(*) FROM table_assignments ta WHERE ta.server_id = servers.id AND ta.status = 'assigned')
                               + " . $onlineCountExpr . "
                           ) AS active_orders_count
                    FROM servers 
                    ORDER BY name ASC";
            
            $result = $conn->query($sql);
            
            if ($result) {
                $servers = [];
                while ($row = $result->fetch_assoc()) {
                    // The primary status indicator is is_online column
                    // It gets set to TRUE when server logs in, FALSE when logs out
                    $servers[] = $row;
                }
                
                echo json_encode([
                    'success' => true,
                    'data' => $servers,
                    'count' => count($servers)
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $conn->error
                ]);
            }
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    } elseif ($action === 'get' && isset($_GET['id'])) {
        $server_id = intval($_GET['id']);
        
        try {
            $sql = "SELECT * FROM servers WHERE id = " . $server_id;
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $server = $result->fetch_assoc();
                echo json_encode([
                    'success' => true,
                    'data' => $server
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server not found'
                ]);
            }
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid action'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
}
?>
