<?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)date('Y');

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

  if ($act === 'toggle') {
    $aid = (int)($_POST['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]);
  }

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

  if ($act === 'bulk_bimesters') {
    $aid  = (int)($_POST['assign_id'] ?? 0);
    $max  = (int)($_POST['n_bim']     ?? 4);
    $created = 0;
    for ($n = 1; $n <= $max; $n++) {
      try {
        $pdo->prepare("INSERT IGNORE INTO bimesters
          (assignment_id,number,name) VALUES(?,?,?)")
          ->execute([$aid,$n,"Bimestre $n"]);
        $created++;
      } catch (PDOException) {}
    }
    json_ok("$created bimestre(s) creados.");
  }
}

/* GET — filtros */
$f_level  = (int)($_GET['level']   ?? 0);
$f_grade  = (int)($_GET['grade']   ?? 0);
$f_status = $_GET['status']        ?? 'active';
$f_doc    = (int)($_GET['teacher'] ?? 0);

$where  = ["ta.school_year=$year"];
$params = [];
if ($f_level)  { $where[]="ta.level_id=?";   $params[]=$f_level; }
if ($f_grade)  { $where[]="ta.grade_id=?";   $params[]=$f_grade; }
if ($f_doc)    { $where[]="ta.teacher_id=?"; $params[]=$f_doc; }
if ($f_status === 'active')   $where[] = 'ta.is_active=1';
if ($f_status === 'inactive') $where[] = 'ta.is_active=0';
$whereSQL = 'WHERE '.implode(' AND ',$where);

$assigns = $pdo->prepare("
  SELECT ta.*,
    l.name AS lv, g.name AS gr,
    c.name AS co, c.color AS co_color,
    sc.name AS sub,
    u.full_name AS docente,
    COUNT(DISTINCT b.id)  AS n_bim,
    COUNT(DISTINCT s.id)  AS n_ses,
    COUNT(DISTINCT sd.id) AS n_docs,
    COUNT(DISTINCT t.id)  AS n_tasks,
    COUNT(DISTINCT sy.id) AS has_syl
  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
  JOIN users u ON u.id=ta.teacher_id
  LEFT JOIN bimesters b ON b.assignment_id=ta.id
  LEFT JOIN sessions s  ON s.bimester_id=b.id
  LEFT JOIN session_documents sd ON sd.session_id=s.id AND sd.is_active=1
  LEFT JOIN tasks t ON t.assignment_id=ta.id AND t.school_year=$year
  LEFT JOIN syllabi sy ON sy.assignment_id=ta.id
  $whereSQL
  GROUP BY ta.id
  ORDER BY l.sort_order, g.sort_order, c.name
");
$assigns->execute($params);
$assigns = $assigns->fetchAll();

$levels   = $pdo->query("SELECT * FROM levels  WHERE is_active=1 ORDER BY sort_order")->fetchAll();
$grades   = $pdo->query("SELECT * FROM grades  WHERE is_active=1 ORDER BY level_id,sort_order")->fetchAll();
$teachers = $pdo->query("SELECT id,full_name FROM users WHERE role='DOCENTE' AND is_active=1 ORDER BY full_name")->fetchAll();

/* Agrupar por nivel→grado */
$grouped = [];
foreach ($assigns as $a) {
  $key = $a['lv'].'___'.$a['gr'];
  $grouped[$key][] = $a;
}

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

<div style="display:flex;align-items:center;justify-content:space-between;
     flex-wrap:wrap;gap:12px;margin-bottom:20px">
  <div>
    <h2 style="font-size:18px;font-weight:800;color:var(--navy)">
      📋 Asignaciones — <?= $year ?>
    </h2>
    <p class="txt-muted">
      <?= count($assigns) ?> asignaciones encontradas
    </p>
  </div>
  <a href="docentes.php" class="btn btn-navy btn-sm">
    ➕ Nueva asignación (desde docentes)
  </a>
</div>

<!-- FILTROS -->
<div class="card" style="padding:12px 16px;margin-bottom:16px">
  <form method="get"
        style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
    <div class="fg" style="min-width:140px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Nivel</label>
      <select name="level" onchange="this.form.submit()">
        <option value="">Todos</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:130px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Grado</label>
      <select name="grade">
        <option value="">Todos</option>
        <?php foreach ($grades as $gr):
          if ($f_level && (int)$gr['level_id'] !== $f_level) continue; ?>
          <option value="<?= (int)$gr['id'] ?>"
            <?= $f_grade===(int)$gr['id']?'selected':'' ?>>
            <?= htmlspecialchars($gr['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fg" style="min-width:180px">
      <label style="font-size:11px;font-weight:700;color:var(--navy)">Docente</label>
      <select name="teacher">
        <option value="">Todos</option>
        <?php foreach ($teachers as $t): ?>
          <option value="<?= (int)$t['id'] ?>"
            <?= $f_doc===(int)$t['id']?'selected':'' ?>>
            <?= htmlspecialchars($t['full_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':'' ?>>Activas</option>
        <option value="inactive" <?= $f_status==='inactive'?'selected':'' ?>>Inactivas</option>
      </select>
    </div>
    <div style="display:flex;gap:6px;align-items:flex-end">
      <button class="btn btn-navy btn-sm">🔍 Filtrar</button>
      <a href="?" class="btn btn-outline btn-sm">✕ Limpiar</a>
    </div>
  </form>
</div>

<!-- AGRUPADO POR NIVEL/GRADO -->
<?php if (!$assigns): ?>
<div class="card" style="text-align:center;padding:40px;color:var(--muted)">
  <div style="font-size:40px;margin-bottom:10px">📭</div>
  Sin asignaciones con los filtros aplicados.
</div>
<?php endif; ?>

<?php foreach ($grouped as $key => $rows):
  [$lv_name,$gr_name] = explode('___',$key);
?>
<div style="margin-bottom:18px">
  <!-- Cabecera grupo -->
  <div style="display:flex;align-items:center;gap:10px;
       margin-bottom:10px;padding:10px 14px;
       background:var(--navy);border-radius:var(--r);color:#fff">
    <div style="font-size:15px;font-weight:800">
      🏫 <?= htmlspecialchars($lv_name) ?>
      <span style="opacity:.7;font-size:13px">· <?= htmlspecialchars($gr_name) ?></span>
    </div>
    <span style="margin-left:auto;font-size:12px;opacity:.75">
      <?= count($rows) ?> asignación(es)
    </span>
  </div>

  <div style="display:grid;
    grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px">
    <?php foreach ($rows as $a):
      $color  = $a['co_color'] ?? '#0d1b6e';
      $active = (int)$a['is_active'];
    ?>
    <div class="asgn-card <?= $active?'':'asgn-inactive' ?>"
         id="asgn-<?= (int)$a['id'] ?>"
         style="border-left:4px solid <?= htmlspecialchars($color) ?>">

      <!-- Course tag -->
      <div style="display:flex;align-items:flex-start;
           justify-content:space-between;gap:6px;margin-bottom:8px">
        <div>
          <div style="font-size:12px;font-weight:800;color:var(--navy)">
            <?= htmlspecialchars($a['co'].($a['sub']?' › '.$a['sub']:'')) ?>
          </div>
          <div class="txt-muted" style="margin-top:2px">
            👨‍🏫 <?= htmlspecialchars($a['docente']) ?>
          </div>
        </div>
        <span class="bdg <?= $active?'bdg-on':'bdg-off' ?>"
              id="ab-<?= (int)$a['id'] ?>"
              style="font-size:10px;flex-shrink:0">
          <?= $active?'Activa':'Inactiva' ?>
        </span>
      </div>

      <!-- Métricas -->
      <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px">
        <span class="mini-chip">📦 <?= (int)$a['n_bim'] ?> bim.</span>
        <span class="mini-chip">🗂 <?= (int)$a['n_ses'] ?> ses.</span>
        <span class="mini-chip">📎 <?= (int)$a['n_docs'] ?> docs.</span>
        <span class="mini-chip">📝 <?= (int)$a['n_tasks'] ?> tar.</span>
        <?php if ($a['has_syl']): ?>
          <span class="mini-chip" style="color:var(--green)">📄 ✅</span>
        <?php endif; ?>
      </div>

      <!-- Acciones -->
      <div style="display:flex;gap:5px;flex-wrap:wrap">
        <a href="bimestres.php?assign_id=<?= (int)$a['id'] ?>"
           class="btn btn-teal btn-xs">📦 Bimestres</a>
        <button class="btn btn-outline btn-xs"
                onclick="bulkBim(<?= (int)$a['id'] ?>)">
          ➕ Bim. auto
        </button>
        <button class="btn btn-orange btn-xs"
                id="atb-<?= (int)$a['id'] ?>"
                onclick="togAsgn(<?= (int)$a['id'] ?>,this)">
          <?= $active?'Desact.':'Activar' ?>
        </button>
        <button class="btn btn-red btn-xs"
                onclick="delAsgn(<?= (int)$a['id'] ?>)">
          🗑
        </button>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endforeach; ?>

<!-- Modal bimestres masivos -->
<div class="modal-ov" id="m-bulk-bim">
  <div class="modal" style="max-width:360px">
    <h3>📦 Crear Bimestres Automáticamente</h3>
    <form id="f-bulk-bim" method="post">
      <input type="hidden" name="csrf"      value="<?= $csrf ?>">
      <input type="hidden" name="act"       value="bulk_bimesters">
      <input type="hidden" name="assign_id" id="bb-aid">
      <div class="fg" style="margin-bottom:14px">
        <label>Cantidad de bimestres</label>
        <input name="n_bim" type="number" min="1" max="8"
               value="<?= (int)sys_cfg('bimesters_per_year',4) ?>">
      </div>
      <div style="background:#e3f2fd;border-radius:8px;padding:10px 14px;
           font-size:12px;color:var(--sky);margin-bottom:14px">
        ℹ️ Solo crea los bimestres que aún no existan.
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-outline"
                onclick="closeModal('m-bulk-bim')">Cancelar</button>
        <button type="submit" class="btn btn-teal">📦 Crear</button>
      </div>
    </form>
  </div>
</div>

<style>
.asgn-card{
  background:var(--card);border-radius:var(--r);
  padding:12px 14px;box-shadow:var(--sh);
  transition:var(--tr)
}
.asgn-card:hover{ box-shadow:0 6px 20px rgba(0,0,0,.1) }
.asgn-inactive{ opacity:.6 }
</style>

<script>
var CSRF='<?= $csrf ?>';
function openModal(id){ document.getElementById(id).classList.add('show'); }
function closeModal(id){ document.getElementById(id).classList.remove('show'); }

function togAsgn(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){
      var c=document.getElementById('asgn-'+id);
      c?.classList.toggle('asgn-inactive',!d.is_active);
      var b=document.getElementById('ab-'+id);
      if(b){ b.className='bdg '+(d.is_active?'bdg-on':'bdg-off');
             b.textContent=d.is_active?'Activa':'Inactiva'; }
      btn.innerHTML=d.is_active?'Desact.':'Activar';
    }
    btn.disabled=false;
  });
}

function delAsgn(id){
  confirmModal('¿Eliminar asignación? Se perderán sus bimestres y sesiones.',function(){
    var fd=new FormData();
    fd.append('csrf',CSRF); fd.append('act','delete'); fd.append('id',id);
    fetch(location.href,{method:'POST',
      headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
    .then(r=>r.json()).then(d=>{
      toast(d.msg,d.ok?'ok':'err');
      if(d.ok) document.getElementById('asgn-'+id)?.remove();
    });
  },'⚠️ Eliminar asignación');
}

function bulkBim(aid){
  document.getElementById('bb-aid').value=aid;
  openModal('m-bulk-bim');
}
ajaxForm(document.getElementById('f-bulk-bim'),function(d){
  closeModal('m-bulk-bim');
});

document.querySelectorAll('.modal-ov').forEach(function(ov){
  ov.addEventListener('click',function(e){
    if(e.target===this) this.classList.remove('show');
  });
});
</script>
<?php layout_end(); ?>