<?php
// Gestione VPN - sistemata per cPanel.
// Mantiene la gestione singola normale e aggiunge SOLO ZIP di massa nello stesso percorso: api/ovpns/

include('includes/header.php');

$dbPath = __DIR__ . '/api/vpn.db';
$uploadDir = __DIR__ . '/api/ovpns';
if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0755, true); }
if (!file_exists($uploadDir . '/index.php')) { @file_put_contents($uploadDir . '/index.php', '<?php // silence'); }

function vpn_h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function vpn_db() {
    global $dbPath;
    $db = new SQLite3($dbPath);
    $db->exec("CREATE TABLE IF NOT EXISTS vpnconfig(
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        userid TEXT,
        vpn_appid TEXT,
        vpn_country TEXT,
        vpn_state TEXT,
        vpn_config TEXT,
        vpn_status TEXT,
        auth_type TEXT,
        auth_embedded TEXT,
        username TEXT,
        password TEXT,
        date TEXT
    )");
    $cols = [];
    $res = $db->query("PRAGMA table_info(vpnconfig)");
    while ($row = $res->fetchArray(SQLITE3_ASSOC)) { $cols[] = $row['name']; }
    if (!in_array('vdate', $cols, true)) { @$db->exec("ALTER TABLE vpnconfig ADD COLUMN vdate TEXT"); }
    return $db;
}

function vpn_base_url() {
    // Crea URL pubblico del pannello, es: https://gennygenn.com/test9
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['SERVER_PORT'] ?? '') == 443)
        || (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost');
    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/'));
    $scriptDir = trim($scriptDir, '/');
    return rtrim($scheme . '://' . $host . ($scriptDir ? '/' . $scriptDir : ''), '/');
}

function vpn_clean_file($name) {
    $name = basename((string)$name);
    $name = preg_replace('/[^A-Za-z0-9._-]+/', '_', $name);
    $name = trim($name, '._-');
    if ($name === '') { $name = 'vpn_' . time() . '.ovpn'; }
    if (strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== 'ovpn') { $name .= '.ovpn'; }
    return $name;
}

function vpn_state_from_file($file) {
    $name = pathinfo($file, PATHINFO_FILENAME);
    $name = preg_replace('/[_-]+/', ' ', $name);
    return trim($name) ?: 'vpn';
}

function vpn_title_words($text) {
    $text = strtolower(trim((string)$text));
    $text = preg_replace('/[^a-z0-9]+/i', ' ', $text);
    $text = preg_replace('/\s+/', ' ', $text);
    return ucwords($text);
}

function vpn_country_aliases() {
    return [
        'unitedstates' => 'US', 'united-states' => 'US', 'united_states' => 'US', 'usa' => 'US', 'us' => 'US', 'america' => 'US',
        'unitedkingdom' => 'GB', 'united-kingdom' => 'GB', 'united_kingdom' => 'GB', 'uk' => 'GB', 'greatbritain' => 'GB', 'england' => 'GB',
        'ireland' => 'IE', 'italy' => 'IT', 'italia' => 'IT', 'france' => 'FR', 'germany' => 'DE', 'deutschland' => 'DE',
        'spain' => 'ES', 'espana' => 'ES', 'netherlands' => 'NL', 'holland' => 'NL', 'belgium' => 'BE',
        'canada' => 'CA', 'brazil' => 'BR', 'brasil' => 'BR', 'portugal' => 'PT', 'switzerland' => 'CH',
        'sweden' => 'SE', 'norway' => 'NO', 'denmark' => 'DK', 'finland' => 'FI', 'poland' => 'PL',
        'romania' => 'RO', 'austria' => 'AT', 'czech' => 'CZ', 'czechrepublic' => 'CZ', 'czech-republic' => 'CZ',
        'slovakia' => 'SK', 'hungary' => 'HU', 'greece' => 'GR', 'turkey' => 'TR', 'australia' => 'AU',
        'newzealand' => 'NZ', 'new-zealand' => 'NZ', 'japan' => 'JP', 'singapore' => 'SG',
        'india' => 'IN', 'hongkong' => 'HK', 'hong-kong' => 'HK', 'southkorea' => 'KR', 'south-korea' => 'KR',
        'mexico' => 'MX', 'argentina' => 'AR', 'chile' => 'CL', 'colombia' => 'CO', 'peru' => 'PE',
        'israel' => 'IL', 'uae' => 'AE', 'dubai' => 'AE', 'russia' => 'RU', 'ukraine' => 'UA',
        'bulgaria' => 'BG', 'croatia' => 'HR', 'serbia' => 'RS', 'slovenia' => 'SI', 'latvia' => 'LV', 'lithuania' => 'LT', 'estonia' => 'EE',
        'luxembourg' => 'LU', 'iceland' => 'IS', 'malta' => 'MT', 'cyprus' => 'CY', 'southafrica' => 'ZA', 'south-africa' => 'ZA',
        'albania' => 'AL', 'andorra' => 'AD', 'belarus' => 'BY', 'bosnia' => 'BA', 'moldova' => 'MD', 'monaco' => 'MC',
        'georgia' => 'GE', 'armenia' => 'AM', 'azerbaijan' => 'AZ', 'kazakhstan' => 'KZ', 'thailand' => 'TH', 'taiwan' => 'TW',
        'malaysia' => 'MY', 'indonesia' => 'ID', 'philippines' => 'PH', 'vietnam' => 'VN', 'china' => 'CN',
        'egypt' => 'EG', 'morocco' => 'MA', 'nigeria' => 'NG', 'kenya' => 'KE', 'pakistan' => 'PK', 'saudiarabia' => 'SA', 'saudi-arabia' => 'SA'
    ];
}

