<?php
require_once __DIR__ . '/_nav.php';
$pageTitle  = 'Teacher Dashboard';
$sidebarNav = teacherNav();
$u = function($p) { return \Core\View::url($p); };

$hour  = (int)date('H');
$greet = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$totalGrades = array_sum($gradeDist);
$subNames = array_column($subjectPerf, 'name');
$subAvgs  = array_column($subjectPerf, 'avg_score');
$subColors = [];
foreach ($subAvgs as $v) {
    if ($v >= 75)     $subColors[] = 'rgba(6,95,70,.75)';
    elseif ($v >= 50) $subColors[] = 'rgba(30,64,175,.75)';
    elseif ($v >= 25) $subColors[] = 'rgba(146,64,14,.75)';
    else              $subColors[] = 'rgba(153,27,27,.75)';
}
$gInfo = ['EE'=>['#065f46','si-green','award','Exceeding'],'ME'=>['#1e40af','si-blue','check2-circle','Meeting'],'AE'=>['#92400e','si-amber','exclamation-circle','Approaching'],'BE'=>['#991b1b','si-red','x-circle','Below']];
?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:22px;font-weight:700"><?= $greet ?>, <?= htmlspecialchars(explode(' ', \Core\Session::get('user')['name'] ?? '')[0]) ?> 👋</h1>
    <p style="color:var(--gray);font-size:13px;margin-top:2px"><i class="bi bi-calendar3"></i> <?= date('l, d F Y') ?></p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('teacher/attendance') ?>" class="btn btn-primary"><i class="bi bi-calendar-check"></i> Take Attendance</a>
    <a href="<?= $u('teacher/marks') ?>" class="btn btn-secondary"><i class="bi bi-pencil-square"></i> Enter Marks</a>
    <a href="<?= $u('teacher/my-learners') ?>" class="btn btn-secondary"><i class="bi bi-people"></i> My Learners</a>
  </div>
</div>

<!-- KPI Row 1 -->
<div class="grid g4" style="margin-bottom:16px">
  <div class="stat-card" style="">
    <div class="stat-icon si-green"><i class="bi bi-people-fill"></i></div>
    <div class="stat-info"><h3><?= $totalLearners ?></h3><p>My Learners</p></div>
    <div style="margin-left:auto;text-align:right"><span class="badge badge-success"><?= count($myStreams) ?> stream<?= count($myStreams)!=1?'s':'' ?></span></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-green"><i class="bi bi-person-check"></i></div>
    <div class="stat-info"><h3><?= $presentToday ?></h3><p>Present Today</p></div>
    <div style="margin-left:auto;text-align:right">
      <div style="font-size:18px;font-weight:700;color:var(--danger)"><?= $absentToday ?></div>
      <div style="font-size:11px;color:var(--gray)">absent</div>
    </div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-blue"><i class="bi bi-book"></i></div>
    <div class="stat-info"><h3><?= count($streams) ?></h3><p>Subject Streams</p></div>
    <div style="margin-left:auto"><span class="badge badge-info"><?= htmlspecialchars($teacher['employment_type'] ?? 'permanent') ?></span></div>
  </div>
  <div class="stat-card" style="">
    <div class="stat-icon si-amber"><i class="bi bi-file-earmark-text"></i></div>
    <div class="stat-info"><h3><?= count($assignments) ?></h3><p>Assignments</p></div>
    <div style="margin-left:auto"><a href="<?= $u('teacher/assignments') ?>" class="btn btn-sm btn-secondary">View</a></div>
  </div>
</div>


<div class="grid g2" style="margin-bottom:20px">

  <!-- Subject Performance -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-bar-chart-horizontal"></i> Subject Performance (Avg Score)</h5>
      <a href="<?= $u('teacher/marks') ?>" class="btn btn-sm btn-secondary">Enter Marks</a>
    </div>
    <div class="card-body">
      <?php if(empty($subjectPerf)): ?>
      <div style="text-align:center;padding:30px;color:var(--gray)"><i class="bi bi-bar-chart" style="font-size:32px;display:block;margin-bottom:8px"></i>No marks data yet this term</div>
      <?php else: ?>
      <canvas id="subjectChart" height="220"></canvas>
      <?php endif; ?>
    </div>
  </div>

  <!-- Grade Distribution Doughnut -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-pie-chart"></i> Grade Distribution This Term</h5></div>
    <div class="card-body" style="display:flex;align-items:center;gap:20px">
      <canvas id="gradeChart" style="max-width:180px;max-height:180px"></canvas>
      <div style="flex:1">
        <?php foreach($gInfo as $g=>[$col,$ic,$icon,$lbl]): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:5px 0;border-bottom:1px solid var(--border);font-size:13px">
          <div style="display:flex;align-items:center;gap:8px">
            <div style="width:10px;height:10px;border-radius:2px;background:<?= $col ?>"></div><?= $lbl ?>
          </div>
          <strong><?= $gradeDist[$g] ?></strong>
        </div>
        <?php endforeach; ?>
        <?php if($totalGrades > 0): ?>
        <div style="margin-top:8px;font-size:12px;color:var(--gray);text-align:center"><?= $totalGrades ?> total marks entered</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<div class="grid g2" style="margin-bottom:20px">

  <!-- My Class Streams -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-people-fill"></i> My Class Stream(s)</h5>
      <a href="<?= $u('teacher/my-learners') ?>" class="btn btn-sm btn-primary"><i class="bi bi-people"></i> View All</a>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($myStreams)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)">Not assigned as class teacher yet</div>
      <?php else: ?>
      <?php foreach($myStreams as $ms): ?>
      <div style="padding:14px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
        <div>
          <div style="font-weight:600"><?= htmlspecialchars($ms['full_name']) ?></div>
          <div style="font-size:12px;color:var(--gray)">Capacity: <?= $ms['capacity'] ?> &bull; Enrolled: <strong><?= $ms['learner_count'] ?></strong></div>
        </div>
        <div style="display:flex;gap:6px">
          <a href="<?= $u('teacher/attendance?stream_id='.$ms['id']) ?>" class="btn btn-sm btn-secondary" title="Attendance"><i class="bi bi-calendar-check"></i></a>
          <a href="<?= $u('teacher/my-learners?stream_id='.$ms['id']) ?>" class="btn btn-sm btn-outline" title="Learners"><i class="bi bi-people"></i></a>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <!-- At-Risk Learners -->
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-exclamation-triangle" style="color:var(--danger)"></i> At-Risk Learners <span class="badge badge-danger"><?= count($atRisk) ?></span></h5>
      <span style="font-size:12px;color:var(--gray)">BE in 2+ subjects</span>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($atRisk)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)"><i class="bi bi-check-circle" style="color:var(--success);font-size:28px;display:block;margin-bottom:8px"></i>No at-risk learners</div>
      <?php else: ?>
      <?php foreach($atRisk as $r): ?>
      <div style="padding:11px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
        <div>
          <div style="font-weight:500;font-size:13px"><?= htmlspecialchars($r['name']) ?></div>
          <div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($r['assessment_no']) ?> &bull; Avg: <?= $r['avg_score'] ?>%</div>
        </div>
        <span class="badge badge-danger"><?= $r['be_count'] ?> BE</span>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Subject Detail Table -->
