<?php
require_once __DIR__ . '/_nav.php';
$pageTitle  = 'Dashboard';
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };
$extraStyles = '<style>
  #subjectCard{grid-column:span 2}
  @media(max-width:1100px){#subjectCard{grid-column:span 1}}
  @media(max-width:600px){#subjectCard{grid-column:span 1}}
  .dash-header-actions{display:flex;gap:8px;flex-wrap:wrap}
  .kpi-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-bottom:20px}
  @media(max-width:1280px){.kpi-grid{grid-template-columns:repeat(4,minmax(0,1fr))}}
  @media(max-width:900px){.kpi-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}
  @media(max-width:600px){.kpi-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
</style>';

// ── Fee chart data ──────────────────────────────────────────
$feeChart = array_fill(1, 12, 0);
foreach ($feeByMonth as $row) $feeChart[(int)$row['month']] = (float)$row['total'];

$collected = (float)($stats['fee_summary']['collected'] ?? 0);
$expected  = (float)($stats['fee_summary']['expected']  ?? 0);
$balance   = $expected - $collected;
$feeRate   = $expected > 0 ? round($collected / $expected * 100, 1) : 0;

// ── Competency dist ─────────────────────────────────────────
$compMap = ['EE'=>0,'ME'=>0,'AE'=>0,'BE'=>0];
foreach ($competencyDist as $r) $compMap[$r['rating']] = (int)$r['cnt'];

// ── Grade dist ──────────────────────────────────────────────
$gradeMap = ['EE'=>0,'ME'=>0,'AE'=>0,'BE'=>0];
foreach ($gradeDist as $r) $gradeMap[$r['grade']] = (int)$r['cnt'];

// ── Attendance last 7 days ───────────────────────────────────
$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);

// ── Fee status ───────────────────────────────────────────────
$feeStatusMap = ['paid'=>0,'partial'=>0,'unpaid'=>0];
foreach ($feeStatus as $r) $feeStatusMap[$r['status']] = (int)$r['cnt'];

// ── Gender ───────────────────────────────────────────────────
$genderMap = ['male'=>0,'female'=>0];
foreach ($genderDist as $r) $genderMap[$r['gender'] ?? 'male'] = (int)$r['cnt'];

// ── Stream chart ─────────────────────────────────────────────
$streamNames  = array_column($streamCount, 'stream_name');
$streamCounts = array_map(function($s) { return (int)$s['cnt']; }, $streamCount);

// ── Subject perf ─────────────────────────────────────────────
$subNames = array_column($subjectPerf, 'name');
$subAvgs  = array_map(fn($s) => (float)$s['avg_score'], $subjectPerf);

$today = date('l, d F Y');
$hour  = (int)date('H');
$greet = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$user  = \Core\Session::get('user');
?>

<!-- ── Header ─────────────────────────────────────────────── -->
<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> <?= $today ?></p>
  </div>
  <div class="dash-header-actions">
    <a href="<?= $u('admin/sms') ?>" class="btn btn-primary"><i class="bi bi-chat-dots"></i> Send SMS</a>
    <a href="<?= $u('admin/analytics') ?>" class="btn btn-secondary"><i class="bi bi-graph-up-arrow"></i> Analytics</a>
    <a href="<?= $u('admin/students/create') ?>" class="btn btn-secondary"><i class="bi bi-person-plus"></i> Enroll Learner</a>
  </div>
</div>

<!-- ── KPI Cards ─────────────────────────────────────────── -->
<div class="kpi-grid">
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-green" style="width:36px;height:36px;font-size:16px"><i class="bi bi-people-fill"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($stats['students']) ?></h3><p>Learners</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-blue" style="width:36px;height:36px;font-size:16px"><i class="bi bi-person-badge"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($stats['teachers']) ?></h3><p>Teachers</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-amber" style="width:36px;height:36px;font-size:16px"><i class="bi bi-diagram-3"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($stats['streams']) ?></h3><p>Streams</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon" style="width:36px;height:36px;font-size:16px;background:#fdf2f8;color:#ec4899"><i class="bi bi-person-heart"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($stats['total_parents']) ?></h3><p>Parents</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-green" style="width:36px;height:36px;font-size:16px"><i class="bi bi-cash-coin"></i></div>
    <div class="stat-info"><h3 style="font-size:16px">KES <?= number_format($collected) ?></h3><p>Collected (<?= $feeRate ?>%)</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon" style="width:36px;height:36px;font-size:16px;background:#f5f3ff;color:#8b5cf6"><i class="bi bi-cash-stack"></i></div>
    <div class="stat-info"><h3 style="font-size:16px">KES <?= number_format($expected) ?></h3><p>Expected</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-red" style="width:36px;height:36px;font-size:16px"><i class="bi bi-receipt-cutoff"></i></div>
    <div class="stat-info"><h3 style="font-size:16px">KES <?= number_format($balance) ?></h3><p>Outstanding</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-red" style="width:36px;height:36px;font-size:16px"><i class="bi bi-exclamation-circle"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($stats['pending_invoices']) ?></h3><p>Pending Inv.</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-green" style="width:36px;height:36px;font-size:16px"><i class="bi bi-check2-all"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= number_format($feeStatusMap['paid'] ?? 0) ?></h3><p>Paid Inv.</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-green" style="width:36px;height:36px;font-size:16px"><i class="bi bi-person-check"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= $stats['present_today'] ?></h3><p>Present Today</p></div>
  </div>
  <div class="stat-card" style="padding:12px">
    <div class="stat-icon si-green" style="width:36px;height:36px;font-size:16px"><i class="bi bi-journal-check"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= $stats['exams_total'] ?></h3><p>Assessments</p></div>
  </div>
  <div class="stat-card" style=">0?'var(--danger)':'var(--success)' ?>;padding:12px">
    <div class="stat-icon <?= $atRiskCount>0?'si-red':'si-green' ?>" style="width:36px;height:36px;font-size:16px"><i class="bi bi-exclamation-triangle"></i></div>
    <div class="stat-info"><h3 style="font-size:16px"><?= $atRiskCount ?></h3><p>At-Risk</p></div>
  </div>
</div>

<!-- ── Row: Fee Trend + Attendance Week ───────────────────── -->
<div class="grid g2" style="margin-bottom:16px">
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-bar-chart-line"></i> Fee Collection <?= date('Y') ?></h5>
      <span style="font-size:12px;color:var(--gray)">Monthly trend</span>
    </div>
    <div class="card-body"><canvas id="feeChart" height="200"></canvas></div>
  </div>
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-calendar-week"></i> Attendance — Last 7 Days</h5>
      <span style="font-size:12px;color:var(--gray)">Present vs Absent</span>
    </div>
    <div class="card-body"><canvas id="attChart" height="200"></canvas></div>
  </div>
</div>

<!-- ── Row: CBC Competency Pie + Grade Dist + Fee Status ──── -->
<div class="grid g3" style="margin-bottom:16px">
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-pie-chart"></i> Competency Ratings</h5></div>
    <div class="card-body" style="display:flex;flex-direction:column;align-items:center">
      <canvas id="compChart" style="max-width:180px;max-height:180px;margin-bottom:16px"></canvas>
      <div style="width:100%">
        <?php foreach(['EE'=>['#065f46','Exceeding'],'ME'=>['#1e40af','Meeting'],'AE'=>['#92400e','Approaching'],'BE'=>['#991b1b','Below']] as $k=>[$col,$lbl]): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:4px 0;border-bottom:1px solid var(--border);font-size:12px">
          <div style="display:flex;align-items:center;gap:6px"><div style="width:10px;height:10px;border-radius:2px;background:<?= $col ?>"></div><?= $lbl ?></div>
          <strong><?= $compMap[$k] ?></strong>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header"><h5><i class="bi bi-pie-chart-fill"></i> Assessment Grades</h5></div>
    <div class="card-body" style="display:flex;flex-direction:column;align-items:center">
      <canvas id="gradeChart" style="max-width:180px;max-height:180px;margin-bottom:16px"></canvas>
      <div style="width:100%">
        <?php foreach(['EE'=>['#10b981','EE — Exceeding'],'ME'=>['#3b82f6','ME — Meeting'],'AE'=>['#f59e0b','AE — Approaching'],'BE'=>['#ef4444','BE — Below']] as $k=>[$col,$lbl]): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:4px 0;border-bottom:1px solid var(--border);font-size:12px">
          <div style="display:flex;align-items:center;gap:6px"><div style="width:10px;height:10px;border-radius:2px;background:<?= $col ?>"></div><?= $lbl ?></div>
          <strong><?= $gradeMap[$k] ?></strong>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-header"><h5><i class="bi bi-donut-chart"></i> Fee Invoice Status</h5></div>
    <div class="card-body" style="display:flex;flex-direction:column;align-items:center">
      <canvas id="feeStatusChart" style="max-width:180px;max-height:180px;margin-bottom:16px"></canvas>
      <div style="width:100%">
        <?php foreach(['paid'=>['#10b981','Fully Paid'],'partial'=>['#f59e0b','Partial'],'unpaid'=>['#ef4444','Unpaid']] as $k=>[$col,$lbl]): ?>
        <div style="display:flex;align-items:center;justify-content:space-between;padding:4px 0;border-bottom:1px solid var(--border);font-size:12px">
          <div style="display:flex;align-items:center;gap:6px"><div style="width:10px;height:10px;border-radius:2px;background:<?= $col ?>"></div><?= $lbl ?></div>
          <strong><?= $feeStatusMap[$k] ?></strong>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<!-- ── Row: Subject Performance + Gender + Stream ─────────── -->
<div class="grid g3" style="margin-bottom:20px">
  <div class="card" style="grid-column:span 2" id="subjectCard">
    <div class="card-header">
      <h5><i class="bi bi-bar-chart-horizontal"></i> Subject Performance (Avg Score)</h5>
      <a href="<?= $u('admin/analytics') ?>" class="btn btn-sm btn-secondary">Full Report</a>
    </div>
    <div class="card-body"><canvas id="subjectChart" height="200"></canvas></div>
  </div>

  <div class="card">
    <div class="card-header"><h5><i class="bi bi-gender-ambiguous"></i> Gender Distribution</h5></div>
    <div class="card-body" style="display:flex;flex-direction:column;align-items:center">
      <canvas id="genderChart" style="max-width:180px;max-height:180px;margin-bottom:16px"></canvas>
      <div style="width:100%">
        <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border)">
          <div style="display:flex;align-items:center;gap:8px"><i class="bi bi-person" style="color:#3b82f6"></i> Male</div>
          <strong><?= $genderMap['male'] ?></strong>
        </div>
        <div style="display:flex;justify-content:space-between;padding:8px 0">
          <div style="display:flex;align-items:center;gap:8px"><i class="bi bi-person" style="color:#ec4899"></i> Female</div>
          <strong><?= $genderMap['female'] ?></strong>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── Row: Stream Enrolment Bar ──────────────────────────── -->
