<?php
// preguntas.php
require_once __DIR__ . '/config.php';
$pdo = db();

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

$categorias = ['STOCK'=>'Stock','RADIOSNET'=>'RadiosNet','SITIOS'=>'Sitios','JINGLES'=>'Jingles','OTROS'=>'Otros'];

// Acciones: crear / editar / borrar / toggle activo
$accion = isset($_POST['accion']) ? $_POST['accion'] : '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($accion === 'crear') {
        $cat    = isset($_POST['categoria']) ? trim($_POST['categoria']) : '';
        $titulo = isset($_POST['titulo']) ? trim($_POST['titulo']) : '';
        $texto  = isset($_POST['texto']) ? trim($_POST['texto']) : '';

        if ($cat && $titulo && $texto && isset($categorias[$cat])) {
            $stmt = $pdo->prepare("INSERT INTO preguntas (categoria, titulo, texto, activo) VALUES (?, ?, ?, 1)");
            $stmt->execute([$cat, $titulo, $texto]);
            header("Location: preguntas.php?ok=1"); exit;
        } else {
            header("Location: preguntas.php?err=1"); exit;
        }
    }

    if ($accion === 'editar') {
        $id     = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $cat    = isset($_POST['categoria']) ? trim($_POST['categoria']) : '';
        $titulo = isset($_POST['titulo']) ? trim($_POST['titulo']) : '';
        $texto  = isset($_POST['texto']) ? trim($_POST['texto']) : '';
        $activo = isset($_POST['activo']) ? (int)$_POST['activo'] : 0;
        $activo = ($activo === 1) ? 1 : 0;

        if ($id > 0 && $cat && $titulo && $texto && isset($categorias[$cat])) {
            $stmt = $pdo->prepare("UPDATE preguntas SET categoria=?, titulo=?, texto=?, activo=? WHERE id=?");
            $stmt->execute([$cat, $titulo, $texto, $activo, $id]);
            header("Location: preguntas.php?ok=1"); exit;
        } else {
            header("Location: preguntas.php?err=1"); exit;
        }
    }

    if ($accion === 'borrar') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM preguntas WHERE id=?");
            $stmt->execute([$id]);
        }
        header("Location: preguntas.php?ok=1"); exit;
    }

    if ($accion === 'toggle') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if ($id > 0) {
            $stmt = $pdo->prepare("UPDATE preguntas SET activo = IF(activo=1,0,1) WHERE id=?");
            $stmt->execute([$id]);
        }
        header("Location: preguntas.php?ok=1"); exit;
    }
}

// Filtro por categoría en UI (opcional)
$fCat = isset($_GET['cat']) ? trim($_GET['cat']) : '';
$params = [];
$where = "WHERE 1=1";
if ($fCat !== '' && isset($categorias[$fCat])) {
    $where .= " AND categoria = ?";
    $params[] = $fCat;
}

