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

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

  /* Crear bimestres automático (1, 2, 3, 4 o todos) */
  if ($act === 'create_bimesters') {
    $aid   = (int)($_POST['assignment_id'] ?? 0);
    $nums  = $_POST['bim_nums'] ?? [1,2,3,4];
    if (!$aid) json_err('Selecciona una asignación.');
    $created = 0;
    foreach ($nums as $n) {
      $n = (int)$n;
      if ($n < 1 || $n > 6) continue;
      try {
        $pdo->prepare("INSERT INTO bimesters (assignment_id,number,name) VALUES(?,?,?)")
            ->execute([$aid, $n, "Bimestre $n"]);
        $created++;
      } catch (PDOException) {}
    }
    json_ok("$created bimestre(s) creado(s).", ['created'=>$created]);
  }

  /* Actualizar nombre/fechas de bimestre */
  if ($act === 'update_bimester') {
    $id    = (int)($_POST['id']         ?? 0);
    $name  = trim($_POST['name']        ?? '');
    $start = $_POST['start_date']       ?? null;
    $end   = $_POST['end_date']         ?? null;
    $pdo->prepare("UPDATE bimesters SET name=?,start_date=?,end_date=? WHERE id=?")
        ->execute([$name ?: "Bimestre", $start ?: null, $end ?: null, $id]);
    json_ok('Bimestre actualizado.');
  }

  /* Toggle bimestre */
  if ($act === 'toggle_bimester') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('UPDATE bimesters SET is_active=1-is_active WHERE id=?')->execute([$id]);
    $is = (int)$pdo->query("SELECT is_active FROM bimesters WHERE id=$id")->fetchColumn();
    json_ok('Estado actualizado.', ['is_active'=>$is]);
  }

  /* Eliminar bimestre */
  if ($act === 'del_bimester') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('DELETE FROM bimesters WHERE id=?')->execute([$id]);
    json_ok('Bimestre eliminado.');
  }

  /* Crear sesiones para un bimestre */
  if ($act === 'create_sessions') {
    $bid   = (int)($_POST['bimester_id'] ?? 0);
    $count = min(50, max(1, (int)($_POST['count'] ?? 1)));
    $from  = (int)($_POST['from_num']   ?? 1);
    if (!$bid) json_err('Bimestre inválido.');
    $created = 0; $rows = [];
    for ($i = 0; $i < $count; $i++) {
      $n = $from + $i;
      try {
        $pdo->prepare("INSERT INTO sessions (bimester_id,number,title) VALUES(?,?,?)")
            ->execute([$bid, $n, "Sesión $n"]);
        $sid = (int)$pdo->lastInsertId();
        $rows[] = ['id'=>$sid,'number'=>$n,'title'=>"Sesión $n",
                   'description'=>'','video_url'=>'','is_active'=>1];
        $created++;
      } catch (PDOException) {}
    }
    json_ok("$created sesión(es) creada(s).", ['sessions'=>$rows]);
  }

  /* Actualizar sesión */
  if ($act === 'update_session') {
    $id    = (int)($_POST['id']          ?? 0);
    $title = trim($_POST['title']        ?? '');
    $desc  = trim($_POST['description']  ?? '');
    $video = trim($_POST['video_url']    ?? '');
    $pdo->prepare("UPDATE sessions SET title=?,description=?,video_url=? WHERE id=?")
        ->execute([$title ?: "Sesión", $desc, $video, $id]);
    json_ok('Sesión guardada.');
  }

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

  /* Eliminar sesión */
  if ($act === 'del_session') {
    $id = (int)($_POST['id'] ?? 0);
    $pdo->prepare('DELETE FROM sessions WHERE id=?')->execute([$id]);
    json_ok('Sesión eliminada.');
  }
}

