<?php
/**
 * dns.php — Servidores DNS: listar, añadir, editar y borrar.
 *
 * Un DNS es una URL base de servidor Xtream (p. ej. título "R4",
 * url "http://newlatam.mx:80"). Las playlists Xtream apuntan a un DNS.
 * Todo se guarda por POST con CSRF y sentencias preparadas.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';

require_login();

$pdo = db();
$flash = '';
$flashType = 'ok';

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

    try {
        if ($action === 'create' || $action === 'update') {
            $title = trim((string) ($_POST['title'] ?? ''));
            $url   = trim((string) ($_POST['url'] ?? ''));

            if ($title === '' || $url === '') {
                $flash = 'Título y URL son obligatorios.';
                $flashType = 'error';
            } else {
                if ($action === 'create') {
                    $ins = $pdo->prepare('INSERT INTO dns (title, url, created_at) VALUES (?, ?, ?)');
                    $ins->execute([$title, $url, now_iso()]);
                    $flash = 'DNS creado.';
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $upd = $pdo->prepare('UPDATE dns SET title = ?, url = ? WHERE id = ?');
                        $upd->execute([$title, $url, $editId]);
                        $flash = 'DNS actualizado.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM dns WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'DNS eliminado.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[dns] ' . $ex->getMessage());
        $flash = 'No se pudo completar la operación.';
        $flashType = 'error';
    }
}

// ¿Editando? Carga la fila a editar para precargar el formulario.
$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT id, title, url FROM dns WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

$dnsList = $pdo->query('SELECT id, title, url, created_at FROM dns ORDER BY title ASC, id ASC')->fetchAll();

$pageTitle = 'Servidores DNS';
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 DNS' : 'Añadir DNS' ?></h2></div>
    <div class="card-body">
        <form method="post" action="dns.php">
            <?= 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-6">
                    <label class="form-label" for="title">Título</label>
                    <input type="text" class="form-control" id="title" name="title" value="<?= e($editing['title'] ?? '') ?>" placeholder="R4" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label" for="url">URL del servidor</label>
                    <input type="text" class="form-control mono" id="url" name="url" value="<?= e($editing['url'] ?? '') ?>" placeholder="http://newlatam.mx:80" required>
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Guardar cambios' : 'Añadir DNS' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="dns.php">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

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

    <?php if (count($dnsList) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">Aún no hay servidores DNS. Añade uno arriba.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Título</th>
                        <th>URL</th>
                        <th>Creado</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($dnsList as $dns): ?>
                        <tr>
                            <td><?= e($dns['title']) ?></td>
                            <td class="mono"><?= e($dns['url']) ?></td>
                            <td class="mono"><?= e($dns['created_at'] ?: '—') ?></td>
                            <td class="text-end actions-row">
                                <a class="btn btn-sm btn-outline-primary" href="dns.php?edit=<?= (int) $dns['id'] ?>"><i class="la la-edit"></i> Editar</a>
                                <form method="post" action="dns.php" onsubmit="return confirm('¿Eliminar este DNS?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $dns['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'; ?>
