<?php
require_once __DIR__ . '/../admin/_nav.php';
$pageTitle  = 'Deputy Dashboard';
$sidebarNav = deputyNav();
$u = function($p) { return \Core\View::url($p); };
$hour  = (int)date('H');
$greet = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$user  = \Core\Session::get('user');

$days7 = [];
for ($i = 6; $i >= 0; $i--) $days7[] = date('Y-m-d', strtotime("-$i days"));
$attMap = [];
foreach ($attendanceWeek as $r) $attMap[$r['date']][$r['status']] = (int)$r['cnt'];
$attPresent = array_map(function($d) use ($attMap){ return $attMap[$d]['present'] ?? 0; }, $days7);
$attAbsent  = array_map(function($d) use ($attMap){ return $attMap[$d]['absent']  ?? 0; }, $days7);
$attLabels  = array_map(function($d){ return date('D d', strtotime($d)); }, $days7);
$streamNames  = array_column($streamCount, 'stream_name');
$streamCounts = array_map(function($s){ return (int)$s['cnt']; }, $streamCount);
?>

<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(' ', $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') ?> &bull; Deputy Head Teacher</p>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <a href="<?= $u('admin/students') ?>" class="btn btn-primary"><i class="bi bi-people"></i> Learners</a>
    <a href="<?= $u('admin/attendance') ?>" class="btn btn-secondary"><i class="bi bi-calendar-check"></i> Attendance</a>
    <a href="<?= $u('admin/analytics') ?>" class="btn btn-secondary"><i class="bi bi-graph-up-arrow"></i> Analytics</a>
  </div>
</div>

<!-- KPI Cards -->
<div class="grid g4" style="margin-bottom:20px">
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-people-fill"></i></div>
    <div class="stat-info"><h3><?= number_format($stats['students']) ?></h3><p>Total Learners</p></div>
    <div style="margin-left:auto"><span class="badge badge-success"><?= $stats['streams'] ?> streams</span></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-blue"><i class="bi bi-person-badge"></i></div>
    <div class="stat-info"><h3><?= number_format($stats['teachers']) ?></h3><p>Teachers</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-person-check"></i></div>
    <div class="stat-info"><h3><?= $stats['present_today'] ?></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)"><?= $stats['absent_today'] ?></div>
      <div style="font-size:11px;color:var(--gray)">absent</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-amber"><i class="bi bi-journal-check"></i></div>
    <div class="stat-info"><h3><?= $stats['exams_total'] ?></h3><p>Assessments</p></div>
  </div>
</div>

<!-- Fee summary — READ ONLY banner -->
<div style="background:#fef3c7;border:1px solid #fde68a;border-radius:8px;padding:10px 16px;margin-bottom:16px;font-size:13px;color:#92400e;display:flex;align-items:center;gap:8px">
  <i class="bi bi-eye"></i> <strong>Finance — View Only.</strong> You can view fee data but cannot make changes.
</div>

<div class="grid g3" style="margin-bottom:20px">
  <div class="stat-card">
    <div class="stat-icon si-blue"><i class="bi bi-cash-stack"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($expected) ?></h3><p>Expected Fees</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-check-circle"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($collected) ?></h3><p>Collected (<?= $feeRate ?>%)</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-red"><i class="bi bi-exclamation-circle"></i></div>
    <div class="stat-info"><h3>KES <?= number_format($expected - $collected) ?></h3><p>Outstanding</p></div>
    <div style="margin-left:auto"><a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-sm btn-secondary">View</a></div>
  </div>
</div>

<div class="grid g2" style="margin-bottom:20px">
  <!-- Attendance chart -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-calendar-week"></i> Attendance — Last 7 Days</h5></div>
    <div class="card-body"><canvas id="attChart" height="200"></canvas></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>
      <a href="<?= $u('admin/analytics') ?>" class="btn btn-sm btn-secondary">Full Report</a>
    </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:10px 18px;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['class_name']??'').' '.($r['stream_name']??'')) ?></div>
        </div>
        <span class="badge badge-danger"><?= $r['be_count'] ?> BE</span>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Stream enrolment -->
<?php if(!empty($streamCount)): ?>
<div class="card" style="margin-bottom:20px">
  <div class="card-header"><h5><i class="bi bi-diagram-3"></i> Enrolment by Stream</h5></div>
  <div class="card-body"><canvas id="streamChart" height="100"></canvas></div>
</div>
<?php endif; ?>

<!-- Quick Actions -->
<div class="card">
  <div class="card-header"><h5><i class="bi bi-lightning-charge"></i> Quick Actions</h5></div>
  <div class="card-body">
    <div style="display:flex;gap:10px;flex-wrap:wrap">
      <a href="<?= $u('admin/students') ?>" class="btn btn-secondary"><i class="bi bi-people"></i> View Learners</a>
      <a href="<?= $u('admin/teachers') ?>" class="btn btn-secondary"><i class="bi bi-person-badge"></i> View Teachers</a>
      <a href="<?= $u('admin/exams') ?>" class="btn btn-secondary"><i class="bi bi-journal-text"></i> Assessments</a>
      <a href="<?= $u('admin/attendance') ?>" class="btn btn-secondary"><i class="bi bi-calendar-check"></i> Attendance</a>
      <a href="<?= $u('admin/analytics') ?>" class="btn btn-secondary"><i class="bi bi-graph-up-arrow"></i> Analytics</a>
      <a href="<?= $u('admin/notifications') ?>" class="btn btn-secondary"><i class="bi bi-bell"></i> Notifications</a>
      <a href="<?= $u('admin/sms') ?>" class="btn btn-secondary"><i class="bi bi-chat-dots"></i> Send SMS</a>
      <a href="<?= $u('admin/library') ?>" class="btn btn-secondary"><i class="bi bi-book"></i> Library</a>
    </div>
  </div>
</div>

<?php
$attPJson  = json_encode($attPresent);
$attAJson  = json_encode($attAbsent);
$attLJson  = json_encode($attLabels);
$stNJson   = json_encode($streamNames);
$stCJson   = json_encode($streamCounts);
$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("attChart",{type:"bar",data:{labels:'.$attLJson.',datasets:[{label:"Present",data:'.$attPJson.',backgroundColor:"rgba(16,185,129,.75)",borderRadius:4},{label:"Absent",data:'.$attAJson.',backgroundColor:"rgba(239,68,68,.75)",borderRadius:4}]},options:{responsive:true,plugins:{legend:{position:"top"}},scales:{x:{stacked:true,grid:{display:false}},y:{stacked:true,beginAtZero:true}}}});
'.(!empty($streamCount)?'new Chart("streamChart",{type:"bar",data:{labels:'.$stNJson.',datasets:[{label:"Learners",data:'.$stCJson.',backgroundColor:"rgba(37,99,235,.7)",borderRadius:4}]},options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{stepSize:1}},x:{grid:{display:false}}}}});':'').'
</script>';
?>
