<?php
/**
 * vpn.php — VPN Servers (OpenVPN): list, add, edit, and delete with NXS Panel dynamic light/dark style.
 */

declare(strict_types=1);

// PHP 8.0 öncesi sürümler için uyumluluk fonksiyonları (Polyfills)
if (!function_exists('str_starts_with')) {
    function str_starts_with(string $haystack, string $needle): bool {
        return $needle === '' || strpos($haystack, $needle) === 0;
    }
}
if (!function_exists('str_ends_with')) {
    function str_ends_with(string $haystack, string $needle): bool {
        return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
    }
}
if (!function_exists('str_contains')) {
    function str_contains(string $haystack, string $needle): bool {
        return $needle === '' || strpos($haystack, $needle) !== false;
    }
}

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/vpn.php';
require_once __DIR__ . '/lib/i18n.php'; // Çoklu dil desteği

require_login();

$pdo = db();
ensure_vpn_schema($pdo);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();
    $action = (string) ($_POST['action'] ?? '');

    try {
        if ($action === 'create' || $action === 'update') {
            $ovpn = trim((string) ($_POST['ovpn'] ?? ''));
            if (isset($_FILES['ovpn_file']) && is_uploaded_file($_FILES['ovpn_file']['tmp_name'] ?? '')) {
                $uploaded = (string) file_get_contents($_FILES['ovpn_file']['tmp_name']);
                if (trim($uploaded) !== '') {
                    $ovpn = trim($uploaded);
                }
            }

            $name     = trim((string) ($_POST['name'] ?? ''));
            $country  = trim((string) ($_POST['country'] ?? ''));
            $flag     = trim((string) ($_POST['flag'] ?? ''));
            $username = trim((string) ($_POST['username'] ?? ''));
            $password = trim((string) ($_POST['password'] ?? ''));
            $enabled  = isset($_POST['enabled']) ? 1 : 0;

            if ($ovpn === '') {
                $_SESSION['flash'] = __('ovpn_required', 'The .ovpn config is required.');
                $_SESSION['flashType'] = 'error';
            } else {
                $meta = vpn_parse_ovpn($ovpn);
                if ($name === '') {
                    $name = !empty($meta['name']) ? $meta['name'] : 'VPN';
                }

                $createdAt = function_exists('now_iso') ? now_iso() : date('Y-m-d H:i:s');
                $host = $meta['host'] ?? '';
                $protocol = $meta['protocol'] ?? 'udp';
                $requiresAuth = !empty($meta['requires_auth']) ? 1 : 0;

                if ($action === 'create') {
                    $ins = $pdo->prepare(
                        'INSERT INTO vpn_servers
                            (name, country, flag, host, protocol, ovpn, requires_auth, username, password, enabled, created_at)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
                    );
                    $ins->execute([
                        $name, $country, $flag, $host, $protocol,
                        $ovpn, $requiresAuth, $username, $password, $enabled, $createdAt
                    ]);
                    $_SESSION['flash'] = __('vpn_created', 'VPN server created successfully.');
                    $_SESSION['flashType'] = 'ok';
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $upd = $pdo->prepare(
                            'UPDATE vpn_servers SET
                                name = ?, country = ?, flag = ?, host = ?, protocol = ?,
                                ovpn = ?, requires_auth = ?, username = ?, password = ?, enabled = ?
                             WHERE id = ?'
                        );
                        $upd->execute([
                            $name, $country, $flag, $host, $protocol,
                            $ovpn, $requiresAuth, $username, $password, $enabled, $editId
                        ]);
                        $_SESSION['flash'] = __('vpn_updated', 'VPN server updated successfully.');
                        $_SESSION['flashType'] = 'ok';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $pdo->prepare('DELETE FROM vpn_servers WHERE id = ?')->execute([$delId]);
                $_SESSION['flash'] = __('vpn_deleted', 'VPN server deleted.');
                $_SESSION['flashType'] = 'ok';
            }
        } elseif ($action === 'toggle') {
            $tid = (int) ($_POST['id'] ?? 0);
            if ($tid > 0) {
                $pdo->prepare('UPDATE vpn_servers SET enabled = 1 - enabled WHERE id = ?')->execute([$tid]);
                $_SESSION['flash'] = __('status_updated', 'Status updated.');
                $_SESSION['flashType'] = 'ok';
            }
        }
    } catch (Throwable $ex) {
        error_log('[vpn] ' . $ex->getMessage());
        $_SESSION['flash'] = __('error_details', 'Error Details: ') . $ex->getMessage();
        $_SESSION['flashType'] = 'error';
    }

    header('Location: vpn.php');
    exit;
}

