<?php
/**
 * vpn.php — Servidores VPN (OpenVPN): listar, añadir, editar y borrar.
 *
 * El admin pega la config .ovpn (o sube el archivo). Al guardar se autodetecta
 * host, protocolo y si necesita usuario/clave. País y bandera son opcionales.
 * La app baja los habilitados por api/device/vpn e importa el perfil.
 */

declare(strict_types=1);

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_login();

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

$flash = '';
$flashType = 'ok';

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

    try {
        if ($action === 'create' || $action === 'update') {
            // .ovpn: preferí el archivo subido; si no, el textarea.
            $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 === '') {
                $flash = 'La config .ovpn es obligatoria.';
                $flashType = 'error';
            } else {
                $meta = vpn_parse_ovpn($ovpn);
                if ($name === '') {
                    $name = $meta['name'] !== '' ? $meta['name'] : 'VPN';
                }

                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, $meta['host'], $meta['protocol'],
                        $ovpn, $meta['requires_auth'], $username, $password, $enabled, now_iso(),
                    ]);
                    $flash = 'Servidor VPN creado.';
                } 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, $meta['host'], $meta['protocol'],
                            $ovpn, $meta['requires_auth'], $username, $password, $enabled, $editId,
                        ]);
                        $flash = 'Servidor VPN actualizado.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $pdo->prepare('DELETE FROM vpn_servers WHERE id = ?')->execute([$delId]);
                $flash = 'Servidor VPN eliminado.';
            }
        } elseif ($action === 'toggle') {
            $tid = (int) ($_POST['id'] ?? 0);
            if ($tid > 0) {
                $pdo->prepare('UPDATE vpn_servers SET enabled = 1 - enabled WHERE id = ?')->execute([$tid]);
                $flash = 'Estado actualizado.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[vpn] ' . $ex->getMessage());
        $flash = 'No se pudo completar la operación.';
        $flashType = 'error';
    }
}

// ¿Editando? Carga la fila para precargar el formulario.
$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 = 'Servidores VPN';
require __DIR__ . '/lib/header.php';
?>

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

<div class="card mb-4">
    <div class="card-header"><h2 class="h6 mb-0"><?= $editing ? 'Editar servidor VPN' : 'Añadir servidor VPN' ?></h2></div>
    <div class="card-body">
        <p class="text-body-secondary small mb-3">
            Subí (o pegá) el <code>.ovpn</code> y se detecta host, protocolo y si necesita usuario/clave.
            País y bandera son opcionales.
        </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" for="name">Nombre <span class="text-body-secondary">(auto desde el .ovpn)</span></label>
                    <input type="text" class="form-control" id="name" name="name" value="<?= e($editing['name'] ?? '') ?>" placeholder="Netherlands #1">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="country">País <span class="text-body-secondary">(opcional)</span></label>
                    <input type="text" class="form-control" id="country" name="country" value="<?= e($editing['country'] ?? '') ?>" placeholder="Netherlands">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="flag">Bandera <span class="text-body-secondary">(opcional, emoji o código)</span></label>
                    <input type="text" class="form-control" id="flag" name="flag" value="<?= e($editing['flag'] ?? '') ?>" placeholder="🇳🇱">
                </div>
                <div class="col-12">
                    <label class="form-label" for="ovpn_file">Subir archivo .ovpn</label>
                    <input type="file" class="form-control" id="ovpn_file" name="ovpn_file" accept=".ovpn,.conf,text/plain">
                </div>
                <div class="col-12">
                    <label class="form-label" for="ovpn">Config .ovpn <span class="text-body-secondary">(pegá la config OpenVPN completa)</span></label>
                    <textarea class="form-control mono" 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" for="username">Usuario <span class="text-body-secondary">(opcional)</span></label>
                    <input type="text" class="form-control" id="username" name="username" value="<?= e($editing['username'] ?? '') ?>" autocomplete="off">
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="password">Contraseña <span class="text-body-secondary">(opcional)</span></label>
                    <input type="text" class="form-control" id="password" name="password" value="<?= e($editing['password'] ?? '') ?>" autocomplete="off">
                </div>
                <div class="col-12">
                    <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" for="enabled">Habilitado (visible en la app)</label>
                    </div>
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Guardar cambios' : 'Añadir servidor VPN' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="vpn.php">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header"><h2 class="h6 mb-0"><?= count($vpnList) ?> servidor<?= count($vpnList) === 1 ? '' : 'es' ?></h2></div>

    <?php if (count($vpnList) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">Aún no hay servidores VPN. Añade uno arriba.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Nombre</th>
                        <th>País</th>
                        <th>Host</th>
                        <th>Proto</th>
                        <th>Auth</th>
                        <th>Estado</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($vpnList as $v): ?>
                        <tr>
                            <td><?= e($v['name']) ?></td>
                            <td><?= e(trim(($v['flag'] ?? '') . ' ' . ($v['country'] ?? ''))) ?: '—' ?></td>
                            <td class="mono"><?= e($v['host'] ?: '—') ?></td>
                            <td class="text-uppercase"><?= e($v['protocol']) ?></td>
                            <td><?= ((int) $v['requires_auth']) === 1
                                ? '<span class="badge bg-warning text-dark">user/clave</span>'
                                : '<span class="badge bg-secondary">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-success' : 'btn-outline-secondary' ?>" type="submit">
                                        <?= ((int) $v['enabled']) === 1 ? 'Habilitado' : 'Deshabilitado' ?>
                                    </button>
                                </form>
                            </td>
                            <td class="text-end actions-row">
                                <a class="btn btn-sm btn-outline-primary" href="vpn.php?edit=<?= (int) $v['id'] ?>"><i class="la la-edit"></i> Editar</a>
                                <form method="post" action="vpn.php" onsubmit="return confirm('¿Eliminar este servidor VPN?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $v['id'] ?>">
                                    <button class="btn btn-sm btn-danger" type="submit"><i class="la la-trash"></i> Borrar</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

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