<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../config/conn.php';
av_require_login();

// ── Acciones rápidas (publicar / archivar / borrar) ─────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    av_csrf_verify();
    $id  = (int)($_POST['aviso_id'] ?? 0);
    $act = $_POST['action'] ?? '';

    if ($id && in_array($act, ['publicar','archivar','borrador','eliminar'], true)) {
        if ($act === 'eliminar') {
            $s = $conn->prepare("DELETE FROM av_avisos WHERE id=?");
            $s->bind_param('i', $id);
            $s->execute();
            $s->close();
        } else {
            $estado_map = ['publicar' => 'publicado', 'archivar' => 'archivado', 'borrador' => 'borrador'];
            $nuevo = $estado_map[$act];
            $s = $conn->prepare("UPDATE av_avisos SET estado=? WHERE id=?");
            $s->bind_param('si', $nuevo, $id);
            $s->execute();
            $s->close();
        }
    }
    header('Location: index.php');
    exit;
}

// ── Estadísticas ────────────────────────────────────────────
$stats = [];
$res = $conn->query("SELECT estado, COUNT(*) AS n FROM av_avisos GROUP BY estado");
while ($r = $res->fetch_assoc()) { $stats[$r['estado']] = (int)$r['n']; }
$total = array_sum($stats);

// ── Lista de avisos ─────────────────────────────────────────
$filtro = $_GET['estado'] ?? 'todos';
$sql = "SELECT id, titulo, resumen, fecha_publicacion, estado, created_at
        FROM av_avisos";
if (in_array($filtro, ['borrador','publicado','archivado'], true)) {
    $stmt = $conn->prepare($sql . " WHERE estado=? ORDER BY fecha_publicacion DESC, id DESC");
    $stmt->bind_param('s', $filtro);
    $stmt->execute();
    $avisos = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $avisos = $conn->query($sql . " ORDER BY fecha_publicacion DESC, id DESC")->fetch_all(MYSQLI_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Panel de Avisos · DEMO</title>
  <link rel="stylesheet" href="admin.css">
</head>
<body>
<div class="av-layout">

  <!-- Sidebar -->
  <aside class="av-sidebar">
    <div class="av-sidebar-brand">
      <img src="../img/demoLogo_SinFondo.png" alt="DEMO" style="max-height:36px;margin-bottom:.4rem"
           onerror="this.style.display='none'">
      <div class="av-sidebar-logo">Panel de Avisos</div>
      <div class="av-sidebar-sub">Servicios DEMO</div>
    </div>
    <nav class="av-sidebar-nav">
      <a href="index.php" class="active">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
        Todos los avisos
      </a>
      <a href="editar.php">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Nuevo aviso
      </a>
      <a href="../index.php" target="_blank">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
        Ver sitio
      </a>
    </nav>
    <div class="av-sidebar-footer">
      Sesión: <strong><?= h(av_nombre()) ?></strong><br>
      <a href="logout.php">Cerrar sesión</a>
    </div>
  </aside>

  <!-- Main -->
  <div class="av-main">
    <div class="av-topbar">
      <span class="av-topbar-title">Avisos institucionales</span>
      <div class="av-topbar-actions">
        <a href="editar.php" class="av-btn av-btn--primary">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Nuevo aviso
        </a>
      </div>
    </div>

    <div class="av-content">

      <!-- Estadísticas -->
      <div class="av-stats">
        <div class="av-stat-card">
          <div class="av-stat-num"><?= $total ?></div>
          <div class="av-stat-label">Total de avisos</div>
        </div>
        <div class="av-stat-card">
          <div class="av-stat-num" style="color:var(--av-success)"><?= $stats['publicado'] ?? 0 ?></div>
          <div class="av-stat-label">Publicados</div>
        </div>
        <div class="av-stat-card">
          <div class="av-stat-num" style="color:#856404"><?= $stats['borrador'] ?? 0 ?></div>
          <div class="av-stat-label">Borradores</div>
        </div>
        <div class="av-stat-card">
          <div class="av-stat-num" style="color:var(--av-muted)"><?= $stats['archivado'] ?? 0 ?></div>
          <div class="av-stat-label">Archivados</div>
        </div>
      </div>

      <!-- Filtros -->
      <div class="av-card">
        <div class="av-card-header">
          <h2>Lista de avisos</h2>
          <div style="display:flex;gap:.4rem;flex-wrap:wrap">
            <?php foreach (['todos','publicado','borrador','archivado'] as $f): ?>
              <a href="?estado=<?= $f ?>"
                 class="av-btn av-btn--sm <?= $filtro === $f ? 'av-btn--primary' : 'av-btn--outline' ?>">
                <?= ucfirst($f) ?>
              </a>
            <?php endforeach; ?>
          </div>
        </div>

        <?php if (empty($avisos)): ?>
          <div class="av-card-body">
            <p class="av-text-muted">No hay avisos<?= $filtro !== 'todos' ? " con estado «{$filtro}»" : '' ?>.</p>
          </div>
        <?php else: ?>
          <table class="av-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Título</th>
                <th>Fecha publicación</th>
                <th>Estado</th>
                <th>Acciones</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($avisos as $a): ?>
              <tr>
                <td><?= $a['id'] ?></td>
                <td class="av-td-title">
                  <?= h($a['titulo']) ?>
                  <?php if ($a['resumen']): ?>
                    <div class="av-text-muted" style="font-weight:400"><?= h(mb_substr($a['resumen'],0,80)) ?>…</div>
                  <?php endif; ?>
                </td>
                <td><?= fecha_es($a['fecha_publicacion']) ?></td>
                <td><span class="av-badge av-badge--<?= h($a['estado']) ?>"><?= h($a['estado']) ?></span></td>
                <td>
                  <div style="display:flex;gap:.3rem;flex-wrap:wrap">
                    <a href="editar.php?id=<?= $a['id'] ?>" class="av-btn av-btn--outline av-btn--sm">
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>Editar
                    </a>
                    <a href="preview.php?id=<?= $a['id'] ?>" target="_blank" class="av-btn av-btn--outline av-btn--sm">
                      <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>Vista previa
                    </a>

                    <form method="post" style="display:inline">
                      <?= av_csrf_field() ?>
                      <input type="hidden" name="aviso_id" value="<?= $a['id'] ?>">
                      <?php if ($a['estado'] === 'publicado'): ?>
                        <input type="hidden" name="action" value="borrador">
                        <button type="submit" class="av-btn av-btn--warning av-btn--sm">Despublicar</button>
                      <?php else: ?>
                        <input type="hidden" name="action" value="publicar">
                        <button type="submit" class="av-btn av-btn--success av-btn--sm">Publicar</button>
                      <?php endif; ?>
                    </form>

                    <form method="post" style="display:inline"
                          onsubmit="return confirm('¿Eliminar «<?= h(addslashes($a['titulo'])) ?>»? Esta acción no se puede deshacer.')">
                      <?= av_csrf_field() ?>
                      <input type="hidden" name="aviso_id" value="<?= $a['id'] ?>">
                      <input type="hidden" name="action" value="eliminar">
                      <button type="submit" class="av-btn av-btn--danger av-btn--sm">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>Eliminar
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>

    </div><!-- /av-content -->
  </div><!-- /av-main -->

</div><!-- /av-layout -->
</body>
</html>
