<?php
/**
 * Parent Portal — a child's Progress Analytics (read-only, published terms only).
 *
 * Ownership and the published-only rule are enforced by the data endpoint
 * (ajax/get_child_progress.php); this page also verifies ownership before it
 * renders anything, so a tampered ?child_id never reaches the DOM.
 */
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }

$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }

$parentId = (int) $_SESSION['parent_id'];
$children = portalGetChildren($conn, $parentId);
$childId  = (int) ($_GET['child_id'] ?? ($children[0]['id'] ?? 0));
if ($childId > 0 && !portalParentOwnsStudent($conn, $parentId, $childId)) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}
$student   = $childId > 0 ? portalGetStudent($conn, $childId, $parentId) : null;
$available = function_exists('hasModule') && hasModule('progress_analytics');

echo portalPageStart('Progress', 'reports', 'Progress');
?>
<?= portalChildSwitcher($children, $childId, 'progress.php') ?>

<?php if (!$student): ?>
    <div class="portal-card text-center"><p class="portal-muted mb-0">Select a child to view progress.</p></div>
<?php elseif (!$available): ?>
    <div class="portal-card text-center">
        <i class="fas fa-lock text-muted mb-2" style="font-size:1.6rem"></i>
        <p class="portal-muted mb-0">Progress Analytics is not enabled for your school.</p>
    </div>
<?php else: ?>

<div class="portal-card">
    <div class="portal-child-card">
        <img src="<?= htmlspecialchars(portalStudentPhoto($student)) ?>" alt="Child photo" class="portal-avatar">
        <div>
            <div class="h6 mb-1"><?= htmlspecialchars(portalStudentDisplayName($student)) ?></div>
            <div class="portal-muted" style="font-size:.8rem"><?= htmlspecialchars((string)($student['class'] ?? '')) ?></div>
        </div>
    </div>
    <div style="margin-top:10px">
        <label class="portal-muted" style="font-size:.75rem;display:block;margin-bottom:4px">Term</label>
        <select id="ppTerm" class="form-select form-select-sm" onchange="ppLoad()"></select>
    </div>
</div>

<div id="ppStatus" class="portal-card text-center" style="display:none">
    <p class="portal-muted mb-0" id="ppStatusMsg">Loading…</p>
</div>

<div id="ppBody" style="display:none">
    <div class="portal-grid cols-3" id="ppKpis" style="gap:10px;margin-bottom:12px"></div>

    <div class="portal-card">
        <div class="portal-section-title" style="margin-bottom:8px"><i class="fas fa-chart-line me-1"></i><span id="ppTrendTitle">Progress over time</span></div>
        <div style="position:relative;height:230px"><canvas id="ppTrend"></canvas></div>
    </div>

    <div class="portal-card">
        <div class="portal-section-title" style="margin-bottom:8px"><i class="fas fa-chart-simple me-1"></i>Subjects vs class average</div>
        <div style="position:relative;height:260px"><canvas id="ppSubjects"></canvas></div>
    </div>

    <div class="portal-card">
        <div class="portal-section-title" style="margin-bottom:8px"><i class="fas fa-table me-1"></i>Subject scores</div>
        <div style="overflow-x:auto"><table class="table table-sm mb-0" id="ppTable"></table></div>
    </div>
</div>

