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

session_start();
require 'config.php';

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

// Check manager authentication
if (!isset($_SESSION['manager_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';
    
    if ($action === 'list') {
        try {
            $sql = "SELECT id, name, employee_id, phone, status, shift_start, shift_end, rating, created_at, is_online
                    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'
    ]);
}
?>
