<?php
/* ═══════════════════════════════════════════════════════════
   LAYOUT PRINCIPAL — Incluir al inicio de toda vista
   ═══════════════════════════════════════════════════════════ */
declare(strict_types=1);
require_once __DIR__.'/db.php';
require_once __DIR__.'/auth.php';
require_once __DIR__.'/config_system.php';
require_once __DIR__.'/notifications.php';

function has_perm(string $role, string $perm): bool {
  return (bool)sys_cfg("perm_{$role}_{$perm}", true);
}

function layout_start(string $title, array $u): void {
  $unread    = notif_unread_count((int)$u['id']);
  $siteName  = sys_cfg('site_name','Sistema Escolar');
  $favicon   = sys_cfg('site_favicon','📚');
  $sideItems = sidebar_items($u['role']);
  $csrf      = htmlspecialchars(csrf_token());
  $poll_ms   = (int)sys_cfg('notif_poll_ms', 30000);
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title><?= htmlspecialchars($title) ?> — <?= htmlspecialchars($siteName) ?></title>
  <meta name="robots" content="noindex,nofollow">
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'
        viewBox='0 0 100 100'><text y='.9em' font-size='90'><?= $favicon ?></text></svg>">
  <style>
  :root{
    --navy:#0d1b6e;--navy-dk:#080f42;--teal:#00796b;--green:#2e7d32;
    --orange:#e65100;--red:#c62828;--sky:#1565c0;--purple:#6a1b9a;
    --muted:#607d8b;--text:#1a1a2e;--bg:#f5f6fa;--card:#ffffff;
    --border:#e0e3ef;--r:12px;--sh:0 2px 12px rgba(0,0,0,.07);
    --tr:all .2s ease;--font:'Segoe UI',system-ui,-apple-system,sans-serif
  }
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
  body{font-family:var(--font);background:var(--bg);color:var(--text);
       min-height:100vh;display:flex;flex-direction:column}
  .topbar{position:sticky;top:0;z-index:1000;background:var(--navy);color:#fff;
    height:56px;display:flex;align-items:center;padding:0 18px;gap:12px;
    box-shadow:0 2px 10px rgba(0,0,0,.2)}
  .topbar-brand{font-size:16px;font-weight:800;letter-spacing:.3px;
    white-space:nowrap;text-decoration:none;color:#fff}
  .topbar-brand span{opacity:.7;font-size:13px;font-weight:400;margin-left:6px}
  .topbar-right{margin-left:auto;display:flex;align-items:center;gap:8px}
  .notif-btn{position:relative;background:rgba(255,255,255,.12);border:none;
    border-radius:10px;padding:7px 10px;color:#fff;cursor:pointer;
    transition:var(--tr);font-size:16px;line-height:1}
  .notif-btn:hover{background:rgba(255,255,255,.22)}
  .notif-badge{position:absolute;top:-5px;right:-5px;background:var(--red);
    color:#fff;border-radius:20px;font-size:10px;font-weight:800;padding:2px 5px;
    min-width:18px;text-align:center;display:none;border:2px solid var(--navy)}
  .notif-badge.show{display:block}
  .notif-dropdown{position:absolute;top:100%;right:0;width:340px;max-height:480px;
    background:var(--card);border-radius:var(--r);box-shadow:0 8px 32px rgba(0,0,0,.18);
    border:1.5px solid var(--border);overflow:hidden;display:none;z-index:2000;margin-top:8px}
  .notif-dropdown.show{display:flex;flex-direction:column}
  .nd-head{display:flex;align-items:center;justify-content:space-between;
    padding:12px 14px;border-bottom:1px solid var(--border);background:var(--bg);flex-shrink:0}
  .nd-title{font-size:13px;font-weight:800;color:var(--navy)}
  .nd-list{overflow-y:auto;flex:1}
  .nd-item{display:flex;align-items:flex-start;gap:10px;padding:11px 14px;
    border-bottom:1px solid var(--bg);text-decoration:none;color:var(--text);
    transition:var(--tr);cursor:pointer}
  .nd-item:hover,.nd-item.unread{background:#f0f4ff}
  .nd-item.unread::before{content:'';width:7px;height:7px;border-radius:50%;
    background:var(--sky);flex-shrink:0;margin-top:5px}
  .nd-ic{font-size:20px;flex-shrink:0;width:32px;height:32px;border-radius:8px;
    display:flex;align-items:center;justify-content:center}
  .nd-body{flex:1;min-width:0}
  .nd-ntitle{font-size:12px;font-weight:700;color:var(--navy);line-height:1.3}
  .nd-nbody{font-size:11px;color:var(--muted);margin-top:2px;overflow:hidden;
    display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
  .nd-time{font-size:10px;color:var(--muted);margin-top:4px}
  .nd-del{opacity:0;transition:var(--tr);background:none;border:none;
    color:var(--red);cursor:pointer;font-size:14px;flex-shrink:0;padding:4px}
  .nd-item:hover .nd-del{opacity:1}
  .nd-footer{display:flex;align-items:center;justify-content:space-between;
    padding:10px 14px;border-top:1px solid var(--border);background:var(--bg);flex-shrink:0}
  .nd-empty{text-align:center;padding:30px 14px;color:var(--muted);font-size:13px}
  .layout-wrap{display:flex;flex:1;min-height:0}
  .sidebar{width:220px;background:var(--card);border-right:1.5px solid var(--border);
    flex-shrink:0;overflow-y:auto;padding:12px 10px}
  .sb-section{font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;
    letter-spacing:.5px;padding:8px 8px 4px}
  .sb-item{display:flex;align-items:center;gap:9px;padding:9px 10px;border-radius:9px;
    text-decoration:none;color:var(--text);font-size:13px;font-weight:500;
    transition:var(--tr);margin-bottom:2px}
  .sb-item:hover{background:var(--bg);color:var(--navy)}
  .sb-item.active{background:#e8eaf6;color:var(--navy);font-weight:700}
  .sb-ic{font-size:16px;width:22px;text-align:center;flex-shrink:0}
  .sb-badge{margin-left:auto;background:var(--red);color:#fff;border-radius:20px;
    font-size:10px;font-weight:700;padding:1px 6px}
  .main-content{flex:1;padding:20px 22px;overflow-y:auto;
    max-width:1300px;width:100%;min-width:0}
  .card{background:var(--card);border-radius:var(--r);box-shadow:var(--sh);
    padding:16px 18px;margin-bottom:14px}
  .card-title{font-size:14px;font-weight:800;color:var(--navy);margin-bottom:14px;
    padding-bottom:10px;border-bottom:2px solid var(--bg)}
  .stats-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));
    gap:12px;margin-bottom:14px}
  .stat-card{background:var(--card);border-radius:var(--r);padding:14px;
    box-shadow:var(--sh);border-top:4px solid var(--navy)}
  .sv{font-size:28px;font-weight:800;color:var(--navy);line-height:1}
  .sl{font-size:11px;color:var(--muted);margin-top:4px;font-weight:600}
  .table-wrap{overflow-x:auto;border-radius:var(--r)}
  table{width:100%;border-collapse:collapse;font-size:13px}
  th{background:var(--bg);color:var(--navy);font-size:11px;font-weight:700;
    text-transform:uppercase;letter-spacing:.4px;padding:10px 12px;
    text-align:left;white-space:nowrap}
  td{padding:10px 12px;border-bottom:1px solid var(--bg);vertical-align:middle}
  tr:last-child td{border-bottom:none}
  tr:hover td{background:#f8faff}
  .tabs{display:flex;gap:4px;flex-wrap:wrap;border-bottom:2px solid var(--border);
    margin-bottom:16px;padding-bottom:0}
  .tab{padding:9px 16px;border-radius:8px 8px 0 0;text-decoration:none;font-size:13px;
    font-weight:600;color:var(--muted);transition:var(--tr);
    border:1.5px solid transparent;border-bottom:none;margin-bottom:-2px}
  .tab:hover{background:var(--bg);color:var(--navy)}
  .tab.on{background:var(--card);color:var(--navy);border-color:var(--border);font-weight:700}
  .btn{display:inline-flex;align-items:center;gap:5px;padding:9px 16px;border-radius:8px;
    font-size:13px;font-weight:600;border:none;cursor:pointer;text-decoration:none;
    transition:var(--tr);white-space:nowrap;line-height:1.2}
  .btn:hover{filter:brightness(1.08)}
  .btn:disabled{opacity:.5;cursor:default}
  .btn-navy{background:var(--navy);color:#fff}
  .btn-teal{background:var(--teal);color:#fff}
  .btn-green{background:var(--green);color:#fff}
  .btn-orange{background:var(--orange);color:#fff}
  .btn-red{background:var(--red);color:#fff}
  .btn-outline{background:transparent;color:var(--navy);border:1.5px solid var(--border)}
  .btn-outline:hover{background:var(--bg);border-color:var(--navy)}
  .btn-sm{padding:7px 12px;font-size:12px}
  .btn-xs{padding:5px 9px;font-size:11px;border-radius:6px}
  .bdg{display:inline-flex;align-items:center;padding:3px 9px;border-radius:20px;
    font-size:11px;font-weight:700}
  .bdg-on{background:#e8f5e9;color:var(--green)}
  .bdg-off{background:#ffebee;color:var(--red)}
  .bdg-info{background:#e3f2fd;color:var(--sky)}
  .bdg-late{background:#fff3e0;color:var(--orange)}
  .grade-badge{display:inline-flex;align-items:baseline;gap:3px;padding:6px 14px;
    border-radius:10px;font-size:20px;font-weight:800;background:#e8f5e9;color:var(--green)}
  .grade-badge.warn{background:#fff3e0;color:var(--orange)}
  .grade-badge.fail{background:#ffebee;color:var(--red)}
  .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
  @media(max-width:560px){.form-grid{grid-template-columns:1fr}}
  .fg{display:flex;flex-direction:column;gap:5px}
  .fg label{font-size:12px;font-weight:700;color:var(--navy)}
  input,select,textarea{padding:9px 12px;border:1.5px solid var(--border);
    border-radius:8px;font-size:13px;font-family:var(--font);background:var(--card);
    color:var(--text);transition:var(--tr);width:100%}
  input:focus,select:focus,textarea:focus{border-color:var(--navy);outline:none;
    box-shadow:0 0 0 3px rgba(13,27,110,.08)}
  textarea{resize:vertical;min-height:80px}
  .drop-zone{border:2px dashed var(--border);border-radius:var(--r);padding:22px;
    text-align:center;cursor:pointer;transition:var(--tr);background:var(--bg)}
  .drop-zone:hover,.drop-zone.over{border-color:var(--navy);background:#e8eaf6}
  .dz-ic{font-size:28px;margin-bottom:6px}
  .dz-txt{font-size:13px;color:var(--muted)}
  .dz-name{font-size:12px;color:var(--navy);font-weight:700;margin-top:4px}
  .up-prog{display:flex;align-items:center;gap:10px;margin-top:10px}
  .prog-bar{flex:1;background:#e0e0e0;border-radius:20px;height:6px;overflow:hidden}
  .prog-fill{height:100%;width:0;background:var(--navy);border-radius:20px;
    transition:width .3s ease}
  .up-lbl{font-size:11px;color:var(--muted);min-width:32px}
  .modal-ov{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:3000;
    display:flex;align-items:center;justify-content:center;padding:20px;
    opacity:0;pointer-events:none;transition:opacity .2s}
  .modal-ov.show{opacity:1;pointer-events:all}
  .modal{background:var(--card);border-radius:var(--r);padding:24px;width:100%;
    max-height:90vh;overflow-y:auto;box-shadow:0 12px 40px rgba(0,0,0,.22)}
  .modal h3{font-size:16px;font-weight:800;color:var(--navy);margin-bottom:16px}
  .modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:18px;
    padding-top:14px;border-top:1px solid var(--bg)}
  #toast-wrap{position:fixed;bottom:20px;right:20px;z-index:9999;
    display:flex;flex-direction:column;gap:8px}
  .toast{display:flex;align-items:center;gap:10px;padding:12px 16px;border-radius:10px;
    font-size:13px;font-weight:600;box-shadow:0 4px 20px rgba(0,0,0,.18);
    animation:slideUp .3s ease;min-width:220px;max-width:340px;backdrop-filter:blur(6px)}
  .toast.ok{background:#e8f5e9;color:var(--green);border-left:4px solid var(--green)}
  .toast.err{background:#ffebee;color:var(--red);border-left:4px solid var(--red)}
  .toast.inf{background:#e3f2fd;color:var(--sky);border-left:4px solid var(--sky)}
  @keyframes slideUp{from{transform:translateY(20px);opacity:0}to{transform:translateY(0);opacity:1}}
  #confirm-ov{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:4000;
    display:flex;align-items:center;justify-content:center;padding:20px;
    opacity:0;pointer-events:none;transition:opacity .2s}
  #confirm-ov.show{opacity:1;pointer-events:all}
  #confirm-box{background:var(--card);border-radius:var(--r);padding:24px;
    max-width:380px;width:100%;box-shadow:0 12px 40px rgba(0,0,0,.22)}
  #confirm-title{font-size:15px;font-weight:800;color:var(--navy);margin-bottom:10px}
  #confirm-msg{font-size:13px;color:var(--muted);margin-bottom:18px}
  .dash-card{display:flex;flex-direction:column;align-items:flex-start;
    background:var(--card);border-radius:var(--r);padding:14px;box-shadow:var(--sh);
    text-decoration:none;color:var(--text);border-top:4px solid var(--navy);
    transition:var(--tr)}
  .dash-card:hover{transform:translateY(-3px);box-shadow:0 8px 24px rgba(0,0,0,.12)}
  .dash-card .ic{font-size:26px;margin-bottom:6px}
  .dash-card .lb{font-size:13px;font-weight:700;color:var(--navy)}
  .dash-card .ds{font-size:11px;color:var(--muted);margin-top:2px}
  .txt-muted{color:var(--muted);font-size:12px}
  .hidden{display:none!important}
  .tbl-head{display:flex;align-items:center;justify-content:space-between;
    flex-wrap:wrap;gap:8px;margin-bottom:14px}
  .tbl-search{display:flex;align-items:center;gap:6px;border:1.5px solid var(--border);
    border-radius:8px;padding:7px 12px;background:var(--card)}
  .tbl-search input{border:none;outline:none;font-size:13px;
    background:transparent;width:180px}
  .tbl-sico{font-size:14px;color:var(--muted)}
  .spinner{display:inline-block;width:14px;height:14px;
    border:2px solid rgba(255,255,255,.3);border-top-color:#fff;
    border-radius:50%;animation:spin .6s linear infinite}
  @keyframes spin{to{transform:rotate(360deg)}}
  .task-item{display:block;padding:10px 12px;border-radius:9px;background:var(--bg);
    text-decoration:none;color:var(--text);transition:var(--tr);margin-bottom:6px;
    border-left:3px solid var(--navy)}
  .task-item:hover{background:#e8eaf6}
  .task-item.due-today{border-left-color:var(--orange)}
  .ti-title{font-size:13px;font-weight:700;color:var(--navy)}
  .ti-sub{font-size:11px;color:var(--muted);margin-top:2px}
  @media(max-width:768px){
    .sidebar{display:none}
    .main-content{padding:14px}
    .topbar-brand span{display:none}
  }
  </style>
</head>
<body>

<nav class="topbar">
  <button onclick="document.querySelector('.sidebar').classList.toggle('show-mobile')"
          style="background:none;border:none;color:#fff;font-size:22px;
                 cursor:pointer;display:none" id="mob-menu">☰</button>
  <a href="/sistemaescolar/<?= strtolower($u['role']) ?>/index.php" class="topbar-brand">
    <?= htmlspecialchars($favicon) ?>
    <?= htmlspecialchars($siteName) ?>
    <span><?= htmlspecialchars($u['role']) ?></span>
  </a>
  <div class="topbar-right">
    <?php if (sys_cfg('notif_enabled', true)): ?>
    <div style="position:relative">
      <button class="notif-btn" id="notif-btn" onclick="toggleNotif()" title="Notificaciones">
        🔔
        <span class="notif-badge <?= $unread > 0 ? 'show' : '' ?>" id="notif-count">
          <?= $unread > 0 ? ($unread > 99 ? '99+' : $unread) : '' ?>
        </span>
      </button>
      <div class="notif-dropdown" id="notif-dd">
        <div class="nd-head">
          <div class="nd-title">🔔 Notificaciones
            <span id="nd-unread-lbl" style="color:var(--muted);font-weight:400">
              <?= $unread ? "($unread sin leer)" : '' ?>
            </span>
          </div>
          <div style="display:flex;gap:6px">
            <button class="btn btn-outline btn-xs" onclick="markAllRead()">✅ Todas leídas</button>
            <button class="btn btn-outline btn-xs" onclick="deleteAllRead()">🗑 Limpiar</button>
          </div>
        </div>
        <div class="nd-list" id="nd-list">
          <div class="nd-empty" id="nd-loading">
            <span class="spinner" style="border-color:var(--border);
              border-top-color:var(--navy);width:20px;height:20px"></span>
          </div>
        </div>
        <div class="nd-footer">
          <a href="/sistemaescolar/notificaciones.php"
             style="font-size:12px;color:var(--sky);text-decoration:none">Ver todas →</a>
          <span id="nd-ts" style="font-size:10px;color:var(--muted)"></span>
        </div>
      </div>
    </div>
    <?php endif; ?>
    <div style="display:flex;align-items:center;gap:8px">
      <div style="width:32px;height:32px;border-radius:50%;background:rgba(255,255,255,.2);
           display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700">
        <?= mb_strtoupper(mb_substr($u['full_name'],0,1)) ?>
      </div>
    </div>
    <a href="/sistemaescolar/logout.php"
       style="color:rgba(255,255,255,.7);font-size:12px;text-decoration:none;
              padding:6px 10px;border-radius:8px;border:1px solid rgba(255,255,255,.2);
              transition:var(--tr)"
       onmouseover="this.style.background='rgba(255,255,255,.15)'"
       onmouseout="this.style.background=''">Salir</a>
  </div>
</nav>

<div class="layout-wrap">
<aside class="sidebar" id="sidebar">
  <?php foreach ($sideItems as $section => $items): ?>
  <div class="sb-section"><?= htmlspecialchars($section) ?></div>
  <?php foreach ($items as $item): ?>
  <?php
    $isActive = strpos($_SERVER['PHP_SELF'], $item['href']) !== false;
    $badge    = isset($item['badge']) ? (int)$item['badge'] : 0;
  ?>
  <a href="<?= htmlspecialchars($item['href']) ?>"
     class="sb-item <?= $isActive ? 'active' : '' ?>">
    <span class="sb-ic"><?= $item['icon'] ?></span>
    <?= htmlspecialchars($item['label']) ?>
    <?php if ($badge > 0): ?>
      <span class="sb-badge"><?= $badge ?></span>
    <?php endif; ?>
  </a>
  <?php endforeach; ?>
  <?php endforeach; ?>
</aside>
<main class="main-content">
<?php
} // end layout_start

/* ── Sidebar items por rol ── */
function sidebar_items(string $role): array {
  $pdo  = app_pdo();
  $uid  = (int)($_SESSION['user']['id'] ?? 0);
  $year = (int)date('Y');

  $pending = 0;
  if ($role === 'DOCENTE' && $uid) {
    try {
      $pending = (int)$pdo->query("
        SELECT COUNT(*) FROM task_submissions ts
        JOIN tasks t ON t.id=ts.task_id
        WHERE t.teacher_id=$uid AND ts.grade IS NULL
      ")->fetchColumn();
    } catch (Throwable) {}
  }

  $task_pending = 0;
  if ($role === 'ALUMNO' && $uid) {
    try {
      $my = $pdo->query("
        SELECT level_id,grade_id FROM student_assignments
        WHERE student_id=$uid AND school_year=$year AND is_active=1 LIMIT 1
      ")->fetch();
      if ($my) {
        $task_pending = (int)$pdo->query("
          SELECT COUNT(*) FROM tasks t
          JOIN teacher_assignments ta ON ta.id=t.assignment_id
          WHERE ta.level_id={$my['level_id']}
            AND ta.grade_id={$my['grade_id']}
            AND t.school_year=$year AND t.is_active=1
            AND (SELECT id FROM task_submissions ts
                 WHERE ts.task_id=t.id AND ts.student_id=$uid LIMIT 1) IS NULL
        ")->fetchColumn();
      }
    } catch (Throwable) {}
  }

  $base = '/sistemaescolar/';
  return match($role) {
    'ADMIN' => [
      'General' => [
        ['href'=>$base.'admin/index.php',       'icon'=>'🏠','label'=>'Dashboard'],
        ['href'=>$base.'admin/config.php',       'icon'=>'⚙️','label'=>'Configuración'],
      ],
      'Gestión' => [
        ['href'=>$base.'admin/usuarios.php',    'icon'=>'👥','label'=>'Usuarios'],
        ['href'=>$base.'admin/docentes.php',    'icon'=>'👨‍🏫','label'=>'Docentes'],
        ['href'=>$base.'admin/alumnos.php',     'icon'=>'🎓','label'=>'Alumnos'],
        ['href'=>$base.'admin/categorias.php',  'icon'=>'📚','label'=>'Cursos'],
        ['href'=>$base.'admin/asignaciones.php','icon'=>'📋','label'=>'Asignaciones'],
        ['href'=>$base.'admin/bimestres.php',   'icon'=>'📦','label'=>'Bimestres'],
      ],
      'Contenido' => [
        ['href'=>$base.'admin/importar.php',    'icon'=>'📥','label'=>'Importar Excel'],
        ['href'=>$base.'admin/anuncios.php',    'icon'=>'📢','label'=>'Anuncios'],
        ['href'=>$base.'admin/reportes.php',    'icon'=>'📊','label'=>'Reportes'],
      ],
    ],
    'DOCENTE' => [
      'Principal' => [
        ['href'=>$base.'docente/index.php',     'icon'=>'🏠','label'=>'Dashboard'],
        ['href'=>$base.'docente/subcursos.php', 'icon'=>'📚','label'=>'Mis Subcursos'],
      ],
      'Académico' => [
        ['href'=>$base.'docente/silabos.php',   'icon'=>'📄','label'=>'Sílabos'],
        ['href'=>$base.'docente/tareas.php',    'icon'=>'📝','label'=>'Tareas','badge'=>$pending],
        ['href'=>$base.'docente/alumnos.php',   'icon'=>'🎓','label'=>'Mis Alumnos'],
        ['href'=>$base.'docente/anuncios.php',  'icon'=>'📢','label'=>'Anuncios'],
      ],
    ],
    'ALUMNO' => [
      'Principal' => [
        ['href'=>$base.'alumno/index.php',      'icon'=>'🏠','label'=>'Dashboard'],
        ['href'=>$base.'alumno/cursos.php',     'icon'=>'📚','label'=>'Mis Cursos'],
      ],
      'Académico' => [
        ['href'=>$base.'alumno/tareas.php',     'icon'=>'📝','label'=>'Mis Tareas','badge'=>$task_pending],
        ['href'=>$base.'alumno/agenda.php',     'icon'=>'📅','label'=>'Agenda'],
        ['href'=>$base.'alumno/anuncios.php',   'icon'=>'📢','label'=>'Anuncios'],
      ],
    ],
    default => [],
  };
}

function layout_end(): void {
  $poll_ms = (int)sys_cfg('notif_poll_ms', 30000);
  $csrf    = htmlspecialchars(csrf_token());
?>
</main>
</div>

<div id="toast-wrap"></div>

<div id="confirm-ov">
  <div id="confirm-box">
    <div id="confirm-title">¿Confirmar acción?</div>
    <div id="confirm-msg"></div>
    <div style="display:flex;gap:8px;justify-content:flex-end">
      <button class="btn btn-outline" onclick="closeConfirm()">Cancelar</button>
      <button class="btn btn-navy" id="confirm-ok">Confirmar</button>
    </div>
  </div>
</div>

<script>
var NOTIF_CSRF='<?= $csrf ?>',NOTIF_POLL=<?= $poll_ms ?>,NOTIF_OPEN=false,_confirmCb=null;

function toast(msg,type,ms){
  type=type||'inf';ms=ms||3200;
  var d=document.createElement('div');
  d.className='toast '+type;
  d.innerHTML=(type==='ok'?'✅':type==='err'?'❌':'ℹ️')+' <span>'+msg+'</span>';
  document.getElementById('toast-wrap').prepend(d);
  setTimeout(function(){d.style.opacity='0';d.style.transform='translateY(10px)';
    setTimeout(function(){d.remove();},300);},ms);
}
function confirmModal(msg,cb,title){
  document.getElementById('confirm-title').textContent=title||'¿Confirmar?';
  document.getElementById('confirm-msg').textContent=msg;
  document.getElementById('confirm-ov').classList.add('show');
  _confirmCb=cb;
}
document.getElementById('confirm-ok').addEventListener('click',function(){
  closeConfirm();if(_confirmCb)_confirmCb();
});
function closeConfirm(){
  document.getElementById('confirm-ov').classList.remove('show');_confirmCb=null;
}
document.getElementById('confirm-ov').addEventListener('click',function(e){
  if(e.target===this)closeConfirm();
});
function ajaxForm(form,cb){
  if(!form)return;
  form.addEventListener('submit',function(e){
    e.preventDefault();
    var btn=form.querySelector('[type=submit]'),orig=btn?btn.innerHTML:'';
    if(btn){btn.disabled=true;btn.innerHTML='<span class="spinner"></span> Guardando...';}
    fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new FormData(form)})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,d.ok?'ok':'err');
      if(btn){btn.disabled=false;btn.innerHTML=orig;}
      if(d.ok&&cb)cb(d);
    }).catch(function(){
      toast('Error de conexión','err');
      if(btn){btn.disabled=false;btn.innerHTML=orig;}
    });
  });
}
function uploadForm(form,cb){
  if(!form)return;
  form.addEventListener('submit',function(e){
    e.preventDefault();
    var btn=form.querySelector('[type=submit]'),
        prog=form.querySelector('.up-prog'),
        fill=form.querySelector('.prog-fill'),
        lbl=form.querySelector('.up-lbl'),
        orig=btn?btn.innerHTML:'';
    if(btn){btn.disabled=true;btn.innerHTML='<span class="spinner"></span> Subiendo...';}
    if(prog)prog.style.display='flex';
    var xhr=new XMLHttpRequest();
    xhr.open('POST',location.href);
    xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
    xhr.upload.onprogress=function(ev){
      if(ev.lengthComputable){
        var p=Math.round(ev.loaded/ev.total*100);
        if(fill)fill.style.width=p+'%';if(lbl)lbl.textContent=p+'%';
      }
    };
    xhr.onload=function(){
      try{
        var d=JSON.parse(xhr.responseText);
        toast(d.msg,d.ok?'ok':'err');
        if(btn){btn.disabled=false;btn.innerHTML=orig;}
        if(prog)prog.style.display='none';
        if(fill)fill.style.width='0';if(lbl)lbl.textContent='0%';
        if(d.ok&&cb)cb(d);
      }catch(ex){toast('Error inesperado','err');}
    };
    xhr.send(new FormData(form));
  });
}
function toggleNotif(){
  var dd=document.getElementById('notif-dd');
  NOTIF_OPEN=!NOTIF_OPEN;
  dd.classList.toggle('show',NOTIF_OPEN);
  if(NOTIF_OPEN)loadNotifs();
}
function loadNotifs(){
  fetch('/sistemaescolar/api/notifications.php?act=list',{
    headers:{'X-Requested-With':'XMLHttpRequest'}
  }).then(r=>r.json()).then(function(d){
    if(!d.ok)return;
    renderNotifs(d.notifications);updateBadge(d.unread);
    var ts=document.getElementById('nd-ts');
    if(ts)ts.textContent='Actualizado: '+new Date().toLocaleTimeString('es-PE');
  });
}
function renderNotifs(items){
  var list=document.getElementById('nd-list');
  if(!items||!items.length){
    list.innerHTML='<div class="nd-empty">🔔 No hay notificaciones</div>';return;
  }
  list.innerHTML=items.map(function(n){
    return '<div class="nd-item '+(n.is_read?'':'unread')+'" id="ni-'+n.id+'"'+
      (n.url?' onclick="goNotif('+n.id+',\''+n.url+'\')"':'')+
      ' style="cursor:'+(n.url?'pointer':'default')+'">'+
      '<div class="nd-ic" style="background:'+n.color+'20">'+n.icon+'</div>'+
      '<div class="nd-body">'+
        '<div class="nd-ntitle">'+escHtml(n.title)+'</div>'+
        (n.body?'<div class="nd-nbody">'+escHtml(n.body)+'</div>':'')+
        (n.from_name?'<div class="nd-time">👤 '+escHtml(n.from_name)+' · '+n.time+'</div>'
                    :'<div class="nd-time">'+n.time+'</div>')+
      '</div>'+
      '<button class="nd-del" onclick="event.stopPropagation();delNotif('+n.id+')">✕</button>'+
    '</div>';
  }).join('');
}
function goNotif(id,url){markRead(id);window.location.href=url;}
function markRead(id){
  var fd=new FormData();fd.append('csrf',NOTIF_CSRF);fd.append('act','mark_read');fd.append('id',id);
  fetch('/sistemaescolar/api/notifications.php',{method:'POST',body:fd})
  .then(r=>r.json()).then(d=>{
    updateBadge(d.unread);
    var el=document.getElementById('ni-'+id);if(el)el.classList.remove('unread');
  });
}
function markAllRead(){
  var fd=new FormData();fd.append('csrf',NOTIF_CSRF);fd.append('act','mark_all');
  fetch('/sistemaescolar/api/notifications.php',{method:'POST',body:fd})
  .then(r=>r.json()).then(d=>{
    updateBadge(0);
    document.querySelectorAll('.nd-item').forEach(function(x){x.classList.remove('unread');});
    var lbl=document.getElementById('nd-unread-lbl');if(lbl)lbl.textContent='';
  });
}
function deleteAllRead(){
  var fd=new FormData();fd.append('csrf',NOTIF_CSRF);fd.append('act','delete_all_read');
  fetch('/sistemaescolar/api/notifications.php',{method:'POST',body:fd})
  .then(r=>r.json()).then(function(){loadNotifs();});
}
function delNotif(id){
  var fd=new FormData();fd.append('csrf',NOTIF_CSRF);fd.append('act','delete');fd.append('id',id);
  fetch('/sistemaescolar/api/notifications.php',{method:'POST',body:fd})
  .then(r=>r.json()).then(d=>{
    updateBadge(d.unread);
    var el=document.getElementById('ni-'+id);if(el)el.remove();
    if(!document.querySelectorAll('.nd-item').length)
      document.getElementById('nd-list').innerHTML='<div class="nd-empty">🔔 No hay notificaciones</div>';
  });
}
function updateBadge(n){
  var b=document.getElementById('notif-count'),lbl=document.getElementById('nd-unread-lbl');
  if(!b)return;
  if(n>0){b.textContent=n>99?'99+':n;b.classList.add('show');}
  else{b.textContent='';b.classList.remove('show');}
  if(lbl)lbl.textContent=n?'('+n+' sin leer)':'';
}
if(NOTIF_POLL>0){
  setInterval(function(){
    if(!NOTIF_OPEN){
      fetch('/sistemaescolar/api/notifications.php?act=count',{
        headers:{'X-Requested-With':'XMLHttpRequest'}
      }).then(r=>r.json()).then(d=>{if(d.ok)updateBadge(d.count);});
    }else{loadNotifs();}
  },NOTIF_POLL);
}
document.addEventListener('click',function(e){
  var btn=document.getElementById('notif-btn'),dd=document.getElementById('notif-dd');
  if(dd&&btn&&!btn.contains(e.target)&&!dd.contains(e.target)){
    dd.classList.remove('show');NOTIF_OPEN=false;
  }
});
function escHtml(s){
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
    .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
document.getElementById('mob-menu')&&
  (document.getElementById('mob-menu').style.display='block');
</script>
</body>
</html>
<?php
} // end layout_end