<?php
declare(strict_types=1);
require_once __DIR__.'/../app/layout.php';
require_once __DIR__.'/../app/notifications.php';
$u   = require_role('ADMIN');
$pdo = app_pdo();

/* POST */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_verify();
  $act = $_POST['act'] ?? '';

  if ($act === 'create') {
    $title    = trim($_POST['title']    ?? '');
    $body     = trim($_POST['body']     ?? '');
    $roles    = $_POST['roles']         ?? [];
    $link     = trim($_POST['link']     ?? '');
    $pin      = (bool)($_POST['pinned'] ?? false);
    $exp_date = $_POST['expires_at']    ?? null;

    if (!$title || !$roles) json_err('Título y roles son obligatorios.');

    /* Guardar anuncio */
    $pdo->prepare("INSERT INTO announcements
      (admin_id, title, body, link, pinned, expires_at, created_at)
      VALUES(?,?,?,?,?,?,NOW())")
      ->execute([
        (int)$u['id'], $title, $body,
        $link?:null, $pin?1:0,
        $exp_date?:null
      ]);
    $aid = (int)$pdo->lastInsertId();

    /* Guardar relación de roles */
    foreach ($roles as $role) {
      $pdo->prepare("INSERT INTO announcement_roles (announcement_id, role)
        VALUES(?,?)")->execute([$aid, $role]);
    }

    /* Enviar notificaciones push */
    $in = implode(',', array_map(fn($r) => $pdo->quote($r), $roles));
    $uids = $pdo->query("SELECT id FROM users WHERE role IN($in) AND is_active=1")
                ->fetchAll(PDO::FETCH_COLUMN);
    foreach ($uids as $uid) {
      notif_create((int)$uid,'announcement',$title,$body,
        '/sistemaescolar/anuncio.php?id='.$aid,(int)$u['id']);
    }
    json_ok('Anuncio publicado para '.count($uids).' usuario(s).',
            ['announcement_id'=>$aid]);
  }

  if ($act === 'toggle_pin') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('UPDATE announcements SET pinned=1-pinned WHERE id=?')->execute([$id]);
    $pin = (int)$pdo->query("SELECT pinned FROM announcements WHERE id=$id")->fetchColumn();
    json_ok($pin ? 'Anuncio fijado.' : 'Anuncio desfijado.', ['pinned'=>$pin]);
  }

  if ($act === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('DELETE FROM announcements WHERE id=?')->execute([$id]);
    json_ok('Anuncio eliminado.');
  }
}

/* GET */
$page     = max(1,(int)($_GET['page'] ?? 1));
$per_page = 15;
$total    = (int)$pdo->query("SELECT COUNT(*) FROM announcements")->fetchColumn();
$pages    = max(1,(int)ceil($total/$per_page));
$offset   = ($page-1)*$per_page;

