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

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

  /* ── Crear docente ───────────────────────────────────── */
  if ($act === 'create') {
    $dni    = preg_replace('/\D/', '', $_POST['dni']       ?? '');
    $name   = trim($_POST['full_name']                     ?? '');
    $email  = trim($_POST['email']                         ?? '');
    $phone  = trim($_POST['phone']                         ?? '');
    $pass   = trim($_POST['password']                      ?? $dni);
    $spec   = trim($_POST['speciality']                    ?? '');

    if (!preg_match('/^\d{7,12}$/', $dni)) json_err('DNI inválido (7-12 dígitos).');
    if (strlen($name) < 3)                  json_err('Nombre muy corto.');
    if (strlen($pass) < 4)                  json_err('Contraseña mínimo 4 caracteres.');

    /* Verificar duplicado */
    $dup = $pdo->prepare('SELECT id FROM users WHERE dni=?');
    $dup->execute([$dni]);
    if ($dup->fetchColumn()) json_err("El DNI $dni ya está registrado.");

    $pdo->prepare("INSERT INTO users
      (dni, full_name, email, phone, role, password_hash, speciality)
      VALUES (?,?,?,?,?,?,?)")
      ->execute([$dni, $name, $email ?: null, $phone ?: null,
                 'DOCENTE', password_hash($pass, PASSWORD_DEFAULT), $spec]);
    $new_uid = (int)$pdo->lastInsertId();

    /* Notificar admins */
    notif_admins('system',
      "👨‍🏫 Nuevo docente registrado: $name",
      "DNI: $dni", '', (int)$u['id']);

    $row = fetch_docente($pdo, $new_uid, $year);
    json_ok("Docente $name registrado.", ['docente' => $row]);
  }

  /* ── Editar docente ──────────────────────────────────── */
  if ($act === 'edit') {
    $id    = (int)($_POST['id']          ?? 0);
    $dni   = preg_replace('/\D/', '', $_POST['dni'] ?? '');
    $name  = trim($_POST['full_name']    ?? '');
    $email = trim($_POST['email']        ?? '');
    $phone = trim($_POST['phone']        ?? '');
    $spec  = trim($_POST['speciality']   ?? '');
    $pass  = trim($_POST['password']     ?? '');

    if (!$id)                             json_err('ID no válido.');
    if (!preg_match('/^\d{7,12}$/',$dni)) json_err('DNI inválido.');
    if (strlen($name) < 3)                json_err('Nombre muy corto.');

    /* Verificar duplicado en otro registro */
    $dup = $pdo->prepare('SELECT id FROM users WHERE dni=? AND id<>?');
    $dup->execute([$dni, $id]);
    if ($dup->fetchColumn()) json_err("El DNI $dni pertenece a otro usuario.");

    if ($pass) {
      $pdo->prepare("UPDATE users SET dni=?,full_name=?,email=?,phone=?,
                     speciality=?,password_hash=? WHERE id=?")
          ->execute([$dni,$name,$email?:null,$phone?:null,$spec,
                     password_hash($pass,PASSWORD_DEFAULT),$id]);
    } else {
      $pdo->prepare("UPDATE users SET dni=?,full_name=?,email=?,phone=?,
                     speciality=? WHERE id=?")
          ->execute([$dni,$name,$email?:null,$phone?:null,$spec,$id]);
    }
    $row = fetch_docente($pdo, $id, $year);
    json_ok('Docente actualizado.', ['docente' => $row]);
  }

  /* ── Toggle activo/inactivo ──────────────────────────── */
  if ($act === 'toggle') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('UPDATE users SET is_active=1-is_active WHERE id=? AND role=?')
        ->execute([$id,'DOCENTE']);
    $is = (int)$pdo->query("SELECT is_active FROM users WHERE id=$id")->fetchColumn();
    json_ok($is ? 'Docente activado.' : 'Docente desactivado.', ['is_active'=>$is]);
  }

  /* ── Resetear contraseña ─────────────────────────────── */
  if ($act === 'reset_pass') {
    $id  = (int)($_POST['id']   ?? 0);
    $new = trim($_POST['pass']  ?? '');
    if (strlen($new) < 4) json_err('Mínimo 4 caracteres.');
    $pdo->prepare("UPDATE users SET password_hash=? WHERE id=? AND role='DOCENTE'")
        ->execute([password_hash($new, PASSWORD_DEFAULT), $id]);
    json_ok('Contraseña restablecida.');
  }

  /* ── Crear asignación ────────────────────────────────── */
  if ($act === 'assign') {
    $did  = (int)($_POST['teacher_id']  ?? 0);
    $lid  = (int)($_POST['level_id']    ?? 0);
    $gid  = (int)($_POST['grade_id']    ?? 0);
    $cid  = (int)($_POST['course_id']   ?? 0);
    $sid  = (int)($_POST['subcourse_id']?? 0) ?: null;
    if (!$did || !$lid || !$gid || !$cid) json_err('Completa todos los campos.');

    /* Verificar duplicado */
    $dup = $pdo->prepare("SELECT id FROM teacher_assignments
      WHERE teacher_id=? AND level_id=? AND grade_id=?
        AND course_id=? AND COALESCE(subcourse_id,0)=COALESCE(?,0)
        AND school_year=?");
    $dup->execute([$did,$lid,$gid,$cid,$sid,$year]);
    if ($dup->fetchColumn()) json_err('Esta asignación ya existe.');

    $pdo->prepare("INSERT INTO teacher_assignments
      (teacher_id,level_id,grade_id,course_id,subcourse_id,school_year)
      VALUES(?,?,?,?,?,?)")
      ->execute([$did,$lid,$gid,$cid,$sid,$year]);
    $aid = (int)$pdo->lastInsertId();

    /* Auto-crear bimestres si está configurado */
    if (sys_cfg('auto_create_bimesters', false)) {
      $max = (int)sys_cfg('bimesters_per_year', 4);
      for ($n = 1; $n <= $max; $n++) {
        try {
          $pdo->prepare("INSERT INTO bimesters (assignment_id,number,name) VALUES(?,?,?)")
              ->execute([$aid, $n, "Bimestre $n"]);
        } catch (PDOException) {}
      }
    }

    /* Notificar al docente */
    $assign_info = $pdo->query("
      SELECT l.name AS lv,g.name AS gr,c.name AS co,sc.name AS sub
      FROM teacher_assignments ta
      JOIN levels l ON l.id=ta.level_id
      JOIN grades g ON g.id=ta.grade_id
      JOIN courses c ON c.id=ta.course_id
      LEFT JOIN subcourses sc ON sc.id=ta.subcourse_id
      WHERE ta.id=$aid
    ")->fetch();
    if ($assign_info && sys_cfg('notif_enabled',true)) {
      notif_create($did,'system',
        '📋 Nueva asignación asignada',
        "{$assign_info['lv']} · {$assign_info['gr']} | {$assign_info['co']}".
        ($assign_info['sub'] ? " › {$assign_info['sub']}" : ''),
        '/sistemaescolar/docente/subcursos.php?assign_id='.$aid,
        (int)$u['id']);
    }
    json_ok('Asignación creada.', ['assign_id'=>$aid]);
  }

  /* ── Eliminar asignación ─────────────────────────────── */
  if ($act === 'del_assign') {
    $aid = (int)($_POST['assign_id'] ?? 0);
    $pdo->prepare('DELETE FROM teacher_assignments WHERE id=?')->execute([$aid]);
    json_ok('Asignación eliminada.');
  }

  /* ── Toggle asignación ───────────────────────────────── */
  if ($act === 'toggle_assign') {
    $aid = (int)($_POST['assign_id'] ?? 0);
    $pdo->prepare('UPDATE teacher_assignments SET is_active=1-is_active WHERE id=?')
        ->execute([$aid]);
    $is = (int)$pdo->query("SELECT is_active FROM teacher_assignments WHERE id=$aid")
                   ->fetchColumn();
    json_ok('Estado actualizado.', ['is_active'=>$is]);
  }

  /* ── Enviar notificación a docente ───────────────────── */
  if ($act === 'send_notif') {
    $did   = (int)($_POST['teacher_id'] ?? 0);
    $title = trim($_POST['title']       ?? '');
    $body  = trim($_POST['body']        ?? '');
    if (!$did || !$title) json_err('Faltan datos.');
    notif_create($did,'announcement',$title,$body,'',(int)$u['id']);
    json_ok('Notificación enviada.');
  }
}

/* ══════════════════════════════════════════════════════════
   GET — cargar datos
   ══════════════════════════════════════════════════════════ */

/* Filtros */
$q_search = trim($_GET['q']       ?? '');
$f_level  = (int)($_GET['level']  ?? 0);
$f_status = $_GET['status']       ?? 'active';
$f_course = (int)($_GET['course'] ?? 0);
$page     = max(1, (int)($_GET['page'] ?? 1));
$per_page = (int)sys_cfg('admin_per_page', 20);

/* Construir WHERE */
$where = ["u.role = 'DOCENTE'"];
$params = [];
if ($q_search) {
  $where[]  = "(u.full_name LIKE ? OR u.dni LIKE ? OR u.email LIKE ?)";
  $like = "%$q_search%";
  $params = array_merge($params, [$like,$like,$like]);
}
if ($f_status === 'active')   $where[] = 'u.is_active=1';
if ($f_status === 'inactive') $where[] = 'u.is_active=0';
if ($f_level) {
  $where[]  = "EXISTS(SELECT 1 FROM teacher_assignments ta
               WHERE ta.teacher_id=u.id AND ta.level_id=? AND ta.school_year=?)";
  $params[] = $f_level; $params[] = $year;
}
if ($f_course) {
  $where[]  = "EXISTS(SELECT 1 FROM teacher_assignments ta
               WHERE ta.teacher_id=u.id AND ta.course_id=? AND ta.school_year=?)";
  $params[] = $f_course; $params[] = $year;
}
$whereSQL = 'WHERE '.implode(' AND ', $where);

/* Total */
$total_q = $pdo->prepare("SELECT COUNT(*) FROM users u $whereSQL");
$total_q->execute($params);
$total    = (int)$total_q->fetchColumn();
$pages    = max(1, (int)ceil($total / $per_page));
$offset   = ($page - 1) * $per_page;

/* Docentes paginados */
$stmt = $pdo->prepare("
  SELECT u.*,
    COUNT(DISTINCT ta.id) AS n_assigns,
    COUNT(DISTINCT s.id)  AS n_sessions,
    COUNT(DISTINCT sy.id) AS n_syllabi,
    SUM(CASE WHEN ta.is_active=1 AND ta.school_year=$year THEN 1 ELSE 0 END)
      AS n_active_assigns
  FROM users u
  LEFT JOIN teacher_assignments ta ON ta.teacher_id=u.id AND ta.school_year=$year
  LEFT JOIN bimesters b ON b.assignment_id=ta.id
  LEFT JOIN sessions s  ON s.bimester_id=b.id
  LEFT JOIN syllabi sy  ON sy.assignment_id=ta.id
  $whereSQL
  GROUP BY u.id
  ORDER BY u.full_name
  LIMIT $per_page OFFSET $offset
");
$stmt->execute($params);
$docentes = $stmt->fetchAll();

/* Catálogos */
$levels  = $pdo->query("SELECT * FROM levels ORDER BY sort_order")->fetchAll();
$courses = $pdo->query("SELECT * FROM courses WHERE is_active=1 ORDER BY name")->fetchAll();

/* Stats globales */
$total_all    = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='DOCENTE'")->fetchColumn();
$total_active = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='DOCENTE' AND is_active=1")->fetchColumn();
$total_assigns= (int)$pdo->query("SELECT COUNT(*) FROM teacher_assignments WHERE school_year=$year AND is_active=1")->fetchColumn();

layout_start('Gestión de Docentes', $u);
$csrf = htmlspecialchars(csrf_token());

/* ── Helpers PHP ─────────────────────────────────────── */
function fetch_docente(PDO $pdo, int $id, int $year): array {
  return $pdo->query("
    SELECT u.*,
      COUNT(DISTINCT ta.id) AS n_assigns,
      SUM(CASE WHEN ta.is_active=1 AND ta.school_year=$year THEN 1 ELSE 0 END)
        AS n_active_assigns
    FROM users u
    LEFT JOIN teacher_assignments ta
      ON ta.teacher_id=u.id AND ta.school_year=$year
    WHERE u.id=$id GROUP BY u.id
  ")->fetch() ?: [];
}
?>

<!-- ── CABECERA ── -->
<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)">
      👨‍🏫 Gestión de Docentes
    </h2>
    <p class="txt-muted">Administra docentes, asignaciones y seguimiento</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <button class="btn btn-outline btn-sm" onclick="exportDocentes()">
      📊 Exportar Excel
    </button>
    <button class="btn btn-navy" onclick="openModal('m-doc')">
      ➕ Nuevo Docente
    </button>
  </div>
</div>

<!-- STATS -->
<div class="stats-row" style="margin-bottom:18px">
  <div class="stat-card">
    <div class="sv"><?= $total_all ?></div>
    <div class="sl">Total docentes</div>
  </div>
  <div class="stat-card" style="border-top-color:var(--green)">
    <div class="sv" style="color:var(--green)"><?= $total_active ?></div>
    <div class="sl">Activos</div>
  </div>
  <div class="stat-card" style="border-top-color:var(--orange)">
    <div class="sv" style="color:var(--orange)"><?= $total_all - $total_active ?></div>
    <div class="sl">Inactivos</div>
  </div>
  <div class="stat-card" style="border-top-color:var(--teal)">
    <div class="sv" style="color:var(--teal)"><?= $total_assigns ?></div>
    <div class="sl">Asignaciones <?= $year ?></div>
  </div>
</div>

<!-- ── FILTROS ── -->
<div class="card" style="padding:12px 16px;margin-bottom:14px">
  <form method="get" id="f-filter"
        style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
    <div class="tbl-search" style="flex:1;min-width:200px">
      <span class="tbl-sico">🔍</span>
      <input name="q" value="<?= htmlspecialchars($q_search) ?>"
             placeholder="Buscar nombre, DNI o email..."
             style="width:100%">
    </div>
    <div class="fg" style="min-width:150px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">
        Nivel
      </label>
      <select name="level">
        <option value="">Todos los niveles</option>
        <?php foreach ($levels as $lv): ?>
          <option value="<?= (int)$lv['id'] ?>"
            <?= $f_level===(int)$lv['id']?'selected':'' ?>>
            <?= htmlspecialchars($lv['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fg" style="min-width:170px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">
        Curso asignado
      </label>
      <select name="course">
        <option value="">Todos los cursos</option>
        <?php foreach ($courses as $co): ?>
          <option value="<?= (int)$co['id'] ?>"
            <?= $f_course===(int)$co['id']?'selected':'' ?>>
            <?= htmlspecialchars($co['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fg" style="min-width:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">
        Estado
      </label>
      <select name="status">
        <option value=""    <?= $f_status===''       ?'selected':'' ?>>Todos</option>
        <option value="active"   <?= $f_status==='active'  ?'selected':'' ?>>Activos</option>
        <option value="inactive" <?= $f_status==='inactive'?'selected':'' ?>>Inactivos</option>
      </select>
    </div>
    <div style="display:flex;gap:6px;align-items:flex-end">
      <button type="submit" class="btn btn-navy btn-sm">🔍 Filtrar</button>
      <a href="?" class="btn btn-outline btn-sm">✕ Limpiar</a>
    </div>
  </form>
</div>

<!-- ── RESULTADOS ── -->
<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:8px;margin-bottom:10px">
  <div class="txt-muted">
    <?= $total ?> docente(s) encontrado(s)
    · Página <?= $page ?> de <?= $pages ?>
  </div>
  <!-- Vista toggle -->
  <div style="display:flex;gap:6px">
    <button class="btn btn-outline btn-xs" id="btn-grid"
            onclick="setView('grid')">⊞ Tarjetas</button>
    <button class="btn btn-outline btn-xs" id="btn-list"
            onclick="setView('list')">☰ Lista</button>
  </div>
</div>

<!-- ════ VISTA TARJETAS (default) ════ -->
<div id="view-grid">
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));
              gap:14px;margin-bottom:16px">
    <?php foreach ($docentes as $d):
      $active = (int)$d['is_active'];
      $color  = $active ? 'var(--navy)' : 'var(--muted)';
    ?>
    <div class="doc-card <?= $active?'':'inactive' ?>"
         id="dc-<?= (int)$d['id'] ?>">
      <div class="dc-head" style="background:<?= $color ?>">
        <div class="dc-avatar">
          <?= mb_strtoupper(mb_substr($d['full_name'],0,2)) ?>
        </div>
        <div style="flex:1;min-width:0">
          <div class="dc-name"><?= htmlspecialchars($d['full_name']) ?></div>
          <div class="dc-dni">🪪 <?= htmlspecialchars($d['dni']) ?></div>
        </div>
        <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>"
              id="ds-<?= (int)$d['id'] ?>"
              style="flex-shrink:0;align-self:flex-start">
          <?= $active?'Activo':'Inactivo' ?>
        </span>
      </div>
      <div class="dc-body">
        <?php if ($d['email']): ?>
          <div class="dc-info">
            ✉️ <?= htmlspecialchars($d['email']) ?>
          </div>
        <?php endif; ?>
        <?php if ($d['phone']): ?>
          <div class="dc-info">
            📞 <?= htmlspecialchars($d['phone']) ?>
          </div>
        <?php endif; ?>
        <?php if ($d['speciality']): ?>
          <div class="dc-info">
            🎓 <?= htmlspecialchars($d['speciality']) ?>
          </div>
        <?php endif; ?>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px">
          <span class="mini-chip">
            📋 <?= (int)$d['n_active_assigns'] ?> asign.
          </span>
          <span class="mini-chip">
            🗂 <?= (int)$d['n_sessions'] ?> ses.
          </span>
          <span class="mini-chip">
            📄 <?= (int)$d['n_syllabi'] ?> síl.
          </span>
        </div>
      </div>
      <div class="dc-foot">
        <button class="btn btn-outline btn-xs"
                onclick='openEditDoc(<?= htmlspecialchars(json_encode([
                  "id"          => (int)$d["id"],
                  "dni"         => $d["dni"],
                  "full_name"   => $d["full_name"],
                  "email"       => $d["email"]       ?? "",
                  "phone"       => $d["phone"]        ?? "",
                  "speciality"  => $d["speciality"]   ?? "",
                ], JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>
          ✏️ Editar
        </button>
        <button class="btn btn-teal btn-xs"
                onclick="openAssign(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
          📋 Asignar
        </button>
        <button class="btn btn-outline btn-xs"
                onclick="openViewAssigns(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
          👁 Ver asign.
        </button>
        <button class="btn btn-outline btn-xs"
                onclick="openNotifDoc(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
          📢
        </button>
        <button class="btn btn-orange btn-xs"
                id="dtb-<?= (int)$d['id'] ?>"
                onclick="togDoc(<?= (int)$d['id'] ?>,this)">
          <?= $active?'Desact.':'Activar' ?>
        </button>
        <button class="btn btn-outline btn-xs"
                onclick="openResetPass(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
          🔑
        </button>
      </div>
    </div>
    <?php endforeach; ?>
    <?php if (!$docentes): ?>
    <div style="grid-column:1/-1;text-align:center;padding:40px;color:var(--muted)">
      <div style="font-size:40px;margin-bottom:10px">👨‍🏫</div>
      No se encontraron docentes con los filtros aplicados.
    </div>
    <?php endif; ?>
  </div>
</div>

<!-- ════ VISTA LISTA ════ -->
<div id="view-list" style="display:none">
  <div class="card" style="padding:0;overflow:hidden">
    <div class="table-wrap">
      <table id="t-docentes">
        <thead>
          <tr>
            <th>#</th><th>Nombre</th><th>DNI</th><th>Email</th>
            <th>Especialidad</th><th>Asign.</th><th>Sesiones</th>
            <th>Estado</th><th style="text-align:center">Acciones</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($docentes as $i => $d):
          $active = (int)$d['is_active'];
        ?>
        <tr id="dtr-<?= (int)$d['id'] ?>" <?= $active?'':'style="opacity:.6"' ?>>
          <td class="txt-muted"><?= $offset + $i + 1 ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <div class="dc-avatar-sm"
                   style="background:var(--navy)">
                <?= mb_strtoupper(mb_substr($d['full_name'],0,1)) ?>
              </div>
              <div>
                <div style="font-size:13px;font-weight:700;color:var(--navy)">
                  <?= htmlspecialchars($d['full_name']) ?>
                </div>
                <?php if ($d['phone']): ?>
                  <div class="txt-muted">📞 <?= htmlspecialchars($d['phone']) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td class="txt-muted"><?= htmlspecialchars($d['dni']) ?></td>
          <td class="txt-muted"><?= htmlspecialchars($d['email'] ?? '—') ?></td>
          <td class="txt-muted"><?= htmlspecialchars($d['speciality'] ?? '—') ?></td>
          <td style="text-align:center;font-weight:700;color:var(--navy)">
            <?= (int)$d['n_active_assigns'] ?>
          </td>
          <td style="text-align:center;color:var(--muted)">
            <?= (int)$d['n_sessions'] ?>
          </td>
          <td>
            <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>"
                  id="dls-<?= (int)$d['id'] ?>">
              <?= $active?'Activo':'Inactivo' ?>
            </span>
          </td>
          <td>
            <div style="display:flex;gap:4px;justify-content:center;flex-wrap:wrap">
              <button class="btn btn-outline btn-xs"
                      onclick='openEditDoc(<?= htmlspecialchars(json_encode([
                        "id"=>(int)$d["id"],"dni"=>$d["dni"],
                        "full_name"=>$d["full_name"],
                        "email"=>$d["email"]??"",
                        "phone"=>$d["phone"]??"",
                        "speciality"=>$d["speciality"]??"",
                      ],JSON_HEX_APOS|JSON_HEX_QUOT)) ?>)'>
                ✏️
              </button>
              <button class="btn btn-teal btn-xs"
                      onclick="openAssign(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
                📋
              </button>
              <button class="btn btn-outline btn-xs"
                      onclick="openViewAssigns(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
                👁
              </button>
              <button class="btn btn-orange btn-xs"
                      id="dltb-<?= (int)$d['id'] ?>"
                      onclick="togDoc(<?= (int)$d['id'] ?>,this)">
                <?= $active?'↓':'↑' ?>
              </button>
              <button class="btn btn-outline btn-xs"
                      onclick="openResetPass(<?= (int)$d['id'] ?>,'<?= addslashes($d['full_name']) ?>')">
                🔑
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- PAGINACIÓN -->
<?php if ($pages > 1): ?>
<div style="display:flex;gap:6px;justify-content:center;
     flex-wrap:wrap;margin-top:16px">
  <?php for ($p = 1; $p <= $pages; $p++):
    $params_page = array_merge($_GET, ['page'=>$p]);
    $url = '?'.http_build_query($params_page);
  ?>
  <a href="<?= htmlspecialchars($url) ?>"
     class="btn <?= $p===$page?'btn-navy':'btn-outline' ?> btn-sm">
    <?= $p ?>
  </a>
  <?php endfor; ?>