function vpn_normalize_ovpn_base($file) {
    $base = strtolower(pathinfo($file, PATHINFO_FILENAME));
    $base = preg_replace('/^(udp|tcp|openvpn|ovpn)[-_]*/i', '', $base);
    $base = preg_replace('/^\d+\s*(gb|mb|g|m)[-_]*/i', '', $base);
    $base = preg_replace('/^\d+[-_]?/i', '', $base);
    return trim($base, '-_ .');
}

function vpn_country_state_from_file($file) {
    // Estrae Country ISO2 per la bandiera e Nome/Stato dal nome reale del file .ovpn.
    $base = vpn_normalize_ovpn_base($file);
    $aliases = vpn_country_aliases();
    uksort($aliases, function($a, $b) { return strlen($b) <=> strlen($a); });
    foreach ($aliases as $key => $code) {
        if ($base === $key || strpos($base, $key . '-') === 0 || strpos($base, $key . '_') === 0) {
            $rest = trim(substr($base, strlen($key)), '-_ .');
            $state = $rest !== '' ? vpn_title_words($rest) : vpn_title_words($key);
            return [strtoupper($code), $state];
        }
    }
    $parts = preg_split('/[-_]+/', $base, -1, PREG_SPLIT_NO_EMPTY);
    $state = count($parts) > 1 ? implode(' ', array_slice($parts, 1)) : ($parts[0] ?? 'vpn');
    return ['XX', vpn_title_words($state)];
}

function vpn_flag_emoji($code) {
    $code = strtoupper(trim((string)$code));
    if (!preg_match('/^[A-Z]{2}$/', $code) || $code === 'XX') { return ''; }
    $flag = '';
    for ($i = 0; $i < 2; $i++) {
        $flag .= html_entity_decode('&#' . (127397 + ord($code[$i])) . ';', ENT_NOQUOTES, 'UTF-8');
    }
    return $flag;
}

function vpn_unique_target_name($safeName) {
    global $uploadDir;
    $safeName = vpn_clean_file($safeName);
    $target = $safeName;
    $i = 2;
    $base = pathinfo($safeName, PATHINFO_FILENAME);
    $ext = pathinfo($safeName, PATHINFO_EXTENSION);
    while (file_exists($uploadDir . '/' . $target)) {
        $target = $base . '_' . $i . '.' . $ext;
        $i++;
    }
    return $target;
}

