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

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

if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid CSRF token']);
    exit;
}

// Validate inputs
$serverName = trim($_POST['server_name'] ?? '');
$country = trim($_POST['country'] ?? '');
$flagUrl = trim($_POST['flag_url'] ?? '');

if (empty($serverName) || empty($country)) {
    header('Location: ../servers.php?error=' . urlencode('Server name and country are required'));
    exit;
}

// Validate file upload
if (!isset($_FILES['ovpn_file']) || $_FILES['ovpn_file']['error'] !== UPLOAD_ERR_OK) {
    header('Location: ../servers.php?error=' . urlencode('Please upload a valid .ovpn file'));
    exit;
}

$file = $_FILES['ovpn_file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Validate extension
if ($fileExt !== 'ovpn') {
    header('Location: ../servers.php?error=' . urlencode('Only .ovpn files are allowed'));
    exit;
}

// Validate file size (max 5MB)
if ($fileSize > MAX_FILE_SIZE) {
    header('Location: ../servers.php?error=' . urlencode('File size exceeds maximum limit (5MB)'));
    exit;
}

// Read the full content of .ovpn file
$ovpnConfig = file_get_contents($fileTmpName);

// Remove BOM if present
$bom = pack('H*','EFBBBF');
$ovpnConfig = preg_replace("/^$bom/", '', $ovpnConfig);

// Ensure UTF-8
if (!mb_check_encoding($ovpnConfig, 'UTF-8')) {
    $ovpnConfig = mb_convert_encoding($ovpnConfig, 'UTF-8', 'ISO-8859-1');
}

// Normalize line endings
$ovpnConfig = str_replace(["\r\n", "\r"], "\n", $ovpnConfig);

if ($ovpnConfig === false || empty(trim($ovpnConfig))) {
    header('Location: ../servers.php?error=' . urlencode('Failed to read .ovpn file or file is empty'));
    exit;
}

// Basic validation - check if it looks like an OpenVPN config
if (stripos($ovpnConfig, 'client') === false && stripos($ovpnConfig, 'remote') === false) {
    header('Location: ../servers.php?error=' . urlencode('File does not appear to be a valid OpenVPN configuration'));
    exit;
}

// Insert into database
try {
    $db = getDB();
    $stmt = $db->prepare("
        INSERT INTO vpn_servers (server_name, country, flag_url, ovpn_config, status)
        VALUES (?, ?, ?, ?, 'active')
    ");
    
    $stmt->execute([$serverName, $country, $flagUrl ?: null, $ovpnConfig]);
    
    $serverId = $db->lastInsertId();
    
    logActivity("Server uploaded: $serverName (ID: $serverId) by " . $_SESSION['admin_email']);
    
    header('Location: ../servers.php?success=' . urlencode('Server uploaded successfully!'));
    
} catch (PDOException $e) {
    logActivity("Server upload error: " . $e->getMessage(), 'error');
    header('Location: ../servers.php?error=' . urlencode('Database error: Failed to save server'));
}