<?php if(!empty($streamCount)): ?>
<div class="card" style="margin-bottom:20px">
  <div class="card-header">
    <h5><i class="bi bi-diagram-3"></i> Learner Enrolment by Stream</h5>
    <span style="font-size:12px;color:var(--gray)"><?= array_sum($streamCounts) ?> active learners</span>
  </div>
  <div class="card-body"><canvas id="streamChart" height="120"></canvas></div>
</div>
<?php endif; ?>

<!-- ── Row: Recent Payments + Activity Log ────────────────── -->
<div class="grid g2" style="margin-bottom:16px">
  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-credit-card"></i> Recent Payments</h5>
      <a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-sm btn-secondary">View All</a>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($recentPayments)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)"><i class="bi bi-inbox" style="font-size:32px;display:block;margin-bottom:8px"></i>No payments yet</div>
      <?php else: ?>
      <?php foreach($recentPayments as $p): ?>
      <div style="padding:12px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px">
        <div class="stat-icon si-green" style="width:36px;height:36px;font-size:14px;border-radius:8px;flex-shrink:0">
          <i class="bi bi-<?= $p['method']==='mpesa'?'phone':'cash' ?>"></i>
        </div>
        <div style="flex:1">
          <div style="font-weight:500;font-size:13px"><?= htmlspecialchars($p['student_name']) ?></div>
          <div style="font-size:11px;color:var(--gray)"><?= ucfirst($p['method']) ?> &bull; <?= $p['payment_date'] ?></div>
        </div>
        <div style="font-weight:700;color:var(--success)">KES <?= number_format($p['amount']) ?></div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <h5><i class="bi bi-activity"></i> Recent Activity</h5>
      <a href="<?= $u('admin/logs') ?>" class="btn btn-sm btn-secondary">All Logs</a>
    </div>
    <div class="card-body" style="padding:0">
      <?php if(empty($recentLogs)): ?>
      <div style="padding:30px;text-align:center;color:var(--gray)">No activity yet</div>
      <?php else: ?>
      <?php
      $actionColors = ['login'=>'si-green','logout'=>'si-blue','created'=>'si-green','updated'=>'si-amber','deleted'=>'si-red','default'=>'si-blue'];
      foreach($recentLogs as $log):
        $ac = $actionColors[$log['action']] ?? $actionColors['default'];
      ?>
      <div style="padding:11px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px">
        <div class="stat-icon <?= $ac ?>" style="width:32px;height:32px;font-size:13px;border-radius:8px;flex-shrink:0">
          <?= strtoupper(substr($log['user_name'] ?? 'S', 0, 1)) ?>
        </div>
        <div style="flex:1">
          <div style="font-size:13px;font-weight:500"><?= htmlspecialchars($log['user_name'] ?? 'System') ?></div>
          <div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars(ucfirst($log['action'])) ?> <?= htmlspecialchars($log['model'] ?? '') ?></div>
        </div>
        <div style="font-size:11px;color:var(--gray)"><?= date('H:i', strtotime($log['created_at'] ?? 'now')) ?></div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ── 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/create') ?>" class="btn btn-primary"><i class="bi bi-person-plus"></i> Enroll Learner</a>
      <a href="<?= $u('admin/sms') ?>" class="btn btn-secondary"><i class="bi bi-chat-dots"></i> Send SMS</a>
      <a href="<?= $u('admin/exams') ?>" class="btn btn-secondary"><i class="bi bi-journal-plus"></i> New Assessment</a>
      <a href="<?= $u('admin/attendance') ?>" class="btn btn-secondary"><i class="bi bi-calendar-check"></i> Take Attendance</a>
      <a href="<?= $u('admin/fees/invoices') ?>" class="btn btn-secondary"><i class="bi bi-receipt"></i> Record Payment</a>
      <a href="<?= $u('admin/competency') ?>" class="btn btn-secondary"><i class="bi bi-stars"></i> Rate Competencies</a>
      <a href="<?= $u('admin/notifications') ?>" class="btn btn-secondary"><i class="bi bi-bell"></i> Send Notification</a>
      <a href="<?= $u('admin/users') ?>" class="btn btn-secondary"><i class="bi bi-person-gear"></i> Manage Users</a>
      <a href="<?= $u('admin/analytics') ?>" class="btn btn-outline"><i class="bi bi-graph-up-arrow"></i> Analytics Engine</a>
    </div>
  </div>
