<?php
// Filename: student_reports_admin.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'timetable_coord', 'principal', 'assistant', 'assistant_hem'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

$year = date('Y');
$s_name = getSetting('school_name', 'SMK Muadzam Shah');
$s_addr = getSetting('school_address', 'Jalan Sekolah, 26700 Muadzam Shah');

/**
 * --- 1. DEMOGRAPHICS ENGINE ---
 * Note: getCache and setCache must be defined in config.php
 * If they are not yet defined, use the fallback logic below.
 */
$demo_stats = false;
if (function_exists('getCache')) {
    $demo_stats = getCache('student_stats_v2', 3600);
}

if ($demo_stats === false) {
    
    // A. Total Count
    $total = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
    
    // B. Gender Ratio (FIXED LOGIC)
    $g_stats = $pdo->query("SELECT sex, COUNT(*) FROM students GROUP BY sex")->fetchAll(PDO::FETCH_KEY_PAIR);
    $male = 0; $female = 0;
    foreach($g_stats as $k => $v) {
        $key = strtoupper(trim($k));
        // Starts with M (Male) or L (Lelaki) -> Male
        if (strpos($key, 'M') === 0 || strpos($key, 'L') === 0) {
            $male += $v;
        } else {
            $female += $v;
        }
    }

    // C. Religion
    $rel_stats = $pdo->query("SELECT religion, COUNT(*) FROM students GROUP BY religion")->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // D. Age Groups
    $age_order = ['<13'=>0, '13'=>0, '14'=>0, '15'=>0, '16'=>0, '17'=>0, '18+'=>0];
    $invalid_by_class = [];
    $invalid_count = 0;

    try {
        $curr_year = intval(date('Y'));
        $ages_sql = "SELECT 
                        CASE 
                            WHEN ($curr_year - birth_year) < 13 THEN '<13'
                            WHEN ($curr_year - birth_year) = 13 THEN '13'
                            WHEN ($curr_year - birth_year) = 14 THEN '14'
                            WHEN ($curr_year - birth_year) = 15 THEN '15'
                            WHEN ($curr_year - birth_year) = 16 THEN '16'
                            WHEN ($curr_year - birth_year) = 17 THEN '17'
                            ELSE '18+' 
                        END as age_group,
                        COUNT(*) as count
                     FROM students 
                     WHERE birth_year IS NOT NULL
                     GROUP BY age_group";
        
        $age_raw = $pdo->query($ages_sql)->fetchAll(PDO::FETCH_KEY_PAIR);
        foreach($age_raw as $k=>$v) { if(isset($age_order[$k])) $age_order[$k] = $v; }

        $inv_sql = "SELECT s.full_name, s.ic_number, c.class_name 
                    FROM students s LEFT JOIN classes c ON s.class_id = c.id 
                    WHERE s.birth_year IS NULL OR s.birth_year = 0";
        $invalid_rows = $pdo->query($inv_sql)->fetchAll(PDO::FETCH_ASSOC);
        foreach($invalid_rows as $row) {
            $invalid_by_class[$row['class_name'] ?? 'Unassigned'][] = ['name'=>$row['full_name'], 'ic'=>$row['ic_number']];
        }
        $invalid_count = count($invalid_rows);

    } catch (Exception $e) {
        // Fallback handled by initializing variables above
    }

    $demo_stats = [
        'total' => $total,
        'male' => $male,
        'female' => $female,
        'religion' => $rel_stats,
        'ages' => $age_order,
        'invalid_list' => $invalid_by_class,
        'invalid_count' => $invalid_count
    ];

    if (function_exists('setCache')) {
        setCache('student_stats_v2', $demo_stats);
    }
}

// Extract Variables
$total_invalid = $demo_stats['invalid_count'];
$invalid_by_class = $demo_stats['invalid_list'];
$rel_labels = array_keys($demo_stats['religion']);
$rel_counts = array_values($demo_stats['religion']);

// --- 2. CLASS PERFORMANCE ---
$holiday_filter = " AND NOT EXISTS (SELECT 1 FROM school_holidays h WHERE sa.date BETWEEN h.start_date AND h.end_date) ";
$class_sql = "SELECT c.id, c.class_name, c.form_level,
        COUNT(CASE WHEN sa.date = CURDATE() AND sa.status = 'present' THEN 1 END) as day_p,
        COUNT(CASE WHEN sa.date = CURDATE() THEN 1 END) as day_t,
        COUNT(CASE WHEN MONTH(sa.date) = MONTH(CURDATE()) AND YEAR(sa.date) = YEAR(CURDATE()) AND sa.status = 'present' THEN 1 END) as mo_p,
        COUNT(CASE WHEN MONTH(sa.date) = MONTH(CURDATE()) AND YEAR(sa.date) = YEAR(CURDATE()) THEN 1 END) as mo_t
    FROM classes c
    LEFT JOIN students s ON c.id = s.class_id
    LEFT JOIN student_attendance sa ON s.id = sa.student_id $holiday_filter
    GROUP BY c.id ORDER BY c.form_level ASC, c.class_name ASC";
