<?php
/**
 * API Endpoint: Connect to VPN Server
 * Returns OpenVPN configuration for specific server
 * 
 * Method: POST
 * Headers: X-API-Key or Authorization: Bearer {api_key}
 * Body: {
 *   "server_id": 1,
 *   "device_id": "xxx" (optional)
 * }
 */

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

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

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

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

// Get API key from request
$apiKey = getAPIKeyFromRequest();

// Get POST data
$input = json_decode(file_get_contents('php://input'), true);
$serverId = intval($input['server_id'] ?? 0);
$deviceId = $input['device_id'] ?? null;

// Validate
if ($serverId <= 0) {
    logAPIRequest($apiKey, 'connect', null, 'missing_server_id', $deviceId);
    sendError('server_id is required', 'MISSING_SERVER_ID', 400);
}

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

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

$api = $auth['api'];

try {
    $db = getDB();
    
    // Check if this API has access to the requested server
    $stmt = $db->prepare("
        SELECT 
            s.id,
            s.server_name,
            s.country,
            s.flag_url,
            s.ovpn_config,
            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.id = ? AND s.status = 'active'
        LIMIT 1
    ");
    
    $stmt->execute([$api['id'], $serverId]);
    $server = $stmt->fetch();
    
    if (!$server) {
        logAPIRequest($apiKey, 'connect', $serverId, 'no_access', $deviceId);
        sendError('Server not found or not accessible', 'SERVER_NOT_ACCESSIBLE', 403);
    }
    
    // Increment usage counter
    incrementAPIUsage($api['id']);
    
    // Log request
    logAPIRequest($apiKey, 'connect', $serverId, 'success', $deviceId);
    
    // Return server config
    sendSuccess([
        'server' => [
            'id' => $server['id'],
            'server_name' => $server['server_name'],
            'country' => $server['country'],
            'flag_url' => $server['flag_url'],
            'ovpn_config' => $server['ovpn_config']
        ]
    ]);
    
} catch (PDOException $e) {
    error_log("Connect API Error: " . $e->getMessage());
    logAPIRequest($apiKey, 'connect', $serverId, 'error', $deviceId);
    sendError('Internal server error', 'SERVER_ERROR', 500);
}