$flash = $_SESSION['flash'] ?? '';
$flashType = $_SESSION['flashType'] ?? 'ok';
unset($_SESSION['flash'], $_SESSION['flashType']);

$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM vpn_servers WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

$vpnList = $pdo->query('SELECT * FROM vpn_servers ORDER BY country ASC, name ASC, id ASC')->fetchAll();

$pageTitle = __('vpn_servers', 'VPN Servers') . '';
require __DIR__ . '/lib/header.php';
?>

<!-- NXS Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }

    .glass-card-body {
        padding: 24px;
    }

    .glass-input {
        background: #f9fafb !important;
        border: 1px solid #d1d5db !important;
        color: #111827 !important;
        border-radius: 10px !important;
        padding: 11px 16px !important;
        font-size: 14px !important;
        transition: all 0.25s ease !important;
    }

    .glass-input:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 10px rgba(124, 58, 237, 0.2) !important;
        background: #ffffff !important;
    }

    .glass-alert-success {
        background: #ecfdf5;
        border: 1px solid #a7f3d0;
        color: #059669;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .glass-alert-danger {
        background: #fef2f2;
        border: 1px solid #fecaca;
        color: #dc2626;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .titan-table {
        margin-bottom: 0;
        color: #1f2937;
    }

    .titan-table th {
        font-size: 0.75rem;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #4b5563;
        background: #f8fafc;
        border-bottom: 2px solid #e5e7eb;
        padding: 14px 24px;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table td {
        border-bottom: 1px solid #f3f4f6;
        padding: 16px 24px;
        vertical-align: middle;
        font-size: 0.9rem;
        color: #374151;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table tbody tr:hover {
        background: #fdfdfd;
    }

    .code-badge {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6;
        padding: 4px 10px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        color: #7c3aed;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .badge-auth-yes {
        background: #fffbeb;
        color: #d97706;
        border: 1px solid #fde68a;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
    }

    .badge-auth-no {
        background: #f3f4f6;
        color: #6b7280;
        border: 1px solid #e5e7eb;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 11px;
    }

    /* Yazılı ve Renkli Aksiyon Butonları */
    .btn-action-text {
        padding: 6px 12px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        border-radius: 8px;
        border: none;
        color: #fff;
        font-size: 13px;
        font-weight: 600;
        transition: opacity 0.2s;
        text-decoration: none;
    }

    .btn-action-text:hover {
        opacity: 0.85;
        color: #fff;
    }

    .btn-submit-main {
        background: #7c3aed;
        border: none;
        color: #fff;
        padding: 10px 24px;
        border-radius: 10px;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.2s ease;
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.25);
    }
    .btn-submit-main:hover {
        background: #6d28d9;
        color: #fff;
        transform: translateY(-1px);
    }

    .actions-group {
        display: inline-flex;
        gap: 6px;
        align-items: center;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-card-header {
        background: #141122 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header h2 {
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input:focus {
        background: #171426 !important;
        border-color: #7c3aed !important;
    }

    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important;
        color: #9ca3af !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important;
        color: #f3f4f6 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02) !important;
    }

    [data-bs-theme="dark"] .code-badge {
        background: rgba(255, 255, 255, 0.05) !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #a78bfa !important;
    }

    [data-bs-theme="dark"] .badge-auth-yes {
        background: rgba(217, 119, 6, 0.15);
        color: #fbbf24;
        border-color: rgba(217, 119, 6, 0.3);
    }

    [data-bs-theme="dark"] .badge-auth-no {
        background: rgba(255, 255, 255, 0.05);
        color: #9ca3af;
        border-color: rgba(255, 255, 255, 0.1);
    }

    [data-bs-theme="dark"] .badge.bg-light {
        background: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
        border-color: rgba(255, 255, 255, 0.15) !important;
    }

    [data-bs-theme="dark"] .text-muted {
        color: #9ca3af !important;
    }

    [data-bs-theme="dark"] .text-dark {
        color: #f3f4f6 !important;
    }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 fw-bold text-dark"><?= __('vpn_servers', 'VPN Servers') ?></h1>
</div>

<?php if ($flash !== ''): ?>
    <div class="mb-4 <?= $flashType === 'ok' ? 'glass-alert-success' : 'glass-alert-danger' ?>" role="alert">
        <?= e($flash) ?>
    </div>
<?php endif; ?>

<!-- Add / Edit VPN Form Card -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2><?= $editing ? __('edit_vpn', 'Edit VPN Server') : __('add_vpn', 'Add New VPN Server') ?></h2>
    </div>
    <div class="glass-card-body">
        <p class="text-muted fs-7 mb-4">
            <?= __('vpn_upload_hint', 'Upload (or paste) the .ovpn config and host, protocol, and auth requirements will be detected automatically. Country and flag are optional.') ?>
        </p>
        <form method="post" action="vpn.php" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="<?= $editing ? 'update' : 'create' ?>">
            <?php if ($editing): ?>
                <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
            <?php endif; ?>
            
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="name"><?= __('name', 'Name') ?> <span class="text-muted fw-normal">(auto from .ovpn)</span></label>
                    <input type="text" class="form-control glass-input" id="name" name="name" value="<?= e($editing['name'] ?? '') ?>" placeholder="Netherlands #1">
                </div>
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="country"><?= __('country', 'Country') ?> <span class="text-muted fw-normal">(optional)</span></label>
                    <input type="text" class="form-control glass-input" id="country" name="country" value="<?= e($editing['country'] ?? '') ?>" placeholder="Netherlands">
                </div>
                <div class="col-md-4">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="flag"><?= __('flag', 'Flag') ?> <span class="text-muted fw-normal">(optional, emoji or code)</span></label>
                    <input type="text" class="form-control glass-input" id="flag" name="flag" value="<?= e($editing['flag'] ?? '') ?>" placeholder="🇳🇱">
                </div>
                <div class="col-12">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="ovpn_file"><?= __('upload_ovpn', 'Upload .ovpn file') ?></label>
                    <input type="file" class="form-control glass-input" id="ovpn_file" name="ovpn_file" accept=".ovpn,.conf,text/plain">
                </div>
                <div class="col-12">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="ovpn"><?= __('config_ovpn', 'Config .ovpn') ?> <span class="text-muted fw-normal">(paste full OpenVPN config)</span></label>
                    <textarea class="form-control glass-input code-badge w-100" id="ovpn" name="ovpn" rows="8" placeholder="client&#10;dev tun&#10;proto udp&#10;remote vpn.example.com 1194&#10;..."><?= e($editing['ovpn'] ?? '') ?></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="username"><?= __('username', 'Username') ?> <span class="text-muted fw-normal">(optional)</span></label>
                    <input type="text" class="form-control glass-input" id="username" name="username" value="<?= e($editing['username'] ?? '') ?>" autocomplete="off">
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="password"><?= __('password', 'Password') ?> <span class="text-muted fw-normal">(optional)</span></label>
                    <input type="text" class="form-control glass-input" id="password" name="password" value="<?= e($editing['password'] ?? '') ?>" autocomplete="off">
                </div>
                <div class="col-12 pt-2">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="enabled" name="enabled" value="1" <?= (!$editing || (int) $editing['enabled'] === 1) ? 'checked' : '' ?>>
                        <label class="form-check-label text-muted fs-7 ms-1" for="enabled"><?= __('enabled_in_app', 'Enabled (visible in the app)') ?></label>
                    </div>
                </div>
            </div>

            <div class="mt-4 d-flex gap-2">
                <button class="btn btn-submit-main" type="submit"><?= $editing ? __('save_changes', 'Save Changes') : __('add_vpn_btn', 'Add VPN Server') ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="vpn.php"><?= __('cancel', 'Cancel') ?></a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- VPN Servers List Table Card -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2><?= count($vpnList) ?> <?= count($vpnList) === 1 ? __('vpn_configured', 'VPN Server Configured') : __('vpns_configured', 'VPN Servers Configured') ?></h2>
    </div>

    <?php if (count($vpnList) === 0): ?>
        <div class="p-5 text-center">
            <i class="la la-shield fs-1 text-muted d-block mb-2"></i>
            <p class="text-muted mb-0"><?= __('no_vpn_servers', 'No VPN servers added yet. Add one using the form above.') ?></p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table align-middle titan-table text-nowrap">
                <thead>
                    <tr>
                        <th><?= __('name', 'Name') ?></th>
                        <th><?= __('country', 'Country') ?></th>
                        <th><?= __('host', 'Host') ?></th>
                        <th><?= __('proto', 'Proto') ?></th>
                        <th><?= __('auth', 'Auth') ?></th>
                        <th><?= __('status', 'Status') ?></th>
                        <th class="text-end"><?= __('actions', 'Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($vpnList as $v): ?>
                        <tr>
                            <td><strong class="text-dark fs-6"><?= e($v['name']) ?></strong></td>
                            <td><?= e(trim(($v['flag'] ?? '') . ' ' . ($v['country'] ?? ''))) ?: '—' ?></td>
                            <td><span class="code-badge"><?= e($v['host'] ?: '—') ?></span></td>
                            <td><span class="badge bg-light text-dark border text-uppercase px-2 py-1"><?= e($v['protocol']) ?></span></td>
                            <td>
                                <?= ((int) $v['requires_auth']) === 1
                                    ? '<span class="badge-auth-yes">user/pass</span>'
                                    : '<span class="badge-auth-no">no</span>' ?>
                            </td>
                            <td>
                                <form method="post" action="vpn.php" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="id" value="<?= (int) $v['id'] ?>">
                                    <button class="btn btn-sm <?= ((int) $v['enabled']) === 1 ? 'btn-action-text bg-success' : 'btn-action-text bg-secondary' ?>" type="submit" style="padding: 4px 10px; font-size: 11px;">
                                        <?= ((int) $v['enabled']) === 1 ? __('enabled', 'Enabled') : __('disabled', 'Disabled') ?>
                                    </button>
                                </form>
                            </td>
                            <td class="text-end">
                                <div class="actions-group">
                                    <!-- Edit Butonu (Sarı/Turuncu) -->
                                    <a class="btn-action-text" style="background-color: #f59e0b;" href="vpn.php?edit=<?= (int) $v['id'] ?>">
                                        <i class="la la-edit"></i> <?= __('edit', 'Edit') ?>
                                    </a>
                                    <!-- Delete Butonu (Kırmızı) -->
                                    <form method="post" action="vpn.php" onsubmit="return confirm('<?= __('confirm_delete_vpn', 'Are you sure you want to delete this VPN server?') ?>');" class="d-inline m-0">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int) $v['id'] ?>">
                                        <button class="btn-action-text bg-danger" type="submit">
                                            <i class="la la-trash"></i> <?= __('delete', 'Delete') ?>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>