/* ── GET ────────────────────────────────────────────── */
$teachers = $pdo->query("SELECT id,full_name,dni FROM users
                          WHERE role='DOCENTE' AND is_active=1
                          ORDER BY full_name")->fetchAll();

$sel_teacher = (int)($_GET['teacher_id'] ?? 0);
$sel_assign  = (int)($_GET['assign_id']  ?? 0);

$assignments = [];
if ($sel_teacher) {
  $s = $pdo->prepare("
    SELECT ta.*,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.teacher_id=? AND ta.school_year=? AND ta.is_active=1
    ORDER BY l.sort_order,g.sort_order,c.name
  ");
  $s->execute([$sel_teacher, $year]);
  $assignments = $s->fetchAll();
}

$bimesters = [];
if ($sel_assign) {
  $bimesters = $pdo->query("
    SELECT b.*,
      (SELECT COUNT(*) FROM sessions s WHERE s.bimester_id=b.id) AS n_sessions
    FROM bimesters b
    WHERE b.assignment_id=$sel_assign
    ORDER BY b.number
  ")->fetchAll();
}

layout_start('Bimestres y Sesiones', $u);
$csrf = htmlspecialchars(csrf_token());
$max_bim = (int)(sys_cfg('bimesters_per_year', 4));
$max_ses = (int)(sys_cfg('max_sessions_per_bimester', 50));
?>

<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px">
  <div>
    <h2 style="font-size:18px;font-weight:800;color:var(--navy)">
      📋 Bimestres y Sesiones
    </h2>
    <p class="txt-muted">Crea y gestiona bimestres y sesiones por asignación de docente</p>
  </div>
</div>

<!-- ── PASO 1: Seleccionar docente ── -->
<div class="card">
  <div class="card-title">🔎 Paso 1 — Selecciona Docente y Asignación</div>
  <form method="get" id="f-filter">
    <input type="hidden" name="year" value="<?= $year ?>">
    <div class="form-grid">
      <div class="fg">
        <label>Docente</label>
        <select name="teacher_id" id="sel-teacher"
                onchange="this.form.submit()">
          <option value="">— Selecciona docente —</option>
          <?php foreach ($teachers as $t): ?>
            <option value="<?= (int)$t['id'] ?>"
              <?= $sel_teacher===(int)$t['id']?'selected':'' ?>>
              <?= htmlspecialchars($t['full_name']) ?>
              (<?= htmlspecialchars($t['dni']) ?>)
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($assignments): ?>
      <div class="fg">
        <label>Asignación (Subcurso)</label>
        <select name="assign_id" onchange="this.form.submit()">
          <option value="">— Selecciona asignación —</option>
          <?php foreach ($assignments as $a): ?>
            <option value="<?= (int)$a['id'] ?>"
              <?= $sel_assign===(int)$a['id']?'selected':'' ?>>
              <?= htmlspecialchars($a['lv'].' · '.$a['gr'].' | '.$a['co'].($a['sub']?' › '.$a['sub']:'')) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>
    </div>
  </form>
</div>

<?php if ($sel_assign): ?>
<!-- ── PASO 2: Crear bimestres ── -->
<div class="card" id="bim-creator">
  <div class="card-title">
    📦 Paso 2 — Crear Bimestres
    <span class="txt-muted" style="font-size:12px;font-weight:400;margin-left:8px">
      Bimestres configurados: <?= $max_bim ?>
    </span>
  </div>

  <!-- Bloques de bimestres disponibles -->
  <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">
    <?php
    $existing_nums = array_column($bimesters,'number');
    for ($n=1; $n<=$max_bim; $n++):
      $exists = in_array($n, $existing_nums, true);
    ?>
    <div class="bim-block <?= $exists?'exists':'' ?>"
         id="bbl-<?= $n ?>"
         onclick="<?= $exists ? '' : "toggleBimBlock($n,this)" ?>">
      <div class="bbl-num"><?= $n ?></div>
      <div class="bbl-lbl">Bimestre <?= $n ?></div>
      <?php if ($exists): ?>
        <div class="bbl-check">✅</div>
      <?php else: ?>
        <div class="bbl-check" id="bbl-chk-<?= $n ?>">⬜</div>
      <?php endif; ?>
    </div>
    <?php endfor; ?>
  </div>

  <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <button class="btn btn-navy" onclick="createSelectedBim()">
      ➕ Crear bimestres seleccionados
    </button>
    <button class="btn btn-teal" onclick="createAllBim()">
      ⚡ Crear todos los <?= $max_bim ?> bimestres
    </button>
    <span class="txt-muted" id="bim-sel-txt">Ninguno seleccionado</span>
  </div>
</div>

<!-- ── PASO 3: Bimestres y Sesiones (Bloques) ── -->
<?php if ($bimesters): ?>
<div id="bim-list">
<?php foreach ($bimesters as $bim):
  $sessions = $pdo->query("SELECT * FROM sessions WHERE bimester_id={$bim['id']} ORDER BY number")->fetchAll();
  $next_num = count($sessions) > 0 ? max(array_column($sessions,'number')) + 1 : 1;
?>
<div class="bim-panel" id="bim-<?= (int)$bim['id'] ?>">

  <!-- Cabecera bimestre -->
  <div class="bim-header"
       onclick="toggleBimPanel(<?= (int)$bim['id'] ?>)">
    <div style="display:flex;align-items:center;gap:12px;flex:1">
      <div class="bim-num-badge"><?= (int)$bim['number'] ?></div>
      <div>
        <div class="bim-title" id="bim-tit-<?= (int)$bim['id'] ?>">
          <?= htmlspecialchars($bim['name']) ?>
        </div>
        <div class="txt-muted" style="font-size:11px">
          🗂 <?= (int)$bim['n_sessions'] ?> sesiones
          <?php if ($bim['start_date']): ?>
            · 📅 <?= date('d/m/Y',strtotime($bim['start_date'])) ?>
            — <?= $bim['end_date']?date('d/m/Y',strtotime($bim['end_date'])):'?' ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <div style="display:flex;gap:6px;align-items:center">
      <span class="bdg <?= (int)$bim['is_active']?'bdg-on':'bdg-off' ?>"
            id="bim-st-<?= (int)$bim['id'] ?>">
        <?= (int)$bim['is_active']?'Activo':'Inactivo' ?>
      </span>
      <button class="btn btn-outline btn-xs"
              onclick="event.stopPropagation();editBim(<?= (int)$bim['id'] ?>,
              '<?= addslashes($bim['name']) ?>',
              '<?= $bim['start_date']??'' ?>',
              '<?= $bim['end_date']??'' ?>')">✏️</button>
      <button class="btn btn-orange btn-xs"
              onclick="event.stopPropagation();togBim(<?= (int)$bim['id'] ?>,this)">
        <?= (int)$bim['is_active']?'Desact.':'Activar' ?>
      </button>
      <button class="btn btn-red btn-xs"
              onclick="event.stopPropagation();delBim(<?= (int)$bim['id'] ?>)">🗑</button>
      <span class="bim-arrow" id="barr-<?= (int)$bim['id'] ?>">▼</span>
    </div>
  </div>

  <!-- Cuerpo bimestre -->
  <div class="bim-body" id="bbd-<?= (int)$bim['id'] ?>">

    <!-- Agregar sesiones -->
    <div class="ses-add-bar">
      <span style="font-size:13px;font-weight:700;color:var(--navy)">
        ➕ Agregar sesiones
      </span>
      <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px">
        <label style="font-size:12px;color:var(--muted)">
          ¿Cuántas sesiones?
        </label>
        <input type="number" id="sc-<?= (int)$bim['id'] ?>"
               min="1" max="<?= $max_ses ?>" value="1"
               style="width:70px;padding:6px 10px;border:1.5px solid var(--border);
                      border-radius:8px;font-size:13px;text-align:center">
        <button class="btn btn-green btn-sm"
                onclick="addSessions(<?= (int)$bim['id'] ?>,<?= $next_num ?>)">
          ⚡ Crear sesiones
        </button>
        <span class="txt-muted" style="font-size:11px">
          (máx. <?= $max_ses ?> por bimestre)
        </span>
      </div>
    </div>

    <!-- Grid de sesiones -->
    <div class="ses-grid" id="sg-<?= (int)$bim['id'] ?>">
      <?php foreach ($sessions as $ses): ?>
        <?= renderSession($ses, $csrf) ?>
      <?php endforeach; ?>
      <?php if (!$sessions): ?>
      <div class="ses-empty" id="se-<?= (int)$bim['id'] ?>">
        <div style="font-size:28px;margin-bottom:8px">📭</div>
        No hay sesiones. Crea las primeras arriba.
      </div>
      <?php endif; ?>
    </div>

  </div><!-- /bim-body -->
</div><!-- /bim-panel -->
<?php endforeach; ?>
</div><!-- /bim-list -->
<?php else: ?>
<div class="card" style="text-align:center;padding:30px;color:var(--muted)">
  <div style="font-size:36px;margin-bottom:10px">📦</div>
  Aún no hay bimestres. Créalos en el paso 2.
</div>
<?php endif; ?>
<?php endif; // sel_assign ?>

<!-- Modal editar bimestre -->
<div class="modal-ov" id="m-bim">
  <div class="modal" style="max-width:420px">
    <h3>✏️ Editar Bimestre</h3>
    <form id="f-edit-bim" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="update_bimester">
      <input type="hidden" name="id"   id="eb-id">
      <div class="fg" style="margin-bottom:12px">
        <label>Nombre</label>
        <input name="name" id="eb-name" type="text" placeholder="Ej: I Bimestre">
      </div>
      <div class="form-grid">
        <div class="fg">
          <label>Fecha inicio</label>
          <input name="start_date" id="eb-start" type="date">
        </div>
        <div class="fg">
          <label>Fecha fin</label>
          <input name="end_date" id="eb-end" type="date">
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-bim')">Cancelar</button>
        <button type="submit" class="btn btn-navy">💾 Guardar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal editar sesión -->
<div class="modal-ov" id="m-ses">
  <div class="modal" style="max-width:480px">
    <h3>✏️ Editar Sesión</h3>
    <form id="f-edit-ses" method="post">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="act"  value="update_session">
      <input type="hidden" name="id"   id="es-id">
      <div class="fg" style="margin-bottom:12px">
        <label>Nombre de la sesión</label>
        <input name="title" id="es-title" type="text" placeholder="Ej: Sesión 1 — Introducción">
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>Descripción / Tema</label>
        <textarea name="description" id="es-desc" rows="3"
                  placeholder="Tema o descripción de la sesión"></textarea>
      </div>
      <div class="fg" style="margin-bottom:12px">
        <label>🎬 URL del video (YouTube, Drive...)</label>
        <input name="video_url" id="es-video" type="url"
               placeholder="https://youtube.com/...">
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-ses')">Cancelar</button>
        <button type="submit" class="btn btn-navy">💾 Guardar sesión</button>
      </div>
    </form>
  </div>
</div>

<style>
/* ── Bloques bimestre selector ── */
.bim-block{
  width:100px;padding:14px 10px;border-radius:var(--r);
  background:var(--bg);border:2px solid var(--border);
  text-align:center;cursor:pointer;transition:var(--tr);user-select:none
}
.bim-block:hover:not(.exists){
  border-color:var(--navy);background:#e8eaf6
}
.bim-block.selected{
  border-color:var(--navy);background:#e8eaf6
}
.bim-block.exists{
  border-color:var(--green);background:#e8f5e9;cursor:default
}
.bbl-num{font-size:24px;font-weight:800;color:var(--navy);line-height:1}
.bbl-lbl{font-size:11px;color:var(--muted);margin-top:3px}
.bbl-check{font-size:16px;margin-top:6px}

/* ── Panel bimestre ── */
.bim-panel{
  background:var(--card);border-radius:var(--r);
  box-shadow:var(--sh);margin-bottom:14px;overflow:hidden
}
.bim-header{
  display:flex;align-items:center;justify-content:space-between;
  padding:14px 18px;cursor:pointer;background:var(--card);
  border-bottom:2px solid var(--bg);transition:var(--tr);
  flex-wrap:wrap;gap:8px
}
.bim-header:hover{background:#f8faff}
.bim-num-badge{
  width:38px;height:38px;border-radius:50%;background:var(--navy);
  color:#fff;display:flex;align-items:center;justify-content:center;
  font-size:16px;font-weight:800;flex-shrink:0
}
.bim-title{font-size:15px;font-weight:700;color:var(--navy)}
.bim-arrow{font-size:12px;color:var(--muted);transition:var(--tr)}
.bim-arrow.up{transform:rotate(180deg)}
.bim-body{padding:16px 18px}
.ses-add-bar{
  background:var(--bg);border-radius:10px;padding:12px 16px;
  margin-bottom:16px
}

/* ── Grid sesiones ── */
.ses-grid{
  display:grid;
  grid-template-columns:repeat(auto-fill,minmax(220px,1fr));
  gap:12px
}
.ses-card{
  background:var(--bg);border-radius:10px;padding:14px;
  border-left:4px solid var(--navy);transition:var(--tr);
  position:relative
}
.ses-card:hover{background:#e8eaf6;transform:translateY(-2px)}
.ses-card.inactive{opacity:.55;border-left-color:var(--muted)}
.ses-num{
  font-size:11px;font-weight:700;color:var(--muted);
  text-transform:uppercase;letter-spacing:.5px
}
.ses-title{font-size:13px;font-weight:700;color:var(--navy);
           margin-top:3px;margin-bottom:4px}
.ses-desc{font-size:11px;color:var(--muted);
          overflow:hidden;display:-webkit-box;
          -webkit-line-clamp:2;-webkit-box-orient:vertical}
.ses-video{font-size:11px;color:var(--sky);margin-top:4px}
.ses-acts{display:flex;gap:5px;margin-top:10px;flex-wrap:wrap}
.ses-empty{
  grid-column:1/-1;text-align:center;
  padding:24px;color:var(--muted);font-size:13px
}
</style>

<?php
function renderSession(array $ses, string $csrf): string {
  $id    = (int)$ses['id'];
  $act   = (int)$ses['is_active'];
  $title = htmlspecialchars($ses['title']);
  $desc  = htmlspecialchars($ses['description'] ?? '');
  $vid   = $ses['video_url'] ?? '';
  $tesc  = addslashes($ses['title']);
  $desc2 = addslashes($ses['description'] ?? '');
  $vid2  = addslashes($ses['video_url'] ?? '');
  return <<<HTML
<div class="ses-card {$( $act ? '' : 'inactive' )}" id="sc-{$id}">
  <div class="ses-num">Sesión {$ses['number']}</div>
  <div class="ses-title" id="st-{$id}">{$title}</div>
  <div class="ses-desc">{$desc}</div>
  {$( $vid ? "<div class='ses-video'>🎬 Video adjunto</div>" : '' )}
  <div class="ses-acts">
    <button class="btn btn-outline btn-xs"
            onclick="editSes({$id},'$tesc','$desc2','$vid2')">✏️</button>
    <button class="btn btn-orange btn-xs"
            onclick="togSes({$id},this)">{$( $act ? 'Desact.' : 'Activar' )}</button>
    <button class="btn btn-red btn-xs"
            onclick="delSes({$id})">🗑</button>
  </div>
</div>
HTML;
}
?>

<script>
var CSRF   = '<?= $csrf ?>';
var AID    = <?= $sel_assign ?: 0 ?>;
var _selBim = new Set();

/* ── Selección bloques bimestre ── */
function toggleBimBlock(n, el) {
  if (_selBim.has(n)) {
    _selBim.delete(n);
    el.classList.remove('selected');
    document.getElementById('bbl-chk-'+n).textContent = '⬜';
  } else {
    _selBim.add(n);
    el.classList.add('selected');
    document.getElementById('bbl-chk-'+n).textContent = '✅';
  }
  var t = document.getElementById('bim-sel-txt');
  t.textContent = _selBim.size
    ? 'Seleccionados: '+[..._selBim].sort().map(n=>'Bimestre '+n).join(', ')
    : 'Ninguno seleccionado';
}
function createSelectedBim() {
  if (!_selBim.size) { toast('Selecciona al menos un bimestre','err'); return; }
  _createBim([..._selBim]);
}
function createAllBim() {
  var nums = [];
  for (var i=1; i<=<?= $max_bim ?>; i++) nums.push(i);
  _createBim(nums);
}
function _createBim(nums) {
  var fd = new FormData();
  fd.append('csrf', CSRF);
  fd.append('act', 'create_bimesters');
  fd.append('assignment_id', AID);
  nums.forEach(function(n){ fd.append('bim_nums[]', n); });
  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) setTimeout(()=>location.reload(), 800);
  });
}

/* ── Toggle panel ── */
function toggleBimPanel(id) {
  var b = document.getElementById('bbd-'+id);
  var a = document.getElementById('barr-'+id);
  var shown = b.style.display !== 'none';
  b.style.display = shown ? 'none' : 'block';
  a.classList.toggle('up', !shown);
}

/* ── Editar bimestre ── */
function editBim(id, name, start, end) {
  document.getElementById('eb-id').value    = id;
  document.getElementById('eb-name').value  = name;
  document.getElementById('eb-start').value = start;
  document.getElementById('eb-end').value   = end;
  document.getElementById('m-bim').classList.add('show');
}
function closeModal(id) {
  document.getElementById(id).classList.remove('show');
}
ajaxForm(document.getElementById('f-edit-bim'), function(d){
  closeModal('m-bim');
});

/* ── Toggle bimestre ── */
function togBim(id, btn) {
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle_bimester'); fd.append('id',id);
  btn.disabled = true;
  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.innerHTML = d.is_active ? 'Desact.' : 'Activar';
      var st = document.getElementById('bim-st-'+id);
      if (st) {
        st.className = 'bdg '+(d.is_active?'bdg-on':'bdg-off');
        st.textContent = d.is_active?'Activo':'Inactivo';
      }
    }
    btn.disabled = false;
  });
}

