<?php
require_once __DIR__ . '/../../admin/_nav.php';
$pageTitle  = 'Learner Profile';
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };

$termLabels = [];
$termAvgs   = [];
foreach ($termTrend as $t) {
    $termLabels[] = $t['year'].' '.$t['term'];
    $termAvgs[]   = round((float)$t['avg_score'], 1);
}

$subjectNames  = [];
$subjectAvgs   = [];
$subjectColors = [];
foreach ($subjectBreakdown as $s) {
    $subjectNames[] = $s['subject'];
    $avg = round((float)$s['avg_score'], 1);
    $subjectAvgs[] = $avg;
    if ($avg >= 75)     $subjectColors[] = 'rgba(6,95,70,.75)';
    elseif ($avg >= 50) $subjectColors[] = 'rgba(30,64,175,.75)';
    elseif ($avg >= 25) $subjectColors[] = 'rgba(146,64,14,.75)';
    else                $subjectColors[] = 'rgba(153,27,27,.75)';
}

$attTotal = $attendance['total'] ?? 0;
$attRate  = $attTotal > 0 ? round(($attendance['present'] / $attTotal) * 100, 1) : 0;
?>
<div class="page-header">
  <div style="display:flex;align-items:center;gap:16px">
    <div class="avatar" style="width:52px;height:52px;font-size:20px"><?= strtoupper(substr($student['name'],0,1)) ?></div>
    <div>
      <h1><?= htmlspecialchars($student['name']) ?></h1>
      <p><?= htmlspecialchars(($student['class_name']??'').' '.($student['stream_name']??'')) ?> &bull; <?= htmlspecialchars($student['assessment_no']) ?></p>
    </div>
  </div>
  <a href="<?= $u('admin/analytics') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Back</a>
</div>

<!-- Insights -->
<div style="margin-bottom:20px">
  <?php foreach($insights as $ins): ?>
  <div class="alert alert-<?= $ins['type'] ?>" style="margin-bottom:8px">
    <i class="bi bi-<?= $ins['type']==='success'?'lightbulb':($ins['type']==='danger'?'exclamation-triangle':'exclamation-circle') ?>"></i>
    <?= htmlspecialchars($ins['msg']) ?>
  </div>
  <?php endforeach; ?>
</div>

<!-- KPI Row -->
<div class="grid g4" style="margin-bottom:24px">
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-graph-up"></i></div>
    <div class="stat-info">
      <h3><?= !empty($termTrend) ? round((float)end($termTrend)['avg_score'],1).'%' : 'N/A' ?></h3>
      <p>Latest Term Avg</p>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-blue"><i class="bi bi-calendar-check"></i></div>
    <div class="stat-info"><h3><?= $attRate ?>%</h3><p>Attendance Rate</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-amber"><i class="bi bi-book"></i></div>
    <div class="stat-info"><h3><?= count($subjectBreakdown) ?></h3><p>Subjects Assessed</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon <?= $attRate<75?'si-red':'si-green' ?>"><i class="bi bi-person-x"></i></div>
    <div class="stat-info"><h3><?= $attendance['absent'] ?? 0 ?></h3><p>Days Absent</p></div>
  </div>
</div>

<div class="grid g2" style="margin-bottom:24px">
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-graph-up"></i> Performance Trend</h5></div>
    <div class="card-body">
      <?php if(empty($termTrend)): ?>
      <div style="text-align:center;padding:40px;color:var(--gray)">No marks data yet</div>
      <?php else: ?>
      <canvas id="trendChart" height="200"></canvas>
      <?php endif; ?>
    </div>
  </div>
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-bar-chart-horizontal"></i> Subject Breakdown</h5></div>
    <div class="card-body">
      <?php if(empty($subjectBreakdown)): ?>
      <div style="text-align:center;padding:40px;color:var(--gray)">No subject data yet</div>
      <?php else: ?>
      <canvas id="subjectChart" height="200"></canvas>
      <?php endif; ?>
    </div>
  </div>
