<?php
require_once __DIR__ . '/../../config/config.php';
requireAuth();

if (!isset($_GET['csrf_token']) || !verifyCSRFToken($_GET['csrf_token'])) {
    header('Location: ../servers.php?error=' . urlencode('Invalid request'));
    exit;
}

$serverId = intval($_GET['id'] ?? 0);
$status = $_GET['status'] ?? '';

if ($serverId <= 0 || !in_array($status, ['active', 'inactive'])) {
    header('Location: ../servers.php?error=' . urlencode('Invalid parameters'));
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("UPDATE vpn_servers SET status = ? WHERE id = ?");
    $stmt->execute([$status, $serverId]);
    
    logActivity("Server status changed to $status (ID: $serverId) by " . $_SESSION['admin_email']);
    
    header('Location: ../servers.php?success=' . urlencode('Server status updated successfully'));
} catch (PDOException $e) {
    logActivity("Toggle server error: " . $e->getMessage(), 'error');
    header('Location: ../servers.php?error=' . urlencode('Failed to update server status'));
}