</div>

<?php
$feeJson     = json_encode(array_values($feeChart));
$compJson    = json_encode(array_values($compMap));
$gradeJson   = json_encode(array_values($gradeMap));
$feeStJson   = json_encode(array_values($feeStatusMap));
$genderJson  = json_encode(array_values($genderMap));
$attPJson    = json_encode($attPresent);
$attAJson    = json_encode($attAbsent);
$attLJson    = json_encode($attLabels);
$subNJson    = json_encode($subNames);
$subAJson    = json_encode($subAvgs);
$stNJson     = json_encode($streamNames);
$stCJson     = json_encode($streamCounts);

$extraScripts = '
<script src="/cbe/sms/public/assets/chart.min.js"></script>
<script>
const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
Chart.defaults.font.family="Inter,sans-serif";
Chart.defaults.font.size=12;

// Fee bar
new Chart("feeChart",{type:"bar",data:{labels:M,datasets:[{label:"KES",data:'.$feeJson.',backgroundColor:"rgba(26,127,90,.75)",borderRadius:6,borderSkipped:false}]},options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{callback:v=>"KES "+v.toLocaleString()},grid:{color:"rgba(0,0,0,.05)"}},x:{grid:{display:false}}}}});

// Attendance stacked
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,grid:{color:"rgba(0,0,0,.05)"}}}}});

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