function vpn_insert($data) {
    $db = vpn_db();
    $now = date('Y-m-d H:i:s');
    $stmt = $db->prepare("INSERT INTO vpnconfig(userid, vpn_appid, vpn_country, vpn_state, vpn_config, vpn_status, auth_type, auth_embedded, username, password, date, vdate)
        VALUES(:userid, :vpn_appid, :vpn_country, :vpn_state, :vpn_config, :vpn_status, :auth_type, :auth_embedded, :username, :password, :date, :vdate)");
    $stmt->bindValue(':userid', $data['userid'] ?? '521064', SQLITE3_TEXT);
    $stmt->bindValue(':vpn_appid', $data['vpn_appid'] ?? '1646', SQLITE3_TEXT);
    $stmt->bindValue(':vpn_country', strtoupper($data['vpn_country'] ?? 'XX'), SQLITE3_TEXT);
    $stmt->bindValue(':vpn_state', $data['vpn_state'] ?? 'vpn', SQLITE3_TEXT);
    $stmt->bindValue(':vpn_config', $data['vpn_config'] ?? '', SQLITE3_TEXT);
    $stmt->bindValue(':vpn_status', $data['vpn_status'] ?? 'ACTIVE', SQLITE3_TEXT);
    $stmt->bindValue(':auth_type', $data['auth_type'] ?? 'up', SQLITE3_TEXT);
    $stmt->bindValue(':auth_embedded', $data['auth_embedded'] ?? 'NO', SQLITE3_TEXT);
    $stmt->bindValue(':username', $data['username'] ?? '', SQLITE3_TEXT);
    $stmt->bindValue(':password', $data['password'] ?? '', SQLITE3_TEXT);
    $stmt->bindValue(':date', $now, SQLITE3_TEXT);
    $stmt->bindValue(':vdate', $now, SQLITE3_TEXT);
    return $stmt->execute();
}

function vpn_delete_file_from_url($url) {
    global $uploadDir;
    $path = parse_url((string)$url, PHP_URL_PATH);
    $name = basename($path ?: (string)$url);
    if ($name) {
        $file = $uploadDir . '/' . $name;
        if (is_file($file)) { @unlink($file); }
        if (!preg_match('/\.ovpn$/i', $name) && is_file($file . '.ovpn')) { @unlink($file . '.ovpn'); }
    }
}

function vpn_zip_extract_ovpns($zipTmp, $zipName, $post) {
    global $uploadDir;
    if (strtolower(pathinfo($zipName, PATHINFO_EXTENSION)) !== 'zip') {
        return [0, 'Carica solo file .zip'];
    }

    $tmpExtract = sys_get_temp_dir() . '/vpnzip_' . uniqid('', true);
    @mkdir($tmpExtract, 0755, true);
    $opened = false;

    if (class_exists('ZipArchive')) {
        $zip = new ZipArchive();
        if ($zip->open($zipTmp) === true) {
            $zip->extractTo($tmpExtract);
            $zip->close();
            $opened = true;
        }
    }

    if (!$opened && function_exists('shell_exec')) {
        @shell_exec('unzip -qq ' . escapeshellarg($zipTmp) . ' -d ' . escapeshellarg($tmpExtract) . ' 2>&1');
        $opened = count(glob($tmpExtract . '/*')) > 0;
    }

    if (!$opened) { return [0, 'ZIP non letto. Attiva estensione PHP zip su cPanel oppure controlla che lo ZIP sia valido.']; }

    $count = 0;
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpExtract, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $fileInfo) {
        if (!$fileInfo->isFile()) { continue; }
        if (strtolower($fileInfo->getExtension()) !== 'ovpn') { continue; }

        $safeName = vpn_clean_file($fileInfo->getFilename());
        // Mantiene il nome originale del file dentro lo ZIP. Niente prefissi numerici/data.
        $targetName = vpn_unique_target_name($safeName);
        $targetPath = $uploadDir . '/' . $targetName;

        if (@copy($fileInfo->getPathname(), $targetPath) && is_file($targetPath) && filesize($targetPath) > 0) {
            @chmod($targetPath, 0644);
            // IMPORTANTE: salva il link completo al FILE .ovpn caricato, non solo il dominio.
            $fileUrl = rtrim(vpn_base_url(), '/') . '/api/ovpns/' . str_replace('%2F','/',rawurlencode($targetName));
            [$autoCountry, $autoState] = vpn_country_state_from_file($safeName);
            vpn_insert([
                'userid' => $post['userid'] ?? '521064',
                'vpn_appid' => $post['vpn_appid'] ?? '1646',
                'vpn_country' => $autoCountry,
                'vpn_state' => $autoState,
                'vpn_config' => $fileUrl,
                'vpn_status' => $post['vpn_status'] ?? 'ACTIVE',
                'auth_type' => $post['auth_type'] ?? 'up',
                'auth_embedded' => $post['auth_embedded'] ?? 'NO',
                'username' => $post['username'] ?? '',
                'password' => $post['password'] ?? '',
            ]);
            $count++;
        }
    }

    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpExtract, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($it as $f) { $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname()); }
    @rmdir($tmpExtract);

    return [$count, $count ? ($count . ' file .ovpn caricati in api/ovpns/') : 'ZIP letto, ma non contiene file .ovpn'];
}

