<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header('Location: ../index.php'); exit(); }
if (file_exists(__DIR__ . '/../../db.php')) {
    require_once __DIR__ . '/../../db.php';
} elseif (file_exists(__DIR__ . '/../db.php')) {
    require_once __DIR__ . '/../db.php';
}

if (file_exists(__DIR__ . '/../../result_db_setup.php')) {
    require_once __DIR__ . '/../../result_db_setup.php';
} elseif (file_exists(__DIR__ . '/../result_db_setup.php')) {
    require_once __DIR__ . '/../result_db_setup.php';
} elseif (file_exists(__DIR__ . '/result_db_setup.php')) {
    require_once __DIR__ . '/result_db_setup.php';
}
setupResultTables($conn);

$sel_class=intval($_GET['class_id']??0); $sel_term=intval($_GET['term_id']??0);
$classes=$conn->query("SELECT rc.*,rs.session_name FROM result_classes rc JOIN result_sessions rs ON rc.session_id=rs.id ORDER BY rs.is_active DESC,rc.numeric_level,rc.section");
$terms=$conn->query("SELECT rt.*,rs.session_name FROM result_terms rt JOIN result_sessions rs ON rt.session_id=rs.id ORDER BY rs.is_active DESC,rt.display_order");

// Analytics data
$class_stats=[];
if($sel_class&&$sel_term){
    $students=$conn->query("SELECT id,first_name,last_name,roll_no FROM result_students WHERE class_id=$sel_class AND is_active=1");
    $stu_ids=[];
    while($s=$students->fetch_assoc()) $stu_ids[$s['id']]=$s;
    
    if(!empty($stu_ids)){
        $sids=implode(',',array_keys($stu_ids));
        $marks=$conn->query("SELECT m.student_id,SUM(m.marks_obtained) as tot_obt,SUM(es.max_marks) as tot_max FROM result_marks m JOIN result_exam_structure es ON m.exam_structure_id=es.id JOIN result_subjects sub ON es.subject_id=sub.id WHERE m.student_id IN($sids) AND es.term_id=$sel_term AND m.status='present' AND sub.is_scholastic=1 AND sub.grading_type='NUMERIC' GROUP BY m.student_id ORDER BY tot_obt DESC");
        $rank=1; $gradeCount=[]; $passCount=0;
        while($m=$marks->fetch_assoc()){
            $sid=$m['student_id'];
            $pct=$m['tot_max']>0?round($m['tot_obt']/$m['tot_max']*100,1):0;
            $g=getGrade($conn,$pct,'PRIMARY');
            $gradeCount[$g['grade_letter']]=($gradeCount[$g['grade_letter']]??0)+1;
            if($pct>=33) $passCount++;
            $class_stats[]=['rank'=>$rank,'name'=>$stu_ids[$sid]['first_name'].' '.$stu_ids[$sid]['last_name'],'roll'=>$stu_ids[$sid]['roll_no'],'total'=>$m['tot_obt'],'max'=>$m['tot_max'],'pct'=>$pct,'grade'=>$g['grade_letter'],'desc'=>$g['description']];
            $rank++;
        }
        $totalStu=count($stu_ids); $failCount=$totalStu-$passCount;
    }
}
?>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Analytics | Result</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<?php include __DIR__.'/_sidebar_style.php'; ?></head><body>
<?php include __DIR__.'/_sidebar.php'; ?>
<div class="main">
<div class="topbar"><h4><i class="fas fa-chart-bar me-2" style="color:var(--primary)"></i>Analytics & Reports</h4></div>
<div class="card-box mb-3 p-3">
<form method="GET" class="row g-2 align-items-end">
<div class="col-md-4"><select name="class_id" class="form-select form-select-sm">
<option value="">-- Class --</option>
<?php while($c=$classes->fetch_assoc()): ?><option value="<?=$c['id']?>" <?=$sel_class==$c['id']?'selected':''?> ><?=$c['class_name'].' '.$c['section']?></option><?php endwhile; ?></select></div>
<div class="col-md-4"><select name="term_id" class="form-select form-select-sm">
<option value="">-- Term --</option>
<?php while($t=$terms->fetch_assoc()): ?><option value="<?=$t['id']?>" <?=$sel_term==$t['id']?'selected':''?> ><?=htmlspecialchars($t['term_name'])?></option><?php endwhile; ?></select></div>
<div class="col-md-4"><button type="submit" class="btn btn-primary btn-sm w-100">Load Analytics</button></div>
</form></div>
<?php if(!empty($class_stats)): ?>
<!-- Summary Cards -->
<div class="row g-3 mb-3">
<div class="col-md-3"><div class="card-box p-4 text-center"><div style="font-size:2rem;font-weight:800;color:#0b3b60"><?=$totalStu??0?></div><div style="font-size:12px;color:#64748b">Total Students</div></div></div>
<div class="col-md-3"><div class="card-box p-4 text-center"><div style="font-size:2rem;font-weight:800;color:#10b981"><?=$passCount??0?></div><div style="font-size:12px;color:#64748b">Passed</div></div></div>
<div class="col-md-3"><div class="card-box p-4 text-center"><div style="font-size:2rem;font-weight:800;color:#ef4444"><?=$failCount??0?></div><div style="font-size:12px;color:#64748b">Failed</div></div></div>
<div class="col-md-3"><div class="card-box p-4 text-center"><div style="font-size:2rem;font-weight:800;color:#f5a623"><?=($totalStu>0)?round($passCount/$totalStu*100,1):0?>%</div><div style="font-size:12px;color:#64748b">Pass Rate</div></div></div>
</div>
<!-- Charts Row -->
<div class="row g-3 mb-3">
<div class="col-md-6"><div class="card-box p-3"><h6 style="font-weight:700;margin-bottom:12px">Grade Distribution</h6>
<canvas id="gradeChart" height="200"></canvas></div></div>
<div class="col-md-6"><div class="card-box p-3"><h6 style="font-weight:700;margin-bottom:12px">Pass vs Fail</h6>
<canvas id="passChart" height="200"></canvas></div></div>
</div>
<!-- Toppers Table -->
<div class="card-box"><div class="cb-header"><h6><i class="fas fa-trophy me-2 text-warning"></i>Class Performance — Ranked</h6></div>
<table class="table mb-0"><thead><tr><th>Rank</th><th>Student</th><th>Roll</th><th>Total</th><th>%</th><th>Grade</th><th>Description</th><th>Report Card</th></tr></thead>
<tbody><?php foreach($class_stats as $st): ?>
<tr class="<?=$st['rank']<=3?'table-warning':''?>">
<td><strong><?php if($st['rank']==1) echo '🥇'; elseif($st['rank']==2) echo '🥈'; elseif($st['rank']==3) echo '🥉'; else echo $st['rank']; ?></strong></td>
<td class="fw-600"><?=htmlspecialchars($st['name'])?></td>
<td><?=$st['roll']?></td>
<td><?=$st['total']?>/<?=$st['max']?></td>
<td><strong><?=$st['pct']?>%</strong></td>
<td><span class="badge" style="background:<?=$st['pct']>=80?'#059669':($st['pct']>=60?'#3b82f6':($st['pct']>=33?'#f59e0b':'#ef4444'))?>"><?=$st['grade']?></span></td>
<td style="font-size:12px"><?=htmlspecialchars($st['desc'])?></td>
<td><a href="report_card.php?student_id=<?=array_search($st['name'],array_column($class_stats,'name',null))?>&term_id=<?=$sel_term?>" class="btn btn-sm btn-outline-info" style="font-size:11px">View</a></td>
</tr><?php endforeach; ?>
</tbody></table></div>
<script>
const gradeData = <?=json_encode($gradeCount??[])?>;
const gc=document.getElementById('gradeChart').getContext('2d');
new Chart(gc,{type:'bar',data:{labels:Object.keys(gradeData),datasets:[{label:'Students',data:Object.values(gradeData),backgroundColor:['#059669','#10b981','#3b82f6','#60a5fa','#f59e0b','#fbbf24','#ef4444','#dc2626']}]},options:{plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{stepSize:1}}}}});
const pc=document.getElementById('passChart').getContext('2d');
new Chart(pc,{type:'doughnut',data:{labels:['Passed','Failed'],datasets:[{data:[<?=$passCount??0?>,<?=$failCount??0?>],backgroundColor:['#10b981','#ef4444']}]},options:{cutout:'65%',plugins:{legend:{position:'bottom'}}}});
</script>
<?php else: ?>
<div class="text-center py-5"><div style="font-size:4rem">📊</div><h5 class="text-muted">Select class & term to view analytics</h5></div>
<?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script></body></html>