// Grade doughnut
new Chart("gradeChart",{type:"doughnut",data:{labels:["EE","ME","AE","BE"],datasets:[{data:'.$gradeJson.',backgroundColor:["#10b981","#3b82f6","#f59e0b","#ef4444"],borderWidth:3,borderColor:"#fff"}]},options:{cutout:"68%",plugins:{legend:{display:false}}}});

// Fee status doughnut
new Chart("feeStatusChart",{type:"doughnut",data:{labels:["Paid","Partial","Unpaid"],datasets:[{data:'.$feeStJson.',backgroundColor:["#10b981","#f59e0b","#ef4444"],borderWidth:3,borderColor:"#fff"}]},options:{cutout:"68%",plugins:{legend:{display:false}}}});

// Gender pie
new Chart("genderChart",{type:"pie",data:{labels:["Male","Female"],datasets:[{data:'.$genderJson.',backgroundColor:["#3b82f6","#ec4899"],borderWidth:3,borderColor:"#fff"}]},options:{plugins:{legend:{display:false}}}});

// Subject horizontal bar
new Chart("subjectChart",{type:"bar",data:{labels:'.$subNJson.',datasets:[{label:"Avg Score",data:'.$subAJson.',backgroundColor:'.$subAJson.'.map(v=>v>=75?"rgba(16,185,129,.8)":v>=50?"rgba(59,130,246,.8)":v>=25?"rgba(245,158,11,.8)":"rgba(239,68,68,.8)"),borderRadius:4}]},options:{indexAxis:"y",responsive:true,plugins:{legend:{display:false}},scales:{x:{beginAtZero:true,max:100,ticks:{callback:v=>v+"%"},grid:{color:"rgba(0,0,0,.05)"}},y:{grid:{display:false}}}}});

// Stream enrolment
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},grid:{color:"rgba(0,0,0,.05)"}},x:{grid:{display:false}}}}});
</script>';
?>