</div>
<?php endif; ?>


<!-- ══════════════════════════════════════════════════════
     MODALES
     ══════════════════════════════════════════════════════ -->

<!-- Modal Crear/Editar Docente -->
<div class="modal-ov" id="m-doc">
  <div class="modal" style="max-width:520px">
    <h3 id="mdoc-title">➕ Nuevo Docente</h3>
    <form id="f-doc" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="create" id="fdoc-act">
      <input type="hidden" name="id"   id="fdoc-id">
      <div class="form-grid">
        <div class="fg">
          <label>DNI *</label>
          <input name="dni" id="fdoc-dni" type="text"
                 maxlength="12" placeholder="Ej: 47201234" required>
        </div>
        <div class="fg">
          <label>Contraseña</label>
          <input name="password" id="fdoc-pass" type="text"
                 placeholder="Vacío = sin cambio (edición)">
        </div>
        <div class="fg" style="grid-column:1/-1">
          <label>Nombre completo *</label>
          <input name="full_name" id="fdoc-name" type="text"
                 required placeholder="Ej: Juan Carlos Pérez López">
        </div>
        <div class="fg">
          <label>Email</label>
          <input name="email" id="fdoc-email" type="email"
                 placeholder="correo@ejemplo.com">
        </div>
        <div class="fg">
          <label>Teléfono</label>
          <input name="phone" id="fdoc-phone" type="tel"
                 placeholder="Ej: 987654321">
        </div>
        <div class="fg" style="grid-column:1/-1">
          <label>Especialidad</label>
          <input name="speciality" id="fdoc-spec" type="text"
                 placeholder="Ej: Matemática, Comunicación...">
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-doc');resetDocForm()">Cancelar</button>
        <button type="submit" class="btn btn-navy">💾 Guardar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Asignar -->