$alert = '';
$db = vpn_db();

// Ripara automaticamente righe già importate dallo ZIP che hanno Nome/Stato vuoto o generico.
$fixRows = $db->query("SELECT id, vpn_config, vpn_country, vpn_state FROM vpnconfig");
while ($fr = $fixRows->fetchArray(SQLITE3_ASSOC)) {
    $url = (string)($fr['vpn_config'] ?? '');
    $fname = basename(parse_url($url, PHP_URL_PATH) ?: $url);
    if ($fname && preg_match('/\.ovpn$/i', $fname)) {
        [$cFix, $sFix] = vpn_country_state_from_file($fname);
        $oldCountry = trim((string)($fr['vpn_country'] ?? ''));
        $oldState = trim((string)($fr['vpn_state'] ?? ''));
        $oldStateLower = strtolower($oldState);
        $fnameLower = strtolower(pathinfo($fname, PATHINFO_FILENAME));
        $needsFix = ($oldCountry === '' || strtoupper($oldCountry) === 'XX' || !preg_match('/^[A-Z]{2}$/', strtoupper($oldCountry)) || $oldState === '' || $oldStateLower === 'vpn' || $oldStateLower === $fnameLower);
        foreach (vpn_country_aliases() as $aliasName => $aliasCode) {
            if ($oldStateLower === $aliasName || strpos($oldStateLower, $aliasName . '-') === 0 || strpos($oldStateLower, $aliasName . ' ') === 0 || strpos($oldStateLower, $aliasName . '_') === 0) {
                $needsFix = true;
                break;
            }
        }
        if ($needsFix) {
            $stFix = $db->prepare('UPDATE vpnconfig SET vpn_country=:c, vpn_state=:s WHERE id=:id');
            $stFix->bindValue(':c', strtoupper($cFix), SQLITE3_TEXT);
            $stFix->bindValue(':s', $sFix, SQLITE3_TEXT);
            $stFix->bindValue(':id', (int)$fr['id'], SQLITE3_INTEGER);
            $stFix->execute();
        }
    }
}

if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $row = $db->querySingle('SELECT vpn_status FROM vpnconfig WHERE id=' . $id, true);
    if ($row) {
        $new = strtoupper($row['vpn_status'] ?? '') === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
        $stmt = $db->prepare('UPDATE vpnconfig SET vpn_status=:s WHERE id=:id');
        $stmt->bindValue(':s', $new, SQLITE3_TEXT);
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $stmt->execute();
        $alert = '<div class="alert alert-success">Stato VPN aggiornato.</div>';
    }
}