<?php if(!empty($subjectPerf)): ?>
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><h5><i class="bi bi-table"></i> Class Performance Report</h5></div>
  <div class="table-wrap"><table>
    <thead><tr><th>Subject</th><th>Avg Score</th><th>Learners</th><th style="color:#065f46">EE</th><th style="color:#1e40af">ME</th><th style="color:#92400e">AE</th><th style="color:#991b1b">BE</th><th>Level</th></tr></thead>
    <tbody>
      <?php foreach($subjectPerf 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><strong><?= htmlspecialchars($s['name']) ?></strong></td>
        <td>
          <div style="display:flex;align-items:center;gap:8px">
            <div style="flex:1;background:var(--light);border-radius:4px;height:6px;min-width:60px">
              <div style="width:<?= min(100,$avg) ?>%;background:<?= $avg>=75?'var(--success)':($avg>=50?'#3b82f6':($avg>=25?'var(--warning)':'var(--danger)')) ?>;height:6px;border-radius:4px"></div>
            </div>
            <strong><?= $avg ?>%</strong>
          </div>
        </td>
        <td><?= $s['learner_count'] ?></td>
        <td><span class="badge badge-success"><?= $s['ee'] ?></span></td>
        <td><span class="badge badge-info"><?= $s['me'] ?></span></td>
        <td><span class="badge badge-warning"><?= $s['ae'] ?></span></td>
        <td><span class="badge badge-danger"><?= $s['be'] ?></span></td>
        <td><span class="badge <?= $cls ?>"><?= $lvl ?></span></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table></div>
</div>
<?php endif; ?>

<!-- Recent Marks + Assignments -->
<div class="grid g2">
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-clock-history"></i> Recently Entered Marks</h5></div>
    <div class="card-body" style="padding:0">
      <?php if(empty($recentMarks)): ?>
      <div style="padding:20px;text-align:center;color:var(--gray)">No marks entered yet</div>
      <?php else: ?>
      <?php foreach($recentMarks as $m):
        $g = $m['grade'] ?? '';
        $cls = ['EE'=>'badge-success','ME'=>'badge-info','AE'=>'badge-warning','BE'=>'badge-danger'][$g] ?? 'badge-gray'; ?>
      <div style="padding:10px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between">
        <div>
          <div style="font-size:13px;font-weight:500"><?= htmlspecialchars($m['student_name']) ?></div>
          <div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($m['subject_name']) ?> &bull; <?= htmlspecialchars($m['exam_name']) ?></div>
        </div>
        <div style="display:flex;align-items:center;gap:6px">
          <strong><?= $m['score'] ?>%</strong>
          <span class="badge <?= $cls ?>"><?= $g ?></span>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-file-earmark-text"></i> My Assignments</h5>
      <a href="<?= $u('teacher/assignments') ?>" class="btn btn-sm btn-primary"><i class="bi bi-plus"></i> New</a>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($assignments)): ?>
      <div style="padding:20px;text-align:center;color:var(--gray)">No assignments yet</div>
      <?php else: ?>
      <?php foreach($assignments as $a): ?>
      <div style="padding:12px 20px;border-bottom:1px solid var(--border)">
        <div style="font-weight:500;font-size:13px"><?= htmlspecialchars($a['title']) ?></div>
        <div style="font-size:12px;color:var(--gray);margin-top:2px">
          <i class="bi bi-calendar"></i> Due: <?= $a['due_date'] ?> &bull;
          <?= htmlspecialchars($a['subject_name']) ?> &bull;
          <?= htmlspecialchars($a['stream_name']) ?>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php
$gradeJson = json_encode(array_values($gradeDist));
$subNJson  = json_encode($subNames);
$subAJson  = json_encode($subAvgs);
$subCJson  = json_encode($subColors);

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

new Chart("gradeChart",{type:"doughnut",data:{labels:["EE","ME","AE","BE"],datasets:[{data:'.$gradeJson.',backgroundColor:["#065f46","#1e40af","#92400e","#991b1b"],borderWidth:2,borderColor:"#fff"}]},options:{cutout:"65%",plugins:{legend:{display:false}}}});

'.(!empty($subjectPerf)?'
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>';
?>