$ann = $pdo->query("
  SELECT a.*,
    u.full_name AS autor,
    (SELECT COUNT(*) FROM notifications n
     WHERE n.body=a.body AND n.title=a.title) AS n_sent,
    GROUP_CONCAT(ar.role ORDER BY ar.role SEPARATOR ',') AS roles
  FROM announcements a
  JOIN users u ON u.id=a.admin_id
  LEFT JOIN announcement_roles ar ON ar.announcement_id=a.id
  GROUP BY a.id
  ORDER BY a.pinned DESC, a.created_at DESC
  LIMIT $per_page OFFSET $offset
")->fetchAll();

layout_start('Anuncios', $u);
$csrf = htmlspecialchars(csrf_token());
?>

<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:12px;margin-bottom:20px">
  <div>
    <h2 style="font-size:18px;font-weight:800;color:var(--navy)">📢 Anuncios</h2>
    <p class="txt-muted">Comunicados para docentes y alumnos</p>
  </div>
  <button class="btn btn-navy" onclick="openModal('m-ann')">
    ➕ Nuevo Anuncio
  </button>
</div>

<!-- Lista de anuncios -->
<div style="display:flex;flex-direction:column;gap:10px;margin-bottom:20px">
  <?php foreach ($ann as $a):
    $expired = $a['expires_at'] && strtotime($a['expires_at']) < time();
    $roles_arr = $a['roles'] ? explode(',',$a['roles']) : [];
    $role_icons = ['ADMIN'=>'⚙️','DOCENTE'=>'👨‍🏫','ALUMNO'=>'🎓'];
  ?>
  <div class="ann-card <?= $expired?'ann-expired':'' ?>"
       id="ann-<?= (int)$a['id'] ?>">
    <div style="display:flex;align-items:flex-start;gap:12px">

      <!-- Pin indicator -->
      <div style="font-size:20px;margin-top:2px">
        <?= $a['pinned'] ? '📌' : '📢' ?>
      </div>

      <div style="flex:1;min-width:0">
        <!-- Título + roles -->
        <div style="display:flex;align-items:flex-start;
             justify-content:space-between;gap:8px;flex-wrap:wrap">
          <div>
            <div style="font-size:15px;font-weight:800;color:var(--navy)">
              <?= htmlspecialchars($a['title']) ?>
              <?php if ($a['pinned']): ?>
                <span class="bdg" style="background:#fff3e0;
                      color:var(--orange);font-size:10px;margin-left:6px">
                  Fijado
                </span>
              <?php endif; ?>
              <?php if ($expired): ?>
                <span class="bdg" style="background:#ffebee;
                      color:var(--red);font-size:10px;margin-left:6px">
                  Expirado
                </span>
              <?php endif; ?>
            </div>
            <div style="display:flex;gap:5px;flex-wrap:wrap;margin-top:5px">
              <?php foreach ($roles_arr as $r): ?>
                <span class="bdg" style="font-size:10px">
                  <?= $role_icons[$r] ?? '👤' ?> <?= $r ?>
                </span>
              <?php endforeach; ?>
              <span class="txt-muted" style="font-size:11px">
                · <?= htmlspecialchars($a['autor']) ?>
                · <?= date('d/m/Y H:i', strtotime($a['created_at'])) ?>
                <?php if ($a['expires_at']): ?>
                  · Expira: <?= date('d/m/Y', strtotime($a['expires_at'])) ?>
                <?php endif; ?>
              </span>
            </div>
          </div>
          <div style="display:flex;gap:5px;flex-shrink:0">
            <button class="btn btn-outline btn-xs"
                    onclick="togglePin(<?= (int)$a['id'] ?>)"
                    id="pin-<?= (int)$a['id'] ?>">
              <?= $a['pinned'] ? '📌 Desfijar' : '📌 Fijar' ?>
            </button>
            <button class="btn btn-red btn-xs"
                    onclick="delAnn(<?= (int)$a['id'] ?>)">🗑</button>
          </div>
        </div>

        <!-- Cuerpo -->
        <?php if ($a['body']): ?>
        <div style="margin-top:8px;font-size:13px;color:var(--muted);
             line-height:1.5;border-top:1px solid var(--bg);padding-top:8px">
          <?= nl2br(htmlspecialchars($a['body'])) ?>
        </div>
        <?php endif; ?>

        <!-- Footer -->
        <div style="display:flex;align-items:center;gap:10px;
             margin-top:8px;flex-wrap:wrap">
          <span class="mini-chip">
            📤 Enviado a <?= (int)$a['n_sent'] ?> usuario(s)
          </span>
          <?php if ($a['link']): ?>
            <a href="<?= htmlspecialchars($a['link']) ?>"
               class="txt-muted" style="font-size:11px;
               text-decoration:none">
              🔗 <?= htmlspecialchars($a['link']) ?>
            </a>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (!$ann): ?>
  <div class="card" style="text-align:center;padding:40px;color:var(--muted)">
    <div style="font-size:40px;margin-bottom:10px">📢</div>
    No hay anuncios publicados aún.
  </div>
  <?php endif; ?>
</div>

<!-- PAGINACIÓN -->
<?php if ($pages > 1): ?>
<div style="display:flex;gap:6px;justify-content:center;flex-wrap:wrap">
  <?php for ($p=1; $p<=$pages; $p++): ?>
    <a href="?page=<?= $p ?>"
       class="btn <?= $p===$page?'btn-navy':'btn-outline' ?> btn-sm">
      <?= $p ?>
    </a>
  <?php endfor; ?>
</div>
<?php endif; ?>

<!-- Modal Nuevo Anuncio -->
<div class="modal-ov" id="m-ann">
  <div class="modal" style="max-width:520px">
    <h3>📢 Nuevo Anuncio</h3>
    <form id="f-ann" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="create">

      <div class="fg" style="margin-bottom:12px">
        <label>Título *</label>
        <input name="title" type="text" required
               placeholder="Título del anuncio">
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Mensaje</label>
        <textarea name="body" rows="4"
                  placeholder="Contenido del anuncio..."></textarea>
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Enlace (opcional)</label>
        <input name="link" type="url"
               placeholder="https://...">
      </div>
      <div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:12px">
        <div class="fg" style="flex:1;min-width:140px">
          <label>Expira el</label>
          <input name="expires_at" type="date"
                 min="<?= date('Y-m-d') ?>">
        </div>
        <div style="display:flex;align-items:flex-end;padding-bottom:2px">
          <label style="display:flex;align-items:center;gap:6px;
                 font-size:12px;cursor:pointer;font-weight:400">
            <input type="checkbox" name="pinned" style="width:auto">
            📌 Fijar en el inicio
          </label>
        </div>
      </div>
      <div class="fg" style="margin-bottom:14px">
        <label>Enviar a *</label>
        <div style="display:flex;gap:14px;flex-wrap:wrap;margin-top:4px">
          <?php foreach (['ADMIN'=>'⚙️ Admin','DOCENTE'=>'👨‍🏫 Docentes','ALUMNO'=>'🎓 Alumnos'] as $rv=>$rl): ?>
          <label style="display:flex;align-items:center;gap:6px;
                 font-size:13px;cursor:pointer;font-weight:400">
            <input type="checkbox" name="roles[]" value="<?= $rv ?>"
                   style="width:auto">
            <?= $rl ?>
          </label>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-ann')">Cancelar</button>
        <button type="submit" class="btn btn-navy">📢 Publicar</button>
      </div>
    </form>
  </div>
</div>

<style>
.ann-card{
  background:var(--card);border-radius:var(--r);
  padding:16px 18px;box-shadow:var(--sh);
  transition:var(--tr);border:1.5px solid var(--border)
}
.ann-card:hover{ box-shadow:0 6px 20px rgba(0,0,0,.1) }
.ann-expired{ opacity:.55 }
</style>

<script>
var CSRF='<?= $csrf ?>';
function openModal(id){ document.getElementById(id).classList.add('show'); }
function closeModal(id){ document.getElementById(id).classList.remove('show'); }
document.querySelectorAll('.modal-ov').forEach(function(ov){
  ov.addEventListener('click',function(e){ if(e.target===this) this.classList.remove('show'); });
});

ajaxForm(document.getElementById('f-ann'),function(d){
  closeModal('m-ann');
  toast(d.msg,'ok');
  setTimeout(()=>location.reload(),800);
});

function togglePin(id){
  var fd=new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle_pin'); fd.append('id',id);
  fetch(location.href,{method:'POST',
    headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
  .then(r=>r.json()).then(d=>{
    toast(d.msg,'ok');
    var btn=document.getElementById('pin-'+id);
    if(btn) btn.textContent=d.pinned?'📌 Desfijar':'📌 Fijar';
  });
}

function delAnn(id){
  confirmModal('¿Eliminar este anuncio?',function(){
    var fd=new FormData();
    fd.append('csrf',CSRF); fd.append('act','delete'); fd.append('id',id);
    fetch(location.href,{method:'POST',
      headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,'ok');
      document.getElementById('ann-'+id)?.remove();
    });
  },'🗑️ Eliminar anuncio');
}
</script>
<?php layout_end(); ?>