$classes_stats = $pdo->query($class_sql)->fetchAll(PDO::FETCH_ASSOC);

// --- 3. RISK WATCH ---
$risk_sql = "SELECT sa.student_id, sa.date, s.full_name, s.ic_number, c.class_name 
             FROM student_attendance sa 
             JOIN students s ON sa.student_id=s.id 
             JOIN classes c ON s.class_id=c.id 
             WHERE sa.status='absent' AND YEAR(sa.date)=? $holiday_filter 
             ORDER BY sa.student_id, sa.date DESC";
$stmt = $pdo->prepare($risk_sql); 
$stmt->execute([$year]);
$all_absences = $stmt->fetchAll(PDO::FETCH_GROUP);
$risk_list = [];

foreach ($all_absences as $sid => $dates) {
    $cum = count($dates); 
    $cons = 0; $last = 0;
    foreach ($dates as $row) {
        $curr = strtotime($row['date']);
        if ($last == 0 || ($last - $curr) == 86400) $cons++; else break;
        $last = $curr;
    }
    
    $lvl=0; $typ='';
    if ($cons >= 7) { $lvl=3; $typ='Warning 2'; } 
    elseif ($cons >= 3) { $lvl=2; $typ='Warning 1'; } 
    elseif ($cum >= 40) { $lvl=1; $typ='Watchlist'; }
    
    if ($lvl > 0) $risk_list[] = ['id'=>$sid, 'name'=>$dates[0]['full_name'], 'ic'=>$dates[0]['ic_number'], 'class'=>$dates[0]['class_name'], 'level'=>$lvl, 'type'=>$typ, 'streak'=>$cons, 'total'=>$cum];
}
usort($risk_list, function($a, $b) { return $b['level'] - $a['level']; });

// Discipline Trends
$disc_trend_sql = "SELECT MONTH(reported_date) as m, COUNT(*) as c FROM student_discipline WHERE YEAR(reported_date) = ? GROUP BY m";
$stmt = $pdo->prepare($disc_trend_sql); 
$stmt->execute([$year]); 
$disc_trends_raw = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$disc_chart_data = array_fill(0, 12, 0); 
foreach($disc_trends_raw as $m => $c) $disc_chart_data[$m-1] = $c;