if (isset($_GET['delete_vpn'])) {
    $id = (int)$_GET['delete_vpn'];
    $row = $db->querySingle('SELECT vpn_config FROM vpnconfig WHERE id=' . $id, true);
    if ($row) {
        vpn_delete_file_from_url($row['vpn_config'] ?? '');
        $stmt = $db->prepare('DELETE FROM vpnconfig WHERE id=:id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $stmt->execute();
        $alert = '<div class="alert alert-success">VPN cancellata.</div>';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['upload_zip_vpn'])) {
        $err = $_FILES['vpn_zip']['error'] ?? UPLOAD_ERR_NO_FILE;
        if ($err !== UPLOAD_ERR_OK) {
            $alert = '<div class="alert alert-danger">ZIP non caricato. Errore upload: ' . vpn_h($err) . '</div>';
        } else {
            [$count, $msg] = vpn_zip_extract_ovpns($_FILES['vpn_zip']['tmp_name'], $_FILES['vpn_zip']['name'], $_POST);
            $alert = '<div class="alert alert-' . ($count ? 'success' : 'warning') . '">' . vpn_h($msg) . '</div>';
        }
    } elseif (isset($_POST['delete_selected_vpn']) && !empty($_POST['vpn_ids']) && is_array($_POST['vpn_ids'])) {
        $deleted = 0;
        foreach ($_POST['vpn_ids'] as $rawId) {
            $id = (int)$rawId;
            if ($id <= 0) { continue; }
            $row = $db->querySingle('SELECT vpn_config FROM vpnconfig WHERE id=' . $id, true);
            if ($row) {
                vpn_delete_file_from_url($row['vpn_config'] ?? '');
                $stmt = $db->prepare('DELETE FROM vpnconfig WHERE id=:id');
                $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
                $stmt->execute();
                $deleted++;
            }
        }
        $alert = '<div class="alert alert-success">VPN selezionate cancellate: ' . (int)$deleted . '</div>';
    } elseif (isset($_POST['delete_all_vpn'])) {
        $rows = $db->query('SELECT vpn_config FROM vpnconfig');
        $deleted = 0;
        while ($r = $rows->fetchArray(SQLITE3_ASSOC)) { vpn_delete_file_from_url($r['vpn_config'] ?? ''); $deleted++; }
        $db->exec('DELETE FROM vpnconfig');
        $alert = '<div class="alert alert-success">Tutte le VPN cancellate: ' . (int)$deleted . '</div>';
    } elseif (isset($_POST['save_single_vpn'])) {
        // Gestione singola semplice/originale: salva il link .ovpn già esistente, senza creare upload file singolo aggiuntivo.
        $vpnConfig = trim($_POST['vpn_config'] ?? '');
        if ($vpnConfig === '') {
            $alert = '<div class="alert alert-danger">Inserisci il link del file .ovpn.</div>';
        } else {
            vpn_insert([
                'userid' => $_POST['userid'] ?? '521064',
                'vpn_appid' => $_POST['vpn_appid'] ?? '1646',
                'vpn_country' => $_POST['vpn_country'] ?? 'XX',
                'vpn_state' => $_POST['vpn_state'] ?? 'vpn',
                'vpn_config' => $vpnConfig,
                'vpn_status' => $_POST['vpn_status'] ?? 'ACTIVE',
                'auth_type' => $_POST['auth_type'] ?? 'up',
                'auth_embedded' => $_POST['auth_embedded'] ?? 'NO',
                'username' => $_POST['username'] ?? '',
                'password' => $_POST['password'] ?? '',
            ]);
            $alert = '<div class="alert alert-success">VPN salvata.</div>';
        }
    }
}

$res = $db->query('SELECT * FROM vpnconfig ORDER BY id DESC');
?>