/* ── Eliminar bimestre ── */
function delBim(id) {
  confirmModal(
    '¿Eliminar este bimestre y todas sus sesiones?',
    function(){
      var fd = new FormData();
      fd.append('csrf',CSRF); fd.append('act','del_bimester'); 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){ var el=document.getElementById('bim-'+id); if(el)el.remove(); }
      });
    }, '⚠️ Confirmar eliminación'
  );
}

/* ── Crear sesiones ── */
function addSessions(bid, fromNum) {
  var count = parseInt(document.getElementById('sc-'+bid).value) || 1;
  count = Math.min(<?= $max_ses ?>, Math.max(1, count));
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','create_sessions');
  fd.append('bimester_id',bid); fd.append('count',count);
  fd.append('from_num',fromNum);
  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 && d.sessions) {
      var grid = document.getElementById('sg-'+bid);
      var empty = document.getElementById('se-'+bid);
      if (empty) empty.remove();
      d.sessions.forEach(function(s){
        grid.insertAdjacentHTML('beforeend', buildSesCard(s));
      });
      // Actualizar next_num para el botón
    }
  });
}

function buildSesCard(s) {
  return `<div class="ses-card" id="sc-${s.id}">
    <div class="ses-num">Sesión ${s.number}</div>
    <div class="ses-title" id="st-${s.id}">${s.title}</div>
    <div class="ses-desc"></div>
    <div class="ses-acts">
      <button class="btn btn-outline btn-xs" onclick="editSes(${s.id},'${s.title}','','')">✏️</button>
      <button class="btn btn-orange btn-xs" onclick="togSes(${s.id},this)">Desact.</button>
      <button class="btn btn-red btn-xs" onclick="delSes(${s.id})">🗑</button>
    </div>
  </div>`;
}