function pct($p, $t) { return ($t > 0) ? round(($p/$t)*100) : '-'; }
function color($v) { if($v==='-') return 'text-muted'; return ($v>=90)?'text-success fw-bold':(($v>=80)?'text-warning fw-bold':'text-danger fw-bold'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Analytics</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root { 
            --primary-grad: <?= getHeaderTheme() ?>; 
            --bg-color: #f8f9fd;
            --text-gray: #64748b;
            --text-dark: #1e293b;
        }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .nav-pills { background: #f1f5f9; padding: 4px; border-radius: 12px; display: flex; width: 100%; margin-bottom: 20px; overflow-x: auto; border: none; }
        .nav-pills .nav-link { flex: 1; border-radius: 10px; color: var(--text-gray); font-weight: 700; padding: 10px 0; border: none; font-size: 0.8rem; transition: 0.2s; background: transparent; text-align: center; white-space: nowrap; }
        .nav-pills .nav-link.active { background: white; color: #8B5CF6; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .stat-card { background: #f8fafc; border-radius: 16px; padding: 15px; text-align: center; border: 1px solid #f1f5f9; height: 100%; }
        .stat-card h3 { font-weight: 800; margin: 0; color: var(--text-dark); }
        .stat-card small { font-weight: 700; font-size: 0.65rem; text-transform: uppercase; color: var(--text-gray); letter-spacing: 0.5px; }
        .st-blue { border-bottom: 4px solid #3b82f6; } 
        .st-pink { border-bottom: 4px solid #ec4899; } 
        .st-purple { border-bottom: 4px solid #8b5cf6; }
        .chart-box { position: relative; height: 220px; width: 100%; }
        
        @media print { 
            .print-area { position: absolute; left: 0; top: 0; width: 100%; background: white; z-index: 9999; display: block !important; padding: 40px; } 
            body * { visibility: hidden; } 
            .print-area * { visibility: visible; } 
            .no-print { display: none !important; } 
        }
    </style>
</head>
<body>

    <div class="app-header no-print">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Student Analytics</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Attendance & Risk Insight</div>
    </div>

    <div class="floating-card no-print">
        <div class="nav nav-pills" id="adminTabs" role="tablist">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#demographics">Demographics</button>
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#classes">Classes</button>
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#risk">Risk Watch</button>
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#discipline">Discipline</button>
        </div>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="demographics">
                <?php if($total_invalid > 0): ?>
                    <div class="alert alert-danger border-0 shadow-sm rounded-4 mb-4 d-flex align-items-center justify-content-between p-3">
                        <div class="small lh-sm text-danger"><strong>Data Alert!</strong><br><?= $total_invalid ?> students missing birth data.</div>
                        <button class="btn btn-light btn-sm text-danger fw-bold rounded-pill" data-bs-toggle="modal" data-bs-target="#invalidICModal">View</button>
                    </div>
                <?php endif; ?>

                <div class="row g-3 mb-4">
                    <div class="col-4"><div class="stat-card st-purple"><h3><?= number_format($demo_stats['total']) ?></h3><small>Total</small></div></div>
                    <div class="col-4"><div class="stat-card st-blue"><h3 class="text-primary"><?= number_format($demo_stats['male']) ?></h3><small>Male</small></div></div>
                    <div class="col-4"><div class="stat-card st-pink"><h3 class="text-danger"><?= number_format($demo_stats['female']) ?></h3><small>Female</small></div></div>
                </div>

                <div class="card border-0 shadow-sm rounded-4 p-3 mb-3">
                    <h6 class="small fw-bold text-muted mb-3 text-uppercase">Gender Ratio</h6>
                    <div class="chart-box" style="height:200px;"><canvas id="genderChart"></canvas></div>
                </div>

                <div class="row g-3">
                    <div class="col-md-6"><div class="card border-0 shadow-sm rounded-4 p-3 h-100"><h6 class="small fw-bold text-muted mb-3 text-uppercase">Religion</h6><div class="chart-box"><canvas id="religionChart"></canvas></div></div></div>
                    <div class="col-md-6"><div class="card border-0 shadow-sm rounded-4 p-3 h-100"><h6 class="small fw-bold text-muted mb-3 text-uppercase">Age Groups</h6><div class="chart-box"><canvas id="ageChart"></canvas></div></div></div>
                </div>
            </div>

            <div class="tab-pane fade" id="classes">
                <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                    <div class="card-header bg-white py-3 border-bottom"><h6 class="fw-bold m-0 text-dark small text-uppercase">Attendance Rate</h6></div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 small">
                            <thead class="bg-light"><tr><th class="ps-3">Class</th><th class="text-center">Today</th><th class="text-center pe-3">Month</th></tr></thead>
                            <tbody><?php foreach($classes_stats as $c): $day_p = pct($c['day_p'], $c['day_t']); $mo_p = pct($c['mo_p'], $c['mo_t']); ?>
                                <tr onclick="openClassModal(<?= $c['id'] ?>, '<?= htmlspecialchars($c['class_name']) ?>')" style="cursor:pointer;">
                                    <td class="ps-3"><div class="fw-bold text-dark"><?= htmlspecialchars($c['class_name']) ?></div></td>
                                    <td class="text-center fw-bold <?= color($day_p) ?>"><?= $day_p ?>%</td>
                                    <td class="text-center pe-3"><div class="progress" style="width: 50px; height: 6px; display:inline-flex;"><div class="progress-bar <?= ($mo_p>=90)?'bg-success':'bg-warning' ?>" style="width: <?= $mo_p==' - '?0:$mo_p ?>%"></div></div><span class="fw-bold ms-2"><?= $mo_p ?>%</span></td>
                                </tr>
                            <?php endforeach; ?></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="risk">
                <?php if(empty($risk_list)): ?>
                    <div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-shield-check display-1"></i><br>No students at risk.</div>
                <?php else: ?>
                    <div class="d-flex flex-column gap-2">
                        <?php foreach($risk_list as $r): $bg = ($r['level'] == 3) ? 'bg-danger text-white' : (($r['level'] == 2) ? 'bg-warning text-dark' : 'bg-info text-white'); ?>
                        <div class="card border-0 shadow-sm rounded-4 p-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div><div class="fw-bold text-dark"><?= htmlspecialchars($r['name']) ?></div><div class="small text-muted"><?= htmlspecialchars($r['class']) ?> &bull; Consecutive: <?= $r['streak'] ?></div></div>
                                <span class="badge <?= $bg ?> rounded-pill"><?= $r['type'] ?></span>
                            </div>
                            <button class="btn btn-light w-100 btn-sm rounded-pill fw-bold text-dark border" onclick='printLetter(<?= json_encode($r) ?>)'><i class="bi bi-printer me-2"></i>Print Letter</button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="tab-pane fade" id="discipline">
                <div class="card border-0 shadow-sm rounded-4 p-3">
                    <h6 class="small fw-bold text-muted mb-3 text-uppercase">Discipline Trends (<?= $year ?>)</h6>
                    <div class="chart-box" style="height: 300px;"><canvas id="discTrendChart"></canvas></div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="invalidICModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"><div class="modal-content border-0 shadow rounded-4"><div class="modal-header bg-danger text-white border-0 py-3"><h6 class="modal-title fw-bold">Invalid Data</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-0"><div class="list-group list-group-flush small"><?php foreach($invalid_by_class as $cls => $stus): ?><div class="list-group-item bg-light fw-bold text-uppercase ps-3 py-2 text-muted"><?= htmlspecialchars($cls) ?></div><?php foreach($stus as $s): ?><div class="list-group-item ps-3 d-flex justify-content-between"><span><?= htmlspecialchars($s['name']) ?></span><span class="font-monospace text-danger"><?= htmlspecialchars($s['ic']) ?></span></div><?php endforeach; ?><?php endforeach; ?></div></div></div></div></div>
    <div class="modal fade" id="classModal" tabindex="-1"><div class="modal-dialog modal-fullscreen"><div class="modal-content bg-light"><div class="modal-header bg-primary text-white border-0 py-2"><h6 class="modal-title fw-bold" id="clsTitle">Class Report</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-0"><iframe id="reportFrame" src="" style="width:100%; height:100%; border:none;"></iframe></div></div></div></div>
    
    <div id="letterArea" class="print-area d-none bg-white text-dark">
        <div class="text-center mb-5"><h3 class="fw-bold text-uppercase mb-1"><?= htmlspecialchars($s_name) ?></h3><p class="small text-muted"><?= htmlspecialchars($s_addr) ?></p><hr class="border-dark"></div>
        <p class="mb-4">Date: <?= date('d M Y') ?></p>
        <p class="mb-4">To Parents/Guardian of: <br><strong class="fs-5" id="l_name"></strong></p>
        <p><strong>SUBJECT: WARNING REGARDING STUDENT ATTENDANCE</strong></p>
        <p>This letter is to inform you that your child has been absent for a consecutive period of <strong id="l_streak"></strong> days.</p>
        <p>Total absences this year: <strong id="l_total"></strong> days.</p>
        <p>Please contact the school administration immediately to discuss this matter.</p>
        <div class="mt-5 pt-5"><p>Sincerely,<br><br><br><strong>Principal</strong><br><?= htmlspecialchars($s_name) ?></p></div>
    </div>
    
    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const commonOptions = { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } };
        document.addEventListener('DOMContentLoaded', function() {
            new Chart(document.getElementById('genderChart'), { type: 'doughnut', data: { labels: ['Male', 'Female'], datasets: [{ data: [<?= $demo_stats['male'] ?>, <?= $demo_stats['female'] ?>], backgroundColor: ['#3b82f6', '#ec4899'], borderWidth: 0 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'right' } }, cutout: '70%' } });
            new Chart(document.getElementById('religionChart'), { type: 'bar', data: { labels: <?= json_encode($rel_labels) ?>, datasets: [{ data: <?= json_encode($rel_counts) ?>, backgroundColor: '#8b5cf6', borderRadius: 5 }] }, options: { ...commonOptions, indexAxis: 'y' } });
            new Chart(document.getElementById('ageChart'), { type: 'bar', data: { labels: <?= json_encode(array_keys($demo_stats['ages'])) ?>, datasets: [{ data: <?= json_encode(array_values($demo_stats['ages'])) ?>, backgroundColor: '#f59e0b', borderRadius: 5 }] }, options: commonOptions });
            new Chart(document.getElementById('discTrendChart'), { type: 'line', data: { labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], datasets: [{ data: <?= json_encode($disc_chart_data) ?>, borderColor: '#ef4444', tension: 0.3, fill: true, backgroundColor: 'rgba(239, 68, 68, 0.1)' }] }, options: commonOptions });
        });
        const classModal = new bootstrap.Modal(document.getElementById('classModal'));
        function openClassModal(id, name) { document.getElementById('clsTitle').innerText = name; document.getElementById('reportFrame').src = 'student_class_analytics.php?class_id=' + id; classModal.show(); }
        function printLetter(s) { document.querySelectorAll('.print-area').forEach(el => el.classList.add('d-none')); const letter = document.getElementById('letterArea'); document.getElementById('l_name').innerText = s.name; document.getElementById('l_streak').innerText = s.streak; document.getElementById('l_total').innerText = s.total; letter.classList.remove('d-none'); window.print(); setTimeout(() => { letter.classList.add('d-none'); }, 1000); }
    </script>
</body>
</html>