<style>
.pp-kpi{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:12px 8px;text-align:center}
.pp-kpi .v{font-size:1.25rem;font-weight:700;color:#14532d;line-height:1.1;font-variant-numeric:tabular-nums}
.pp-kpi .l{font-size:.62rem;text-transform:uppercase;letter-spacing:.03em;color:#94a3b8;margin-top:3px}
#ppTable th{font-size:.72rem;color:#64748b;font-weight:600;white-space:nowrap}
#ppTable td{font-size:.82rem;color:#1e293b;font-variant-numeric:tabular-nums}
.pp-grade{display:inline-block;min-width:22px;text-align:center;color:#fff;font-weight:700;border-radius:5px;padding:1px 6px;font-size:.78rem}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script>
(function () {
  'use strict';
  var CHILD = <?= (int) $childId ?>;
  var C = { s1:'#16a34a', s1soft:'rgba(22,163,74,.14)', s2:'#f59e0b', grid:'#e5e7eb', muted:'#94a3b8', ink:'#14532d' };
  var GRADE = { A:'#0ca30c', B:'#1baf7a', C:'#eda100', D:'#eb6834', E:'#e34948', W:'#b23b3b' };
  var charts = {};
  function $(id){ return document.getElementById(id); }
  function esc(s){ return String(s==null?'':s).replace(/[&<>"']/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];}); }
  function num(v,d){ return v==null?'—':(+v).toFixed(d==null?1:d); }

  window.ppLoad = function () {
    status('Loading…');
    var term = $('ppTerm').value;
    fetch('ajax/get_child_progress.php?child_id=' + CHILD + '&term=' + encodeURIComponent(term), { credentials:'same-origin' })
      .then(function(r){ return r.json(); })
      .then(render).catch(function(){ status('Could not load progress.'); });
  };

  function status(msg){ $('ppStatus').style.display='block'; $('ppStatusMsg').textContent=msg; $('ppBody').style.display='none'; }
  function showBody(){ $('ppStatus').style.display='none'; $('ppBody').style.display='block'; }

  function fillTerms(periods, selected){
    var sel = $('ppTerm');
    if (sel.options.length) return; // populate once
    sel.innerHTML = periods.map(function(p){
      var v = p.term, lbl = p.term + ' · ' + p.academic_year;
      var isSel = selected && p.term===selected.term && p.academic_year===selected.academic_year;
      return '<option value="'+esc(v)+'"'+(isSel?' selected':'')+'>'+esc(lbl)+'</option>';
    }).join('');
  }

  function render(res){
    if (!res || !res.success){ status(res && res.message || 'Could not load.'); return; }
    if (res.locked){ status('Progress Analytics is not enabled.'); return; }
    if (!res.published){ status('No published reports yet. Progress appears once a report is released.'); return; }
    fillTerms(res.periods, res.selected);
    showBody();

    var k = res.kpis;
    var tiles = [
      ['Average', num(k.avg_score,1)],
      ['Attendance', res.attendance_rate==null?'—':num(res.attendance_rate,0)+'%'],
      ['Best', num(k.top_score,1)]
    ];
    $('ppKpis').innerHTML = tiles.map(function(t){
      return '<div class="pp-kpi"><div class="v">'+esc(t[1])+'</div><div class="l">'+esc(t[0])+'</div></div>';
    }).join('');

    $('ppTrendTitle').textContent = 'Progress over time';
    trend(res.trend);
    subjects(res.subjects);
    table(res.table);
  }

  function make(id, cfg){ if (charts[id]) charts[id].destroy(); charts[id] = new Chart($(id).getContext('2d'), cfg); }
  var AXES = { x:{grid:{display:false},ticks:{color:C.muted,font:{size:10}}},
               y:{beginAtZero:true,suggestedMax:100,grid:{color:C.grid},ticks:{color:C.muted,font:{size:10}}} };

  function trend(tr){
    var ds = (tr.series||[]).map(function(s,i){ return {
      label:s.name, data:s.data, borderColor:i?C.s2:C.s1, backgroundColor:i?'rgba(245,158,11,.12)':C.s1soft,
      borderWidth:2, tension:.3, fill:(i===0 && tr.series.length===1), pointRadius:3, pointHoverRadius:5, spanGaps:true }; });
    make('ppTrend', { type:'line', data:{labels:tr.labels,datasets:ds},
      options:{responsive:true,maintainAspectRatio:false,
        plugins:{legend:{display:(tr.series||[]).length>1,labels:{color:C.ink,boxWidth:10,font:{size:10}}}}, scales:AXES } });
  }

  function subjects(subs){
    var labels = subs.map(function(s){ return s.subject; });
    var ds = [{ label:'Your child', data:subs.map(function(s){return s.avg_score;}), backgroundColor:C.s1, borderRadius:4 }];
    if (subs.some(function(s){ return s.class_avg!=null; }))
      ds.push({ label:'Class average', data:subs.map(function(s){return s.class_avg;}), backgroundColor:C.s2, borderRadius:4 });
    make('ppSubjects', { type:'bar', data:{labels:labels,datasets:ds},
      options:{responsive:true,maintainAspectRatio:false,
        plugins:{legend:{display:ds.length>1,labels:{color:C.ink,boxWidth:10,font:{size:10}}}},
        scales:{x:{grid:{display:false},ticks:{color:C.muted,font:{size:9},maxRotation:60,minRotation:30}},
                y:{beginAtZero:true,suggestedMax:100,grid:{color:C.grid},ticks:{color:C.muted,font:{size:10}}}} } });
  }

  function table(tbl){
    if (!tbl || !tbl.rows.length){ $('ppTable').innerHTML = '<tbody><tr><td class="portal-muted">No scores.</td></tr></tbody>'; return; }
    var numKeys = {class_score:1,exam_score:1,total_score:1};
    var head = '<thead><tr>' + tbl.columns.map(function(c){ return '<th>'+esc(c.label)+'</th>'; }).join('') + '</tr></thead>';
    var body = '<tbody>' + tbl.rows.map(function(r){
      return '<tr>' + tbl.columns.map(function(c){
        var v = r[c.key];
        if (c.key==='grade' && v) return '<td><span class="pp-grade" style="background:'+(GRADE[v]||'#666')+'">'+esc(v)+'</span></td>';
        if (c.key in numKeys) v = num(v,1); else v = esc(v==null?'—':v);
        return '<td>'+v+'</td>';
      }).join('') + '</tr>';
    }).join('') + '</tbody>';
    $('ppTable').innerHTML = head + body;
  }

  ppLoad();
})();
</script>

<?php endif; ?>
<?= portalPageEnd('reports') ?>