<div class="row">
    <div class="col-md-12">
        <h2><i class="fa fa-shield"></i> Gestione VPN</h2>
        <?php echo $alert; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header bg-primary text-white"><b>Aggiungi VPN</b></div>
            <div class="card-body">
                <form method="post" enctype="multipart/form-data">
                    <div class="form-row">
                        <div class="form-group col-md-6"><label>User ID</label><input class="form-control" name="userid" value="521064"></div>
                        <div class="form-group col-md-6"><label>App ID</label><input class="form-control" name="vpn_appid" value="1646"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-4"><label>Country</label><input class="form-control" name="vpn_country" value="XX"></div>
                        <div class="form-group col-md-8"><label>Nome/Stato</label><input class="form-control" name="vpn_state" placeholder="esempio: Italy"></div>
                    </div>
                    <div class="form-group"><label>Link configurazione .ovpn</label><input class="form-control" name="vpn_config" placeholder="https://.../file.ovpn"></div>
                    <div class="form-row">
                        <div class="form-group col-md-6"><label>Username</label><input class="form-control" name="username"></div>
                        <div class="form-group col-md-6"><label>Password</label><input class="form-control" name="password"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6"><label>Status</label><select class="form-control" name="vpn_status"><option>ACTIVE</option><option>INACTIVE</option></select></div>
                        <div class="form-group col-md-6"><label>Auth Embedded</label><select class="form-control" name="auth_embedded"><option>NO</option><option>YES</option></select></div>
                    </div>
                    <input type="hidden" name="auth_type" value="up">
                    <button class="btn btn-success" type="submit" name="save_single_vpn" value="1"><i class="fa fa-plus"></i> Salva VPN</button>

                    <hr>
                    <div style="border:1px solid #ffc107;padding:12px;border-radius:8px;background:#fff8e1;">
                        <label><b>Caricamento VPN di massa tramite ZIP</b></label>
                        <input type="file" class="form-control-file" name="vpn_zip" accept=".zip,application/zip,application/x-zip-compressed">
                        <small class="form-text text-muted">Lo ZIP deve contenere file .ovpn. Verranno copiati in api/ovpns/ con il nome originale del file. Country e Nome/Stato vengono compilati automaticamente dal nome del file.</small><br>
                        <button class="btn btn-warning" type="submit" name="upload_zip_vpn" value="1"><i class="fa fa-upload"></i> Carica ZIP VPN di massa</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header"><b>VPN salvate</b></div>
    <div class="card-body table-responsive">
        <form method="post" onsubmit="return confirm('Confermi la cancellazione?');">
            <div class="mb-2">
                <button type="submit" name="delete_selected_vpn" value="1" class="btn btn-danger btn-sm">Cancella VPN selezionate</button>
                <button type="submit" name="delete_all_vpn" value="1" class="btn btn-outline-danger btn-sm" onclick="return confirm('Vuoi cancellare TUTTE le VPN?');">Cancella tutte le VPN</button>
            </div>
            <table id="Dtable" class="table table-striped table-bordered">
                <thead><tr><th><input type="checkbox" onclick="document.querySelectorAll('.vpn-check').forEach(c=>c.checked=this.checked)"></th><th>ID</th><th>Country</th><th>Nome/Stato</th><th>File/Config</th><th>Username</th><th>Password</th><th>Status</th><th>Azioni</th></tr></thead>
                <tbody>
                <?php while ($row = $res->fetchArray(SQLITE3_ASSOC)): ?>
                    <tr>
                        <td><input class="vpn-check" type="checkbox" name="vpn_ids[]" value="<?php echo (int)$row['id']; ?>"></td>
                        <td><?php echo vpn_h($row['id']); ?></td>
                        <?php
                            $vpnUrl = (string)($row['vpn_config'] ?? '');
                            $vpnName = basename(parse_url($vpnUrl, PHP_URL_PATH) ?: $vpnUrl);
                            [$displayCountry, $displayState] = $vpnName ? vpn_country_state_from_file($vpnName) : [($row['vpn_country'] ?? 'XX'), ($row['vpn_state'] ?? '')];
                            if (!preg_match('/^[A-Z]{2}$/', strtoupper((string)$displayCountry)) || strtoupper((string)$displayCountry) === 'XX') { $displayCountry = $row['vpn_country'] ?? 'XX'; }
                            if (trim((string)$displayState) === '') { $displayState = $row['vpn_state'] ?? ''; }
                        ?>
                        <td><?php echo vpn_h(vpn_flag_emoji($displayCountry) . ' ' . strtoupper($displayCountry)); ?></td>
                        <td><?php echo vpn_h($displayState); ?></td>
                        <td style="max-width:320px;word-break:break-all;">
                            <a href="<?php echo vpn_h($vpnUrl); ?>" target="_blank"><?php echo vpn_h($vpnName ?: 'file.ovpn'); ?></a>
                        </td>
                        <td><?php echo vpn_h($row['username']); ?></td>
                        <td><?php echo ($row['password'] ?? '') !== '' ? '••••••••' : ''; ?></td>
                        <td><span class="badge badge-<?php echo strtoupper($row['vpn_status'] ?? '') === 'ACTIVE' ? 'success' : 'secondary'; ?>"><?php echo vpn_h($row['vpn_status']); ?></span></td>
                        <td>
                            <a class="btn btn-sm btn-info" href="vpn.php?toggle=<?php echo (int)$row['id']; ?>">Attiva/Disattiva</a>
                            <a class="btn btn-sm btn-danger" href="vpn.php?delete_vpn=<?php echo (int)$row['id']; ?>" onclick="return confirm('Cancellare questa VPN?');">Cancella</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </form>
    </div>
</div>

<?php include('includes/footer.php'); ?>
