<?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'));
$max = (int)sys_cfg('tasks_max_grade', 20);

/* ══════════════════════════════════════════════════════════
   DATOS PARA GRÁFICAS
   ══════════════════════════════════════════════════════════ */

/* ── 1. Entregas por mes ─────────────────────────────── */
$by_month = $pdo->query("
  SELECT
    MONTH(ts.submitted_at) AS mes,
    COUNT(*)               AS total,
    SUM(ts.grade IS NOT NULL) AS calificadas
  FROM task_submissions ts
  JOIN tasks t ON t.id=ts.task_id
  WHERE t.school_year=$year
  GROUP BY MONTH(ts.submitted_at)
  ORDER BY mes
")->fetchAll();

$meses_labels = ['','Ene','Feb','Mar','Abr','May','Jun',
                  'Jul','Ago','Sep','Oct','Nov','Dic'];
$entregas_data    = array_fill(1,12,0);
$calificadas_data = array_fill(1,12,0);
foreach ($by_month as $r) {
  $entregas_data[(int)$r['mes']]    = (int)$r['total'];
  $calificadas_data[(int)$r['mes']] = (int)$r['calificadas'];
}

/* ── 2. Promedio por curso ───────────────────────────── */
$by_course = $pdo->query("
  SELECT
    CONCAT(c.name, IFNULL(CONCAT(' › ',sc.name),'')) AS label,
    ROUND(AVG(ts.grade), 1)                           AS promedio,
    COUNT(DISTINCT ts.student_id)                     AS alumnos,
    COUNT(ts.id)                                      AS entregas
  FROM task_submissions ts
  JOIN tasks t  ON t.id=ts.task_id
  JOIN teacher_assignments ta ON ta.id=t.assignment_id
  JOIN courses c ON c.id=ta.course_id
  LEFT JOIN subcourses sc ON sc.id=ta.subcourse_id
  WHERE ts.grade IS NOT NULL AND t.school_year=$year
  GROUP BY ta.course_id, ta.subcourse_id
  ORDER BY promedio DESC
  LIMIT 12
")->fetchAll();

/* ── 3. Promedio por grado ───────────────────────────── */
$by_grade = $pdo->query("
  SELECT
    CONCAT(l.name,' · ',g.name) AS label,
    ROUND(AVG(ts.grade / $max * $max), 1) AS promedio,
    COUNT(DISTINCT ts.student_id) AS alumnos
  FROM task_submissions ts
  JOIN tasks t ON t.id=ts.task_id
  JOIN teacher_assignments ta ON ta.id=t.assignment_id
  JOIN levels l ON l.id=ta.level_id
  JOIN grades g ON g.id=ta.grade_id
  WHERE ts.grade IS NOT NULL AND t.school_year=$year
  GROUP BY ta.level_id, ta.grade_id
  ORDER BY l.sort_order, g.sort_order
")->fetchAll();

/* ── 4. Distribución de notas (rangos) ───────────────── */
$dist = $pdo->query("
  SELECT
    SUM(CASE WHEN (ts.grade/$max*$max) BETWEEN 0  AND ".($max*0.55-0.01)." THEN 1 ELSE 0 END) AS muy_bajo,
    SUM(CASE WHEN (ts.grade/$max*$max) BETWEEN ".($max*0.55)." AND ".($max*0.69)." THEN 1 ELSE 0 END) AS bajo,
    SUM(CASE WHEN (ts.grade/$max*$max) BETWEEN ".($max*0.70)." AND ".($max*0.84)." THEN 1 ELSE 0 END) AS medio,
    SUM(CASE WHEN (ts.grade/$max*$max) BETWEEN ".($max*0.85)." AND ".($max*0.94)." THEN 1 ELSE 0 END) AS bueno,
    SUM(CASE WHEN (ts.grade/$max*$max) BETWEEN ".($max*0.95)." AND $max          THEN 1 ELSE 0 END) AS excelente
  FROM task_submissions ts
  JOIN tasks t ON t.id=ts.task_id
  WHERE ts.grade IS NOT NULL AND t.school_year=$year
")->fetch();

/* ── 5. Alumnos destacados (top promedio) ────────────── */
$top_alumnos = $pdo->query("
  SELECT
    u.full_name, u.dni,
    l.name AS lv, g.name AS gr,
    COUNT(ts.id)           AS entregas,
    ROUND(AVG(ts.grade/$max*$max),1) AS promedio,
    SUM(ts.grade IS NOT NULL) AS calificadas
  FROM task_submissions ts
  JOIN tasks t ON t.id=ts.task_id
  JOIN teacher_assignments ta ON ta.id=t.assignment_id
  JOIN users u ON u.id=ts.student_id
  JOIN student_assignments sa
    ON sa.student_id=u.id AND sa.school_year=$year AND sa.is_active=1
  JOIN levels l ON l.id=sa.level_id
  JOIN grades g ON g.id=sa.grade_id
  WHERE ts.grade IS NOT NULL AND t.school_year=$year
  GROUP BY ts.student_id
  HAVING calificadas >= 1
  ORDER BY promedio DESC
  LIMIT 10
")->fetchAll();

/* ── 6. Alumnos en riesgo (promedio bajo) ────────────── */
$risk_alumnos = $pdo->query("
  SELECT
    u.full_name, u.dni,
    l.name AS lv, g.name AS gr,
    ROUND(AVG(ts.grade/$max*$max),1) AS promedio,
    COUNT(ts.id) AS calificadas
  FROM task_submissions ts
  JOIN tasks t ON t.id=ts.task_id
  JOIN teacher_assignments ta ON ta.id=t.assignment_id
  JOIN users u ON u.id=ts.student_id
  JOIN student_assignments sa
    ON sa.student_id=u.id AND sa.school_year=$year AND sa.is_active=1
  JOIN levels l ON l.id=sa.level_id
  JOIN grades g ON g.id=sa.grade_id
  WHERE ts.grade IS NOT NULL AND t.school_year=$year
  GROUP BY ts.student_id
  HAVING promedio < ".($max*0.55)." AND calificadas >= 1
  ORDER BY promedio ASC
  LIMIT 10
")->fetchAll();

/* ── 7. KPIs globales ────────────────────────────────── */
$kpis = $pdo->query("
  SELECT
    (SELECT COUNT(*) FROM users WHERE role='ALUMNO'  AND is_active=1) AS alumnos,
    (SELECT COUNT(*) FROM users WHERE role='DOCENTE' AND is_active=1) AS docentes,
    (SELECT COUNT(*) FROM teacher_assignments WHERE school_year=$year AND is_active=1) AS asignaciones,
    (SELECT COUNT(*) FROM tasks WHERE school_year=$year AND is_active=1) AS tareas,
    (SELECT COUNT(*) FROM task_submissions ts
       JOIN tasks t ON t.id=ts.task_id
       WHERE t.school_year=$year) AS entregas,
    (SELECT COUNT(*) FROM task_submissions ts
       JOIN tasks t ON t.id=ts.task_id
       WHERE t.school_year=$year AND ts.grade IS NOT NULL) AS calificadas,
    (SELECT ROUND(AVG(ts.grade/$max*$max),1)
       FROM task_submissions ts
       JOIN tasks t ON t.id=ts.task_id
       WHERE ts.grade IS NOT NULL AND t.school_year=$year) AS promedio_global,
    (SELECT COUNT(*) FROM tasks WHERE school_year=$year
       AND is_active=1 AND due_date < CURDATE()
       AND (SELECT COUNT(*) FROM task_submissions WHERE task_id=tasks.id)=0
    ) AS tareas_vencidas_vacias
")->fetch();

/* ── 8. Actividad por docente ────────────────────────── */
$by_teacher = $pdo->query("
  SELECT
    u.full_name,
    COUNT(DISTINCT t.id)              AS n_tareas,
    COUNT(DISTINCT ts.id)             AS n_entregas,
    SUM(ts.grade IS NOT NULL)         AS n_calificadas,
    COUNT(DISTINCT s.id)              AS n_sesiones,
    ROUND(AVG(ts.grade/$max*$max),1) AS promedio
  FROM users u
  LEFT JOIN tasks t  ON t.teacher_id=u.id AND t.school_year=$year
  LEFT JOIN task_submissions ts ON ts.task_id=t.id
  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
  WHERE u.role='DOCENTE' AND u.is_active=1
  GROUP BY u.id
  ORDER BY n_tareas DESC
  LIMIT 15
")->fetchAll();

/* ── 9. Años disponibles ─────────────────────────────── */
$years_avail = $pdo->query("
  SELECT DISTINCT school_year FROM tasks
  UNION SELECT DISTINCT school_year FROM teacher_assignments
  ORDER BY school_year DESC
")->fetchAll(PDO::FETCH_COLUMN);
if (!in_array($year, $years_avail)) $years_avail[] = $year;
rsort($years_avail);

layout_start('Reportes y Estadísticas', $u);
?>

<!-- ── 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)">
      📊 Reportes y Estadísticas
    </h2>
    <p class="txt-muted">Análisis académico del año <?= $year ?></p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <!-- Selector de año -->
    <form method="get" style="display:flex;gap:6px;align-items:center">
      <select name="year" onchange="this.form.submit()"
              style="padding:7px 12px;border:1.5px solid var(--border);
                     border-radius:8px;font-size:13px">
        <?php foreach ($years_avail as $yr): ?>
          <option value="<?= (int)$yr ?>"
            <?= (int)$yr===$year?'selected':'' ?>>
            <?= (int)$yr ?>
          </option>
        <?php endforeach; ?>
      </select>
    </form>
    <button class="btn btn-outline btn-sm" onclick="exportAllCSV()">
      📊 Exportar CSV
    </button>
    <button class="btn btn-navy btn-sm" onclick="window.print()">
      🖨️ Imprimir PDF
    </button>
  </div>
</div>

<!-- ══ KPIs GLOBALES ══ -->
<div style="display:grid;
  grid-template-columns:repeat(auto-fill,minmax(140px,1fr));
  gap:12px;margin-bottom:22px" id="kpi-section">

  <?php
  $kpi_items = [
    ['🎓','Alumnos activos',    $kpis['alumnos'],         'var(--navy)'],
    ['👨‍🏫','Docentes activos',   $kpis['docentes'],        'var(--teal)'],
    ['📋','Asignaciones',       $kpis['asignaciones'],    'var(--sky)'],
    ['📝','Tareas creadas',     $kpis['tareas'],          'var(--purple)'],
    ['📬','Total entregas',     $kpis['entregas'],        'var(--orange)'],
    ['✅','Calificadas',        $kpis['calificadas'],     'var(--green)'],
    ['⭐','Promedio global',    $kpis['promedio_global'] ?? '—', '#c62828'],
    ['⚠️','Tareas sin entregar',$kpis['tareas_vencidas_vacias'],'var(--muted)'],
  ];
  foreach ($kpi_items as [$ic,$lb,$val,$color]): ?>
  <div class="kpi-card" style="border-top-color:<?= $color ?>">
    <div class="kpi-ic"><?= $ic ?></div>
    <div class="kpi-val" style="color:<?= $color ?>"><?= $val ?? 0 ?></div>
    <div class="kpi-lbl"><?= $lb ?></div>
  </div>
  <?php endforeach; ?>
</div>

<!-- ══ GRÁFICAS FILA 1 ══ -->
<div class="charts-grid-2" style="margin-bottom:18px">

  <!-- Entregas por mes -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">📅 Entregas por Mes — <?= $year ?></div>
      <button class="btn btn-outline btn-xs" onclick="downloadChart('c-month')">
        ⬇️ PNG
      </button>
    </div>
    <div style="position:relative;height:240px">
      <canvas id="c-month"></canvas>
    </div>
  </div>

  <!-- Distribución de notas -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">🎯 Distribución de Notas</div>
      <button class="btn btn-outline btn-xs" onclick="downloadChart('c-dist')">
        ⬇️ PNG
      </button>
    </div>
    <div style="position:relative;height:240px">
      <canvas id="c-dist"></canvas>
    </div>
  </div>
</div>

<!-- ══ GRÁFICAS FILA 2 ══ -->
<div class="charts-grid-2" style="margin-bottom:18px">

  <!-- Promedio por curso -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">📚 Promedio por Curso</div>
      <button class="btn btn-outline btn-xs" onclick="downloadChart('c-curso')">
        ⬇️ PNG
      </button>
    </div>
    <div style="position:relative;height:260px">
      <canvas id="c-curso"></canvas>
    </div>
  </div>

  <!-- Promedio por grado -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">🏫 Promedio por Grado</div>
      <button class="btn btn-outline btn-xs" onclick="downloadChart('c-grado')">
        ⬇️ PNG
      </button>
    </div>
    <div style="position:relative;height:260px">
      <canvas id="c-grado"></canvas>
    </div>
  </div>
</div>

<!-- ══ GRÁFICA DOCENTES (full width) ══ -->
<div class="chart-card" style="margin-bottom:18px">
  <div class="chart-head">
    <div class="chart-title">👨‍🏫 Actividad de Docentes — Tareas y Sesiones</div>
    <button class="btn btn-outline btn-xs" onclick="downloadChart('c-teacher')">
      ⬇️ PNG
    </button>
  </div>
  <div style="position:relative;height:240px">
    <canvas id="c-teacher"></canvas>
  </div>
</div>

<!-- ══ TABLAS BOTTOM ══ -->
<div class="charts-grid-2" style="margin-bottom:18px">

  <!-- Top 10 alumnos -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">🏆 Top 10 Alumnos</div>
      <button class="btn btn-outline btn-xs"
              onclick="exportTableCSV('t-top','top_alumnos')">
        📊 CSV
      </button>
    </div>
    <div style="overflow-x:auto">
      <table id="t-top" style="font-size:12px">
        <thead>
          <tr>
            <th>#</th><th>Alumno</th><th>Grado</th>
            <th>Entregas</th><th>Promedio</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($top_alumnos as $i => $a):
          $avg_cls = (float)$a['promedio'] >= $max*0.85 ? '' :
                    ((float)$a['promedio'] >= $max*0.7 ? 'warn' : 'fail');
          $medal   = match($i) { 0=>'🥇', 1=>'🥈', 2=>'🥉', default=>$i+1 };
        ?>
        <tr>
          <td style="text-align:center"><?= $medal ?></td>
          <td>
            <div style="font-weight:700;color:var(--navy)">
              <?= htmlspecialchars($a['full_name']) ?>
            </div>
            <div class="txt-muted"><?= htmlspecialchars($a['dni']) ?></div>
          </td>
          <td class="txt-muted">
            <?= htmlspecialchars($a['lv'].' · '.$a['gr']) ?>
          </td>
          <td style="text-align:center"><?= (int)$a['entregas'] ?></td>
          <td style="text-align:center">
            <span class="grade-badge <?= $avg_cls ?>"
                  style="font-size:12px;padding:3px 10px">
              <?= number_format((float)$a['promedio'],1) ?>/<?= $max ?>
            </span>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$top_alumnos): ?>
        <tr><td colspan="5" style="text-align:center;
            padding:20px;color:var(--muted)">Sin datos</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Alumnos en riesgo -->
  <div class="chart-card">
    <div class="chart-head">
      <div class="chart-title">⚠️ Alumnos en Riesgo</div>
      <button class="btn btn-outline btn-xs"
              onclick="exportTableCSV('t-risk','alumnos_riesgo')">
        📊 CSV
      </button>
    </div>
    <div style="overflow-x:auto">
      <table id="t-risk" style="font-size:12px">
        <thead>
          <tr>
            <th>#</th><th>Alumno</th><th>Grado</th>
            <th>Calif.</th><th>Promedio</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($risk_alumnos as $i => $a): ?>
        <tr>
          <td style="text-align:center;color:var(--red);font-weight:800">
            ⚠️
          </td>
          <td>
            <div style="font-weight:700;color:var(--navy)">
              <?= htmlspecialchars($a['full_name']) ?>
            </div>
            <div class="txt-muted"><?= htmlspecialchars($a['dni']) ?></div>
          </td>
          <td class="txt-muted">
            <?= htmlspecialchars($a['lv'].' · '.$a['gr']) ?>
          </td>
          <td style="text-align:center"><?= (int)$a['calificadas'] ?></td>
          <td style="text-align:center">
            <span class="grade-badge fail"
                  style="font-size:12px;padding:3px 10px">
              <?= number_format((float)$a['promedio'],1) ?>/<?= $max ?>
            </span>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$risk_alumnos): ?>
        <tr><td colspan="5" style="text-align:center;
            padding:20px;color:var(--green)">
          ✅ Sin alumnos en riesgo
        </td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ══ TABLA ACTIVIDAD DOCENTES ══ -->
<div class="chart-card" style="margin-bottom:20px">
  <div class="chart-head">
    <div class="chart-title">👨‍🏫 Resumen de Actividad por Docente</div>
    <button class="btn btn-outline btn-xs"
            onclick="exportTableCSV('t-teach','docentes_actividad')">
      📊 CSV
    </button>
  </div>
  <div class="table-wrap">
    <table id="t-teach">
      <thead>
        <tr>
          <th>Docente</th><th>Tareas</th><th>Entregas</th>
          <th>Calificadas</th><th>Sesiones</th><th>Promedio</th>
          <th>% Calificado</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($by_teacher as $t):
        $pct_cal = $t['n_entregas'] > 0
          ? round($t['n_calificadas'] / $t['n_entregas'] * 100) : 0;
        $avg     = $t['promedio'] !== null ? (float)$t['promedio'] : null;
        $avg_cls = $avg===null?'':($avg<$max*0.55?'fail':($avg<$max*0.7?'warn':''));
      ?>
      <tr>
        <td>
          <div style="display:flex;align-items:center;gap:8px">
            <div style="width:28px;height:28px;border-radius:50%;
                 background:var(--navy);display:flex;align-items:center;
                 justify-content:center;font-size:11px;
                 font-weight:800;color:#fff;flex-shrink:0">
              <?= mb_strtoupper(mb_substr($t['full_name'],0,1)) ?>
            </div>
            <span style="font-weight:700;font-size:13px;color:var(--navy)">
              <?= htmlspecialchars($t['full_name']) ?>
            </span>
          </div>
        </td>
        <td style="text-align:center;font-weight:700">
          <?= (int)$t['n_tareas'] ?>
        </td>
        <td style="text-align:center"><?= (int)$t['n_entregas'] ?></td>
        <td style="text-align:center;color:var(--green);font-weight:700">
          <?= (int)$t['n_calificadas'] ?>
        </td>
        <td style="text-align:center"><?= (int)$t['n_sesiones'] ?></td>
        <td style="text-align:center">
          <?php if ($avg !== null): ?>
            <span class="grade-badge <?= $avg_cls ?>"
                  style="font-size:11px;padding:3px 9px">
              <?= number_format($avg,1) ?>/<?= $max ?>
            </span>
          <?php else: ?>
            <span class="txt-muted">—</span>
          <?php endif; ?>
        </td>
        <td>
          <div style="display:flex;align-items:center;gap:6px">
            <div style="flex:1;background:#e0e0e0;border-radius:20px;
                 height:6px;overflow:hidden;min-width:60px">
              <div style="width:<?= $pct_cal ?>%;height:100%;
                   background:<?= $pct_cal>=70?'var(--green)':($pct_cal>=40?'var(--orange)':'var(--red)') ?>;
                   border-radius:20px;transition:width .5s"></div>
            </div>
            <span style="font-size:11px;font-weight:700;
                  color:<?= $pct_cal>=70?'var(--green)':($pct_cal>=40?'var(--orange)':'var(--red)') ?>">
              <?= $pct_cal ?>%
            </span>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- ══ RESUMEN DISTRIBUCIÓN ══ -->
<div class="chart-card" style="margin-bottom:20px">
  <div class="chart-head">
    <div class="chart-title">📊 Distribución de Notas — Detalle</div>
  </div>
  <?php
  $total_dist = array_sum(array_filter((array)$dist));
  $dist_items = [
    ['Excelente', (int)$dist['excelente'], 'var(--green)',   '95–100%'],
    ['Bueno',     (int)$dist['bueno'],     'var(--teal)',    '85–94%'],
    ['Medio',     (int)$dist['medio'],     'var(--sky)',     '70–84%'],
    ['Bajo',      (int)$dist['bajo'],      'var(--orange)',  '55–69%'],
    ['Muy bajo',  (int)$dist['muy_bajo'],  'var(--red)',     '0–54%'],
  ];
  ?>
  <div style="display:flex;flex-direction:column;gap:10px">
    <?php foreach ($dist_items as [$lbl,$cnt,$color,$range]):
      $pct = $total_dist > 0 ? round($cnt/$total_dist*100,1) : 0;
    ?>
    <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
      <div style="width:90px;font-size:12px;font-weight:700;color:var(--navy)">
        <?= $lbl ?>
        <span class="txt-muted" style="font-size:10px"><?= $range ?></span>
      </div>
      <div style="flex:1;background:#e0e0e0;border-radius:20px;
           height:14px;overflow:hidden;min-width:100px">
        <div style="width:<?= $pct ?>%;height:100%;
             background:<?= $color ?>;border-radius:20px;
             display:flex;align-items:center;justify-content:center;
             transition:width .6s ease">
        </div>
      </div>
      <div style="min-width:80px;font-size:12px;color:var(--muted)">
        <span style="font-weight:800;color:<?= $color ?>"><?= $cnt ?></span>
        alumnos (<?= $pct ?>%)
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- ══ PRINT STYLES ══ -->
<style>
@media print {
  .topbar, .sidebar, .btn, form, select,
  [onclick], .modal-ov { display:none !important; }
  .main-content { padding: 0 !important; }
  body { background:#fff !important; }
  .chart-card { break-inside: avoid; page-break-inside: avoid; }
  canvas { max-width: 100% !important; }
}

.kpi-card{
  background:var(--card);border-radius:var(--r);
  box-shadow:var(--sh);padding:14px;
  border-top:4px solid var(--muted);
  text-align:center
}
.kpi-ic  { font-size:22px;margin-bottom:4px }
.kpi-val { font-size:24px;font-weight:800;line-height:1 }
.kpi-lbl { font-size:11px;color:var(--muted);margin-top:4px;font-weight:600 }

.charts-grid-2 {
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:16px
}
@media(max-width:768px){
  .charts-grid-2{ grid-template-columns:1fr }
}

.chart-card{
  background:var(--card);border-radius:var(--r);
  box-shadow:var(--sh);padding:16px 18px
}
.chart-head{
  display:flex;align-items:center;justify-content:space-between;
  margin-bottom:14px;flex-wrap:wrap;gap:8px
}
.chart-title{
  font-size:14px;font-weight:800;color:var(--navy)
}
</style>

<!-- ══ Chart.js ══ -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
/* ── Datos PHP → JS ── */
var YEAR = <?= $year ?>;
var MAX  = <?= $max ?>;

var mesesLbl = ['Ene','Feb','Mar','Abr','May','Jun',
                'Jul','Ago','Sep','Oct','Nov','Dic'];

var entregasData    = <?= json_encode(array_values($entregas_data)) ?>;
var calificadasData = <?= json_encode(array_values($calificadas_data)) ?>;

var cursoLabels  = <?= json_encode(array_column($by_course,'label')) ?>;
var cursoPromed  = <?= json_encode(array_column($by_course,'promedio')) ?>;

var gradoLabels  = <?= json_encode(array_column($by_grade,'label')) ?>;
var gradoPromed  = <?= json_encode(array_column($by_grade,'promedio')) ?>;

var distLabels   = ['Muy bajo (0–54%)','Bajo (55–69%)','Medio (70–84%)',
                    'Bueno (85–94%)','Excelente (95–100%)'];
var distData     = [
  <?= (int)$dist['muy_bajo'] ?>,
  <?= (int)$dist['bajo'] ?>,
  <?= (int)$dist['medio'] ?>,
  <?= (int)$dist['bueno'] ?>,
  <?= (int)$dist['excelente'] ?>
];
var distColors   = ['#c62828','#e65100','#1565c0','#00695c','#2e7d32'];

var teacherLabels  = <?= json_encode(array_column($by_teacher,'full_name')) ?>;
var teacherTareas  = <?= json_encode(array_column($by_teacher,'n_tareas')) ?>;
var teacherSes     = <?= json_encode(array_column($by_teacher,'n_sesiones')) ?>;
var teacherCal     = <?= json_encode(array_column($by_teacher,'n_calificadas')) ?>;

/* ── Chart defaults ── */
Chart.defaults.font.family = "'Segoe UI', system-ui, sans-serif";
Chart.defaults.font.size   = 12;
Chart.defaults.color       = '#607d8b';
Chart.defaults.plugins.legend.labels.usePointStyle = true;
Chart.defaults.plugins.legend.labels.padding = 16;
Chart.defaults.plugins.tooltip.backgroundColor = '#1a1a2e';
Chart.defaults.plugins.tooltip.cornerRadius    = 8;
Chart.defaults.plugins.tooltip.padding         = 10;

var charts = {};

/* ── 1. Entregas por mes ── */
charts['c-month'] = new Chart(
  document.getElementById('c-month').getContext('2d'), {
  type: 'bar',
  data: {
    labels: mesesLbl,
    datasets: [
      {
        label: 'Entregas',
        data: entregasData,
        backgroundColor: 'rgba(13,27,110,.75)',
        borderRadius: 6,
        borderSkipped: false,
      },
      {
        label: 'Calificadas',
        data: calificadasData,
        backgroundColor: 'rgba(46,125,50,.75)',
        borderRadius: 6,
        borderSkipped: false,
      }
    ]
  },
  options: {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { position:'top' } },
    scales: {
      y: {
        beginAtZero: true,
        ticks: { stepSize: 1 },
        grid: { color: '#f0f0f0' }
      },
      x: { grid: { display: false } }
    }
  }
});

/* ── 2. Distribución de notas (donut) ── */
charts['c-dist'] = new Chart(
  document.getElementById('c-dist').getContext('2d'), {
  type: 'doughnut',
  data: {
    labels: distLabels,
    datasets: [{
      data: distData,
      backgroundColor: distColors,
      hoverOffset: 10,
      borderWidth: 2,
      borderColor: '#fff'
    }]
  },
  options: {
    responsive: true, maintainAspectRatio: false,
    cutout: '60%',
    plugins: {
      legend: {
        position: 'right',
        labels: { font: { size: 11 } }
      },
      tooltip: {
        callbacks: {
          label: function(ctx) {
            var total = ctx.dataset.data.reduce((a,b)=>a+b,0);
            var pct   = total > 0 ? Math.round(ctx.parsed/total*100) : 0;
            return ' '+ctx.label+': '+ctx.parsed+' ('+pct+'%)';
          }
        }
      }
    }
  }
});

/* ── 3. Promedio por curso (horizontal bar) ── */
var barColors = cursoPromed.map(function(v){
  var p = v/MAX;
  return p>=0.85?'rgba(46,125,50,.8)':p>=0.7?'rgba(0,105,92,.8)':
         p>=0.55?'rgba(21,101,192,.8)':'rgba(198,40,40,.8)';
});
charts['c-curso'] = new Chart(
  document.getElementById('c-curso').getContext('2d'), {
  type: 'bar',
  data: {
    labels: cursoLabels,
    datasets: [{
      label: 'Promedio',
      data: cursoPromed,
      backgroundColor: barColors,
      borderRadius: 5,
      borderSkipped: false,
    }]
  },
  options: {
    indexAxis: 'y',
    responsive: true, maintainAspectRatio: false,
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          label: ctx => ' Promedio: '+ctx.parsed.x+' / '+MAX
        }
      }
    },
    scales: {
      x: {
        beginAtZero: true,
        max: MAX,
        grid: { color: '#f0f0f0' },
        ticks: {
          callback: v => v+'/'+MAX
        }
      },
      y: {
        grid: { display: false },
        ticks: { font: { size: 11 } }
      }
    }
  }
});

/* ── 4. Promedio por grado (radar) ── */
charts['c-grado'] = new Chart(
  document.getElementById('c-grado').getContext('2d'), {
  type: 'radar',
  data: {
    labels: gradoLabels,
    datasets: [{
      label: 'Promedio '+YEAR,
      data: gradoPromed,
      backgroundColor: 'rgba(13,27,110,.15)',
      borderColor: '#0d1b6e',
      borderWidth: 2,
      pointBackgroundColor: '#0d1b6e',
      pointRadius: 4,
      pointHoverRadius: 6,
    }]
  },
  options: {
    responsive: true, maintainAspectRatio: false,
    scales: {
      r: {
        beginAtZero: true,
        max: MAX,
        ticks: { stepSize: MAX/4, font: { size:10 } },
        pointLabels: { font: { size:11 } },
        grid: { color:'rgba(0,0,0,.07)' },
        angleLines: { color:'rgba(0,0,0,.07)' }
      }
    },
    plugins: { legend: { position:'top' } }
  }
});

/* ── 5. Actividad docentes (grouped bar) ── */
charts['c-teacher'] = new Chart(
  document.getElementById('c-teacher').getContext('2d'), {
  type: 'bar',
  data: {
    labels: teacherLabels,
    datasets: [
      {
        label: 'Tareas',
        data: teacherTareas,
        backgroundColor: 'rgba(13,27,110,.75)',
        borderRadius: 5,
      },
      {
        label: 'Sesiones',
        data: teacherSes,
        backgroundColor: 'rgba(0,121,107,.75)',
        borderRadius: 5,
      },
      {
        label: 'Calificadas',
        data: teacherCal,
        backgroundColor: 'rgba(46,125,50,.75)',
        borderRadius: 5,
      }
    ]
  },
  options: {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { position:'top' } },
    scales: {
      y: {
        beginAtZero: true,
        ticks: { stepSize: 1 },
        grid: { color:'#f0f0f0' }
      },
      x: {
        grid: { display:false },
        ticks: {
          font: { size:11 },
          maxRotation: 30
        }
      }
    }
  }
});

/* ── Descargar gráfica como PNG ── */
function downloadChart(id) {
  var canvas = document.getElementById(id);
  var link   = document.createElement('a');
  link.download = id+'_'+YEAR+'.png';
  link.href      = canvas.toDataURL('image/png', 1.0);
  link.click();
}

/* ── Exportar tabla a CSV ── */
function exportTableCSV(tableId, filename) {
  var rows = [];
  var table= document.getElementById(tableId);
  if (!table) return;
  table.querySelectorAll('tr').forEach(function(tr){
    var cells=[];
    tr.querySelectorAll('th,td').forEach(function(td){
      cells.push('"'+td.innerText.replace(/\n/g,' ').replace(/"/g,'""').trim()+'"');
    });
    rows.push(cells.join(','));
  });
  var csv = rows.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 = filename+'_'+YEAR+'.csv';
  a.click();
}

/* ── Exportar TODO a CSV (KPIs + resúmenes) ── */
function exportAllCSV() {
  var all = '';

  /* KPIs */
  all += 'REPORTE ACADÉMICO '+YEAR+'\n\n';
  all += 'INDICADORES GLOBALES\n';
  document.querySelectorAll('.kpi-card').forEach(function(k){
    var val=k.querySelector('.kpi-val')?.textContent.trim()||'';
    var lbl=k.querySelector('.kpi-lbl')?.textContent.trim()||'';
    all += '"'+lbl+'","'+val+'"\n';
  });

  /* Tablas */
  ['t-top','t-risk','t-teach'].forEach(function(id){
    var t=document.getElementById(id);
    if (!t) return;
    all += '\n'+id.replace('t-','')+'\n';
    t.querySelectorAll('tr').forEach(function(tr){
      var cells=[];
      tr.querySelectorAll('th,td').forEach(function(td){
        cells.push('"'+td.innerText.replace(/\n/g,' ').replace(/"/g,'""').trim()+'"');
      });
      all += cells.join(',')+'\n';
    });
  });

  var b=new Blob(['\uFEFF'+all],{type:'text/csv;charset=utf-8;'});
  var a=document.createElement('a');
  a.href=URL.createObjectURL(b);
  a.download='reporte_completo_'+YEAR+'.csv';
  a.click();
}
</script>
<?php layout_end(); ?>