<?php
/**
 * menu_ads.php — Anuncios de menú: listar, añadir, editar y borrar.
 *
 * Un anuncio = título + url + orden (sort). Se exponen a la app en la config
 * del dispositivo (menu_ads[]) y en GET /api/ads, ordenados por sort.
 * 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'] ?? ''));
            $sort  = (int) ($_POST['sort'] ?? 0);

            if ($title === '' || $url === '') {
                $flash = 'Título y URL son obligatorios.';
                $flashType = 'error';
            } else {
                if ($action === 'create') {
                    $ins = $pdo->prepare('INSERT INTO menu_ads (title, url, sort, created_at) VALUES (?, ?, ?, ?)');
                    $ins->execute([$title, $url, $sort, now_iso()]);
                    $flash = 'Anuncio creado.';
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $upd = $pdo->prepare('UPDATE menu_ads SET title = ?, url = ?, sort = ? WHERE id = ?');
                        $upd->execute([$title, $url, $sort, $editId]);
                        $flash = 'Anuncio actualizado.';
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM menu_ads WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'Anuncio eliminado.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[menu_ads] ' . $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, sort FROM menu_ads WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

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

$pageTitle = 'Anuncios';
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 anuncio' : 'Añadir anuncio' ?></h2></div>
    <div class="card-body">
        <form method="post" action="menu_ads.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-5">
                    <label class="form-label" for="title">Título</label>
                    <input type="text" class="form-control" id="title" name="title" value="<?= e($editing['title'] ?? '') ?>" placeholder="Promoción" required>
                </div>
                <div class="col-md-5">
                    <label class="form-label" for="url">URL</label>
                    <input type="text" class="form-control mono" id="url" name="url" value="<?= e($editing['url'] ?? '') ?>" placeholder="https://host/promo.png" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="sort">Orden</label>
                    <input type="number" class="form-control" id="sort" name="sort" value="<?= e((string) ($editing['sort'] ?? '0')) ?>" min="0">
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Guardar cambios' : 'Añadir anuncio' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="menu_ads.php">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header"><h2 class="h6 mb-0"><?= count($ads) ?> anuncio<?= count($ads) === 1 ? '' : 's' ?></h2></div>

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