/* ── Editar sesión ── */
function editSes(id, title, desc, video) {
  document.getElementById('es-id').value    = id;
  document.getElementById('es-title').value = title;
  document.getElementById('es-desc').value  = desc;
  document.getElementById('es-video').value = video;
  document.getElementById('m-ses').classList.add('show');
}
ajaxForm(document.getElementById('f-edit-ses'), function(d){
  closeModal('m-ses');
  var id = document.getElementById('es-id').value;
  var t  = document.getElementById('st-'+id);
  if (t) t.textContent = document.getElementById('es-title').value;
});

/* ── Toggle sesión ── */
function togSes(id, btn) {
  var fd = new FormData();
  fd.append('csrf',CSRF); fd.append('act','toggle_session'); fd.append('id',id);
  btn.disabled=true;
  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 c = document.getElementById('sc-'+id);
      if(c) c.classList.toggle('inactive', !d.is_active);
      btn.innerHTML = d.is_active ? 'Desact.' : 'Activar';
    }
    btn.disabled=false;
  });
}

/* ── Eliminar sesión ── */
function delSes(id) {
  confirmModal('¿Eliminar esta sesión y sus documentos?', function(){
    var fd = new FormData();
    fd.append('csrf',CSRF); fd.append('act','del_session'); 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){ var el=document.getElementById('sc-'+id); if(el)el.remove(); }
    });
  });
}
</script>
<?php layout_end(); ?>