<?php
/**
 * API Endpoint: Get VPN Servers
 * Returns list of servers accessible by the API key
 * 
 * Method: GET
 * Headers: X-API-Key or Authorization: Bearer {api_key}
 * Optional: ?device_id=xxx
 */

require_once __DIR__ . '/helpers/auth.php';
require_once __DIR__ . '/helpers/response.php';

// CORS headers (adjust for production)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, Authorization');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 'METHOD_NOT_ALLOWED', 405);
}

// Get API key from request
$apiKey = getAPIKeyFromRequest();
$deviceId = $_GET['device_id'] ?? null;

// Authenticate
$auth = authenticateAPI($apiKey);

if (!$auth['success']) {
    logAPIRequest($apiKey, 'servers', null, $auth['code'], $deviceId);
    sendError($auth['error'], $auth['code'], 401);
}

$api = $auth['api'];

try {
    $db = getDB();
    
    // Get servers assigned to this API key (only active servers)
    $stmt = $db->prepare("
        SELECT 
            s.id,
            s.server_name,
            s.country,
            s.flag_url,
            s.status
        FROM vpn_servers s
        INNER JOIN api_server_access asa ON s.id = asa.server_id
        WHERE asa.api_key_id = ? AND s.status = 'active'
        ORDER BY s.country, s.server_name
    ");
    
    $stmt->execute([$api['id']]);
    $servers = $stmt->fetchAll();
    
    // Increment usage counter
    incrementAPIUsage($api['id']);
    
    // Log request
    logAPIRequest($apiKey, 'servers', null, 'success', $deviceId);
    
    // Return server list
    sendSuccess([
        'servers' => $servers,
        'total' => count($servers)
    ]);
    
} catch (PDOException $e) {
    error_log("Servers API Error: " . $e->getMessage());
    logAPIRequest($apiKey, 'servers', null, 'error', $deviceId);
    sendError('Internal server error', 'SERVER_ERROR', 500);
}