</div>

<div class="grid g2">
  <!-- Subject Detail -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-table"></i> Subject Performance Detail</h5></div>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Subject</th><th>Avg</th><th>Best</th><th>Lowest</th><th>Level</th></tr></thead>
        <tbody>
          <?php foreach($subjectBreakdown as $s):
            $avg = (float)$s['avg_score'];
            $lvl = $avg>=75?'EE':($avg>=50?'ME':($avg>=25?'AE':'BE'));
            $cls = ['EE'=>'badge-success','ME'=>'badge-info','AE'=>'badge-warning','BE'=>'badge-danger'][$lvl]; ?>
          <tr>
            <td><?= htmlspecialchars($s['subject']) ?></td>
            <td><strong><?= round($avg,1) ?>%</strong></td>
            <td style="color:var(--success)"><?= $s['best'] ?>%</td>
            <td style="color:var(--danger)"><?= $s['lowest'] ?>%</td>
            <td><span class="badge <?= $cls ?>"><?= $lvl ?></span></td>
          </tr>
          <?php endforeach; ?>
          <?php if(empty($subjectBreakdown)): ?>
          <tr><td colspan="5" style="text-align:center;padding:20px;color:var(--gray)">No data</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Competency Ratings -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-stars"></i> Key Competency Ratings</h5></div>
    <div class="card-body" style="padding:0">
      <?php if(empty($competencies)): ?>
      <div style="padding:20px;text-align:center;color:var(--gray)">No competency ratings recorded yet</div>
      <?php else:
        $byComp = [];
        foreach($competencies as $c) $byComp[$c['name']][] = $c;
        foreach($byComp as $name => $entries): ?>
      <div style="padding:12px 20px;border-bottom:1px solid var(--border)">
        <div style="font-weight:500;font-size:13px;margin-bottom:6px"><?= htmlspecialchars($name) ?></div>
        <div style="display:flex;gap:6px;flex-wrap:wrap">
          <?php foreach($entries as $e):
            $cls = ['EE'=>'badge-success','ME'=>'badge-info','AE'=>'badge-warning','BE'=>'badge-danger'][$e['rating']] ?? 'badge-gray'; ?>
          <span class="badge <?= $cls ?>"><?= $e['rating'] ?> <span style="font-weight:400;opacity:.8"><?= htmlspecialchars($e['term_name']) ?></span></span>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endforeach; endif; ?>
    </div>
  </div>
</div>

<?php
$trendLJson = json_encode($termLabels);
$trendAJson = json_encode($termAvgs);
$subNJson   = json_encode($subjectNames);
$subAJson   = json_encode($subjectAvgs);
$subCJson   = json_encode($subjectColors);

$extraScripts = '
<script src="/cbe/sms/public/assets/chart.min.js"></script>
<script>
Chart.defaults.font.family="Inter,sans-serif";
Chart.defaults.font.size=12;

'.(!empty($termTrend) ? '
new Chart("trendChart",{type:"line",data:{labels:'.$trendLJson.',datasets:[{label:"Avg Score",data:'.$trendAJson.',borderColor:"#1a7f5a",backgroundColor:"rgba(26,127,90,.1)",tension:.4,fill:true,pointRadius:5,pointBackgroundColor:"#1a7f5a"}]},options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,max:100,ticks:{callback:function(v){return v+"%";}}},x:{grid:{display:false}}}}});
' : '').'

'.(!empty($subjectBreakdown) ? '
new Chart("subjectChart",{type:"bar",data:{labels:'.$subNJson.',datasets:[{label:"Avg Score",data:'.$subAJson.',backgroundColor:'.$subCJson.',borderRadius:4}]},options:{indexAxis:"y",responsive:true,plugins:{legend:{display:false}},scales:{x:{beginAtZero:true,max:100,ticks:{callback:function(v){return v+"%";}}},y:{grid:{display:false}}}}});
' : '').'
</script>';
?>