$stmt = $pdo->prepare("SELECT * FROM preguntas $where ORDER BY categoria ASC, id DESC");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Modo edición
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editRow = null;
if ($editId > 0) {
    $st = $pdo->prepare("SELECT * FROM preguntas WHERE id=? LIMIT 1");
    $st->execute([$editId]);
    $editRow = $st->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Preguntas pregrabadas</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<style>
    body { background:#0f1418; color:#eaeaea; }
    .wrap { max-width: 1100px; margin: 24px auto; padding: 0 16px; }
    .card-dark { background:#182229; border:1px solid #2c3a42; border-radius:12px; }
    .muted { color:#9fb0b8; }
    .badge-cat { border:1px solid rgba(255,255,255,0.18); background:rgba(255,255,255,0.06); }
    .rowline { border-top:1px solid #2c3a42; }
    textarea { min-height: 90px; }
    a { color:#9fe7d8; }
</style>
</head>
<body>
<div class="wrap">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h4 class="mb-0">Preguntas / Mensajes pregrabados</h4>
            <div class="muted" style="font-size:0.95rem;">Se usan en el botón “Pregrabados” del WhatsApp.</div>
        </div>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-light" href="whatsapp.php">&laquo; Volver</a>
        </div>
    </div>

    <?php if (isset($_GET['ok'])): ?>
        <div class="alert alert-success">Cambios guardados.</div>
    <?php elseif (isset($_GET['err'])): ?>
        <div class="alert alert-danger">Faltan datos o categoría inválida.</div>
    <?php endif; ?>

    <div class="card-dark p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center">
            <strong>Filtrar</strong>
            <div class="d-flex gap-2 flex-wrap">
                <a class="btn btn-sm <?= ($fCat===''?'btn-success':'btn-outline-success') ?>" href="preguntas.php">Todas</a>
                <?php foreach ($categorias as $k=>$lbl): ?>
                    <a class="btn btn-sm <?= ($fCat===$k?'btn-success':'btn-outline-success') ?>" href="preguntas.php?cat=<?= h($k) ?>"><?= h($lbl) ?></a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <?php if ($editRow): ?>
        <div class="card-dark p-3 mb-3">
            <h5 class="mb-3">Editar pregunta #<?= (int)$editRow['id'] ?></h5>

            <form method="post">
                <input type="hidden" name="accion" value="editar">
                <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>">

                <div class="row g-2">
                    <div class="col-md-3">
                        <label class="form-label muted">Categoría</label>
                        <select name="categoria" class="form-select" required>
                            <?php foreach ($categorias as $k=>$lbl): ?>
                                <option value="<?= h($k) ?>" <?= ($editRow['categoria']===$k?'selected':'') ?>><?= h($lbl) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label muted">Título</label>
                        <input type="text" name="titulo" class="form-control" value="<?= h($editRow['titulo']) ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label muted">Activo</label>
                        <select name="activo" class="form-select">
                            <option value="1" <?= ((int)$editRow['activo']===1?'selected':'') ?>>Sí</option>
                            <option value="0" <?= ((int)$editRow['activo']===0?'selected':'') ?>>No</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label muted">Texto</label>
                        <textarea name="texto" class="form-control" required><?= h($editRow['texto']) ?></textarea>
                    </div>
                    <div class="col-12 d-flex gap-2">
                        <button class="btn btn-success">Guardar cambios</button>
                        <a class="btn btn-outline-light" href="preguntas.php">Cancelar</a>
                    </div>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div class="card-dark p-3 mb-3">
            <h5 class="mb-3">Agregar nueva pregunta</h5>

            <form method="post">
                <input type="hidden" name="accion" value="crear">

                <div class="row g-2">
                    <div class="col-md-3">
                        <label class="form-label muted">Categoría</label>
                        <select name="categoria" class="form-select" required>
                            <option value="">Elegir...</option>
                            <?php foreach ($categorias as $k=>$lbl): ?>
                                <option value="<?= h($k) ?>"><?= h($lbl) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-9">
                        <label class="form-label muted">Título</label>
                        <input type="text" name="titulo" class="form-control" placeholder="Ej: Consulta SistemaStock" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label muted">Texto</label>
                        <textarea name="texto" class="form-control" placeholder="Escribí el mensaje completo..." required></textarea>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-success">Guardar</button>
                    </div>
                </div>
            </form>
        </div>
    <?php endif; ?>

    <div class="card-dark p-3">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h5 class="mb-0">Listado</h5>
            <div class="muted" style="font-size:0.9rem;">
                Total: <?= (int)count($rows) ?>
            </div>
        </div>

        <div class="rowline mb-2"></div>

        <?php if (!$rows): ?>
            <div class="muted">No hay preguntas cargadas.</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-dark table-striped align-middle mb-0">
                    <thead>
                        <tr>
                            <th style="width:90px;">ID</th>
                            <th style="width:150px;">Categoría</th>
                            <th style="width:220px;">Título</th>
                            <th>Texto</th>
                            <th style="width:110px;">Activo</th>
                            <th style="width:220px;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rows as $r): ?>
                        <tr>
                            <td>#<?= (int)$r['id'] ?></td>
                            <td><span class="badge badge-cat"><?= h($r['categoria']) ?></span></td>
                            <td><?= h($r['titulo']) ?></td>
                            <td><?= h($r['texto']) ?></td>
                            <td><?= ((int)$r['activo']===1) ? 'Sí' : 'No' ?></td>
                            <td class="d-flex gap-2">
                                <a class="btn btn-sm btn-outline-info" href="preguntas.php?edit=<?= (int)$r['id'] ?>">Editar</a>

                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="accion" value="toggle">
                                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                    <button class="btn btn-sm btn-outline-warning" type="submit">
                                        <?= ((int)$r['activo']===1) ? 'Desactivar' : 'Activar' ?>
                                    </button>
                                </form>

                                <form method="post" style="display:inline;" onsubmit="return confirm('¿Borrar esta pregunta?');">
                                    <input type="hidden" name="accion" value="borrar">
                                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                    <button class="btn btn-sm btn-outline-danger" type="submit">Borrar</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

</div>
</body>
</html>