<div class="modal-ov" id="m-assign">
  <div class="modal" style="max-width:500px">
    <h3 id="massign-title">📋 Nueva Asignación</h3>
    <form id="f-assign" method="post">
      <input type="hidden" name="csrf"       value="<?= $csrf ?>">
      <input type="hidden" name="act"        value="assign">
      <input type="hidden" name="teacher_id" id="assign-tid">
      <div class="form-grid">
        <div class="fg">
          <label>Nivel *</label>
          <select name="level_id" id="asgn-level" required
                  onchange="loadGrades(this.value,'asgn-grade')">
            <option value="">— Nivel —</option>
            <?php foreach ($levels as $lv): ?>
              <option value="<?= (int)$lv['id'] ?>">
                <?= htmlspecialchars($lv['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <label>Grado *</label>
          <select name="grade_id" id="asgn-grade" required>
            <option value="">— Selecciona nivel primero —</option>
          </select>
        </div>
        <div class="fg">
          <label>Curso *</label>
          <select name="course_id" id="asgn-course" required
                  onchange="loadSubcourses(this.value,'asgn-sub')">
            <option value="">— Curso —</option>
            <?php foreach ($courses as $co): ?>
              <option value="<?= (int)$co['id'] ?>">
                <?= htmlspecialchars($co['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <label>Subcurso</label>
          <select name="subcourse_id" id="asgn-sub">
            <option value="">— Sin subcurso —</option>
          </select>
        </div>
      </div>
      <div style="background:var(--bg);border-radius:8px;
           padding:10px 14px;margin-top:12px;font-size:12px;color:var(--muted)">
        ℹ️ <?php if (sys_cfg('auto_create_bimesters',false)): ?>
          Se crearán automáticamente <?= (int)sys_cfg('bimesters_per_year',4) ?> bimestres.
        <?php else: ?>
          El docente deberá crear sus bimestres desde su panel.
        <?php endif; ?>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-assign')">Cancelar</button>
        <button type="submit" class="btn btn-teal">📋 Crear asignación</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Ver Asignaciones del docente -->
<div class="modal-ov" id="m-vassign">
  <div class="modal" style="max-width:620px">
    <h3 id="mva-title">📋 Asignaciones del docente</h3>
    <div id="mva-body">
      <div style="text-align:center;padding:20px">
        <span class="spinner" style="border-color:var(--border);
              border-top-color:var(--navy);width:24px;height:24px;
              display:inline-block"></span>
      </div>
    </div>
    <div class="modal-actions">
      <button class="btn btn-outline" onclick="closeModal('m-vassign')">Cerrar</button>
    </div>
  </div>
</div>

<!-- Modal Resetear Contraseña -->
<div class="modal-ov" id="m-pass">
  <div class="modal" style="max-width:380px">
    <h3>🔑 Restablecer Contraseña</h3>
    <p class="txt-muted" id="pass-name" style="margin-bottom:14px"></p>
    <form id="f-pass" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="reset_pass">
      <input type="hidden" name="id"   id="pass-id">
      <div class="fg" style="margin-bottom:14px">
        <label>Nueva contraseña</label>
        <input name="pass" type="text" required minlength="4"
               placeholder="Mínimo 4 caracteres">
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-pass')">Cancelar</button>
        <button type="submit" class="btn btn-navy">🔑 Restablecer</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Enviar Notificación -->
<div class="modal-ov" id="m-notif-doc">
  <div class="modal" style="max-width:420px">
    <h3>📢 Enviar Notificación</h3>
    <p class="txt-muted" id="notif-doc-name" style="margin-bottom:14px"></p>
    <form id="f-notif-doc" method="post">
      <input type="hidden" name="csrf"       value="<?= $csrf ?>">
      <input type="hidden" name="act"        value="send_notif">
      <input type="hidden" name="teacher_id" id="nd-tid">
      <div class="fg" style="margin-bottom:12px">
        <label>Título</label>
        <input name="title" type="text" required
               placeholder="Asunto del aviso">
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Mensaje</label>
        <textarea name="body" rows="3"
                  placeholder="Detalle del mensaje"></textarea>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-notif-doc')">Cancelar</button>
        <button type="submit" class="btn btn-navy">📤 Enviar</button>
      </div>
    </form>
  </div>
</div>

<!-- ── ESTILOS ── -->
<style>
.doc-card{
  background:var(--card);border-radius:var(--r);
  box-shadow:var(--sh);overflow:hidden;
  transition:var(--tr);border:1.5px solid var(--border)
}
.doc-card:hover{transform:translateY(-3px);
                box-shadow:0 8px 24px rgba(0,0,0,.12)}
.doc-card.inactive{opacity:.65}
.dc-head{
  padding:14px;display:flex;align-items:center;gap:12px;
  flex-wrap:wrap
}
.dc-avatar{
  width:42px;height:42px;border-radius:50%;
  background:rgba(255,255,255,.25);color:#fff;
  display:flex;align-items:center;justify-content:center;
  font-size:16px;font-weight:800;flex-shrink:0
}
.dc-avatar-sm{
  width:30px;height:30px;border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  font-size:12px;font-weight:800;color:#fff;flex-shrink:0
}
.dc-name{font-size:14px;font-weight:800;color:#fff;line-height:1.2}
.dc-dni{font-size:11px;color:rgba(255,255,255,.75);margin-top:2px}
.dc-body{padding:12px 14px}
.dc-info{font-size:12px;color:var(--muted);margin-bottom:5px;
         white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dc-foot{
  padding:10px 14px;border-top:1px solid var(--bg);
  display:flex;gap:5px;flex-wrap:wrap
}
.mini-chip{
  display:inline-flex;align-items:center;gap:3px;
  padding:3px 8px;border-radius:20px;font-size:10px;
  font-weight:700;background:var(--bg);color:var(--navy)
}

/* Asignación row */
.assign-row{
  display:flex;align-items:center;justify-content:space-between;
  padding:10px 12px;border-radius:9px;
  background:var(--bg);margin-bottom:6px;flex-wrap:wrap;gap:8px
}
.assign-row.inactive-assign{opacity:.6}
</style>

<!-- ── JAVASCRIPT ── -->
<script>
var CSRF = '<?= $csrf ?>';
var _view = localStorage.getItem('doc_view') || 'grid';

/* Vista inicial */
setView(_view, true);

function setView(v, silent) {
  _view = v;
  if (!silent) localStorage.setItem('doc_view', v);
  document.getElementById('view-grid').style.display = v==='grid' ? '' : 'none';
  document.getElementById('view-list').style.display = v==='list' ? '' : 'none';
  document.getElementById('btn-grid').className =
    'btn btn-xs ' + (v==='grid' ? 'btn-navy' : 'btn-outline');
  document.getElementById('btn-list').className =
    'btn btn-xs ' + (v==='list' ? 'btn-navy' : 'btn-outline');
}

/* ── Modales ── */
function openModal(id){ document.getElementById(id).classList.add('show'); }
function closeModal(id){ document.getElementById(id).classList.remove('show'); }

/* ── Crear docente ── */
ajaxForm(document.getElementById('f-doc'), function(d){
  closeModal('m-doc');
  resetDocForm();
  toast(d.msg, 'ok');
  setTimeout(()=> location.reload(), 900);
});

function openEditDoc(data) {
  document.getElementById('mdoc-title').textContent = '✏️ Editar Docente';
  document.getElementById('fdoc-act').value  = 'edit';
  document.getElementById('fdoc-id').value   = data.id;
  document.getElementById('fdoc-dni').value  = data.dni;
  document.getElementById('fdoc-name').value = data.full_name;
  document.getElementById('fdoc-email').value= data.email;
  document.getElementById('fdoc-phone').value= data.phone;
  document.getElementById('fdoc-spec').value = data.speciality;
  document.getElementById('fdoc-pass').placeholder = '(vacío = no cambiar)';
  openModal('m-doc');
}

function resetDocForm() {
  document.getElementById('mdoc-title').textContent = '➕ Nuevo Docente';
  document.getElementById('fdoc-act').value  = 'create';
  document.getElementById('fdoc-id').value   = '';
  document.getElementById('f-doc').reset();
}

/* ── Toggle docente ── */
function togDoc(id, btn) {
  btn.disabled = true;
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle'); 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, d.ok?'ok':'err');
    if (d.ok) {
      /* Card */
      var c = document.getElementById('dc-'+id);
      if (c) c.classList.toggle('inactive', !d.is_active);
      /* Badge card */
      var bs = document.getElementById('ds-'+id);
      if (bs) {
        bs.className='bdg '+(d.is_active?'bdg-on':'bdg-off');
        bs.textContent = d.is_active?'Activo':'Inactivo';
      }
      /* Badge lista */
      var bl = document.getElementById('dls-'+id);
      if (bl) {
        bl.className='bdg '+(d.is_active?'bdg-on':'bdg-off');
        bl.textContent = d.is_active?'Activo':'Inactivo';
      }
      btn.innerHTML = d.is_active ? 'Desact.' : 'Activar';
      /* btn lista */
      var blt = document.getElementById('dltb-'+id);
      if(blt) blt.innerHTML = d.is_active ? '↓' : '↑';
    }
    btn.disabled = false;
  });
}

/* ── Asignar ── */
function openAssign(tid, name) {
  document.getElementById('massign-title').textContent = '📋 Asignar — '+name;
  document.getElementById('assign-tid').value = tid;
  document.getElementById('asgn-level').value  = '';
  document.getElementById('asgn-grade').innerHTML = '<option value="">— Selecciona nivel primero —</option>';
  document.getElementById('asgn-sub').innerHTML   = '<option value="">— Sin subcurso —</option>';
  openModal('m-assign');
}

ajaxForm(document.getElementById('f-assign'), function(d){
  closeModal('m-assign');
  toast('Asignación creada correctamente', 'ok');
});

/* Cargar grados según nivel */
function loadGrades(lid, targetId) {
  var sel = document.getElementById(targetId);
  sel.innerHTML = '<option value="">Cargando...</option>';
  if (!lid) { sel.innerHTML='<option value="">— Selecciona nivel primero —</option>'; return; }
  fetch('/sistemaescolar/api/catalog.php?act=grades&level_id='+lid,{
    headers:{'X-Requested-With':'XMLHttpRequest'}
  }).then(r=>r.json()).then(d=>{
    sel.innerHTML = '<option value="">— Grado —</option>'+
      (d.data||[]).map(function(g){
        return '<option value="'+g.id+'">'+g.name+'</option>';
      }).join('');
  });
}

/* Cargar subcursos según curso */
function loadSubcourses(cid, targetId) {
  var sel = document.getElementById(targetId);
  sel.innerHTML = '<option value="">Cargando...</option>';
  if (!cid) { sel.innerHTML='<option value="">— Sin subcurso —</option>'; return; }
  fetch('/sistemaescolar/api/catalog.php?act=subcourses&course_id='+cid,{
    headers:{'X-Requested-With':'XMLHttpRequest'}
  }).then(r=>r.json()).then(d=>{
    sel.innerHTML = '<option value="">— Sin subcurso —</option>'+
      (d.data||[]).map(function(s){
        return '<option value="'+s.id+'">'+s.name+'</option>';
      }).join('');
  });
}

/* ── Ver asignaciones ── */
function openViewAssigns(tid, name) {
  document.getElementById('mva-title').textContent = '📋 Asignaciones — '+name;
  document.getElementById('mva-body').innerHTML =
    '<div style="text-align:center;padding:20px">'+
    '<span class="spinner" style="border-color:var(--border);'+
    'border-top-color:var(--navy);width:24px;height:24px;display:inline-block"></span></div>';
  openModal('m-vassign');
  fetch('/sistemaescolar/api/catalog.php?act=teacher_assigns&teacher_id='+tid+
        '&year=<?= $year ?>',{headers:{'X-Requested-With':'XMLHttpRequest'}})
  .then(r=>r.json()).then(d=>{
    if (!d.data || !d.data.length) {
      document.getElementById('mva-body').innerHTML =
        '<div style="text-align:center;padding:24px;color:var(--muted)">'+
        '📭 Sin asignaciones para <?= $year ?>.</div>';
      return;
    }
    var html = d.data.map(function(a){
      return '<div class="assign-row '+(a.is_active?'':'inactive-assign')+'">'+
        '<div>'+
          '<div style="font-size:13px;font-weight:700;color:var(--navy)">'+
            escH(a.co+(a.sub?' › '+a.sub:''))+
          '</div>'+
          '<div class="txt-muted">'+escH(a.lv+' · '+a.gr)+'</div>'+
          '<div class="txt-muted" style="font-size:11px;margin-top:2px">'+
            '📦 '+a.n_bim+' bim. · 🗂 '+a.n_ses+' ses.</div>'+
        '</div>'+
        '<div style="display:flex;gap:5px;align-items:center">'+
          '<span class="bdg '+(a.is_active?'bdg-on':'bdg-off')+'">'+
            (a.is_active?'Activa':'Inactiva')+'</span>'+
          '<button class="btn btn-orange btn-xs" '+
            'onclick="togAssign('+a.id+',this)">'+
            (a.is_active?'Desact.':'Activar')+'</button>'+
          '<button class="btn btn-red btn-xs" '+
            'onclick="delAssign('+a.id+',this)">🗑</button>'+
        '</div>'+
      '</div>';
    }).join('');
    document.getElementById('mva-body').innerHTML = html;
  });
}

function togAssign(aid, btn) {
  btn.disabled=true;
  var fd=new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle_assign'); fd.append('assign_id',aid);
  fetch(location.href,{method:'POST',
    headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
  .then(r=>r.json()).then(d=>{
    toast(d.msg,d.ok?'ok':'err');
    if(d.ok){
      var row=btn.closest('.assign-row');
      row.classList.toggle('inactive-assign',!d.is_active);
      btn.innerHTML=d.is_active?'Desact.':'Activar';
      var bdg=row.querySelector('.bdg');
      if(bdg){ bdg.className='bdg '+(d.is_active?'bdg-on':'bdg-off');
               bdg.textContent=d.is_active?'Activa':'Inactiva'; }
    }
    btn.disabled=false;
  });
}

function delAssign(aid, btn) {
  confirmModal('¿Eliminar esta asignación? Se eliminarán sus bimestres y sesiones.', function(){
    var fd=new FormData();
    fd.append('csrf',CSRF); fd.append('act','del_assign'); fd.append('assign_id',aid);
    fetch(location.href,{method:'POST',
      headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,d.ok?'ok':'err');
      if(d.ok){ btn.closest('.assign-row')?.remove(); }
    });
  },'⚠️ Eliminar asignación');
}

/* ── Resetear contraseña ── */
function openResetPass(id, name) {
  document.getElementById('pass-id').value = id;
  document.getElementById('pass-name').textContent = '👤 '+name;
  openModal('m-pass');
}
ajaxForm(document.getElementById('f-pass'), function(){
  closeModal('m-pass');
});

/* ── Notificación ── */
function openNotifDoc(id, name) {
  document.getElementById('nd-tid').value = id;
  document.getElementById('notif-doc-name').textContent = '📢 Para: '+name;
  openModal('m-notif-doc');
}
ajaxForm(document.getElementById('f-notif-doc'), function(){
  closeModal('m-notif-doc');
});

/* ── Exportar ── */
function exportDocentes() {
  var rows = [['Nombre','DNI','Email','Teléfono','Especialidad','Estado','Asignaciones']];
  document.querySelectorAll('#t-docentes tbody tr').forEach(function(tr){
    var tds = tr.querySelectorAll('td');
    if(tds.length < 7) return;
    rows.push([
      tds[1].querySelector('.dc-name, [style*="font-weight:700"]')?.textContent.trim()||'',
      tds[2].textContent.trim(),
      tds[3].textContent.trim(),
      '',
      tds[4].textContent.trim(),
      tds[7].textContent.trim(),
      tds[5].textContent.trim(),
    ]);
  });
  if(rows.length<=1){
    /* Exportar vista grid */
    rows = [['Nombre','DNI','Estado']];
    document.querySelectorAll('.doc-card').forEach(function(c){
      rows.push([
        c.querySelector('.dc-name')?.textContent.trim()||'',
        c.querySelector('.dc-dni')?.textContent.replace('🪪','').trim()||'',
        c.querySelector('.bdg')?.textContent.trim()||'',
      ]);
    });
  }
  var csv = rows.map(function(r){
    return r.map(function(x){ return '"'+String(x).replace(/"/g,'""')+'"'; }).join(',');
  }).join('\n');
  var b = new Blob(['\uFEFF'+csv],{type:'text/csv;charset=utf-8;'});
  var a = document.createElement('a');
  a.href=URL.createObjectURL(b);
  a.download='docentes_<?= $year ?>.csv';
  a.click();
}

function escH(s){
  return String(s||'')
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;');
}
</script>
<?php layout_end(); ?>