<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

$totalStudents = tableExists($pdo, 'students') ? safeCount($pdo, "SELECT COUNT(*) FROM students") : 0;
$totalCourses = tableExists($pdo, 'core_courses') ? safeCount($pdo, "SELECT COUNT(*) FROM core_courses") : 0;
$totalTeachers = tableExists($pdo, 'core_teachers') ? safeCount($pdo, "SELECT COUNT(*) FROM core_teachers") : 0;
$totalExams = tableExists($pdo, 'core_exams') ? safeCount($pdo, "SELECT COUNT(*) FROM core_exams") : 0;

$totalGrades = tableExists($pdo, 'core_final_grades') ? safeCount($pdo, "SELECT COUNT(*) FROM core_final_grades") : 0;
$passedStudents = tableExists($pdo, 'core_final_grades') ? safeCount($pdo, "SELECT COUNT(*) FROM core_final_grades WHERE final_percentage >= 60") : 0;
$failedStudents = max(0, $totalGrades - $passedStudents);
$passRate = $totalGrades > 0 ? round(($passedStudents / $totalGrades) * 100, 2) : 0;

$attendanceTotal = tableExists($pdo, 'core_attendance') ? safeCount($pdo, "SELECT COUNT(*) FROM core_attendance") : 0;
$attendancePresent = tableExists($pdo, 'core_attendance') ? safeCount($pdo, "SELECT COUNT(*) FROM core_attendance WHERE status='present'") : 0;
$attendanceRate = $attendanceTotal > 0 ? round(($attendancePresent / $attendanceTotal) * 100, 2) : 0;

$levelStats = [];

if (tableExists($pdo, 'students')) {
    $levelStats = $pdo->query("
        SELECT final_level, COUNT(*) AS total
        FROM students
        GROUP BY final_level
        ORDER BY total DESC
    ")->fetchAll();
}

$courseStats = [];

if (tableExists($pdo, 'core_courses')) {
    $courseStats = $pdo->query("
        SELECT c.title, COUNT(cs.id) AS total_students
        FROM core_courses c
        LEFT JOIN core_course_students cs ON cs.course_id = c.id
        GROUP BY c.id
        ORDER BY total_students DESC
        LIMIT 10
    ")->fetchAll();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Analytics</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:#f1f5f9;color:#0f172a}
.page{padding:34px}
.topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:30px}
.page-title{font-size:42px;font-weight:900}
.back-btn{background:#dbeafe;color:#1d4ed8;text-decoration:none;padding:14px 20px;border-radius:18px;font-weight:900}
.hero{background:linear-gradient(135deg,#7c3aed,#2563eb);color:#fff;border-radius:34px;padding:36px;margin-bottom:26px}
.hero h2{font-size:40px;font-weight:900;margin-bottom:12px}
.hero p{color:#ede9fe;line-height:2}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:20px;margin-bottom:26px}
.stat{background:#fff;border-radius:28px;padding:26px;border:1px solid #e2e8f0;box-shadow:0 18px 45px rgba(15,23,42,.05)}
.stat span{display:block;color:#64748b;font-weight:900;font-size:13px;margin-bottom:12px}
.stat h3{font-size:38px;font-weight:900;color:#2563eb}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:26px}
.card{background:#fff;border-radius:34px;padding:30px;border:1px solid #e2e8f0;box-shadow:0 18px 45px rgba(15,23,42,.05)}
.card h2{font-size:30px;margin-bottom:22px;font-weight:900}
.bar-item{margin-bottom:20px}
.bar-top{display:flex;justify-content:space-between;margin-bottom:10px;font-weight:800}
.bar{height:16px;background:#e2e8f0;border-radius:999px;overflow:hidden}
.fill{height:100%;background:linear-gradient(135deg,#2563eb,#7c3aed);border-radius:999px}
.empty{color:#64748b;text-align:center;padding:40px}
@media(max-width:1000px){.grid{grid-template-columns:1fr}}
</style>
</head>

<body>

<div class="page">

    <div class="topbar">
        <h1 class="page-title">Analytics</h1>
        <a href="dashboard.php" class="back-btn">← Dashboard</a>
    </div>

    <div class="hero">
        <h2>SMI Gateway Analytics</h2>
        <p>
            Monitor students, courses, teachers, attendance rate,
            pass rate, and course activity in one professional dashboard.
        </p>
    </div>

    <div class="stats">

        <div class="stat">
            <span>Total Students</span>
            <h3><?php echo $totalStudents; ?></h3>
        </div>

        <div class="stat">
            <span>Total Teachers</span>
            <h3><?php echo $totalTeachers; ?></h3>
        </div>

        <div class="stat">
            <span>Total Courses</span>
            <h3><?php echo $totalCourses; ?></h3>
        </div>

        <div class="stat">
            <span>Total Exams</span>
            <h3><?php echo $totalExams; ?></h3>
        </div>

        <div class="stat">
            <span>Attendance Rate</span>
            <h3><?php echo $attendanceRate; ?>%</h3>
        </div>

        <div class="stat">
            <span>Pass Rate</span>
            <h3><?php echo $passRate; ?>%</h3>
        </div>

        <div class="stat">
            <span>Passed Students</span>
            <h3><?php echo $passedStudents; ?></h3>
        </div>

        <div class="stat">
            <span>Failed Students</span>
            <h3><?php echo $failedStudents; ?></h3>
        </div>

    </div>

    <div class="grid">

        <div class="card">
            <h2>Students by Level</h2>

            <?php if($levelStats): ?>
                <?php foreach($levelStats as $row): ?>
                    <?php
                    $total = (int)$row['total'];
                    $percentage = $totalStudents > 0 ? round(($total / $totalStudents) * 100, 2) : 0;
                    ?>
                    <div class="bar-item">
                        <div class="bar-top">
                            <span><?php echo e(ucfirst($row['final_level'] ?? 'Unknown')); ?></span>
                            <span><?php echo $total; ?> students</span>
                        </div>
                        <div class="bar">
                            <div class="fill" style="width:<?php echo $percentage; ?>%;"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty">No level data.</div>
            <?php endif; ?>
        </div>

        <div class="card">
            <h2>Courses Activity</h2>

            <?php if($courseStats): ?>
                <?php foreach($courseStats as $row): ?>
                    <?php
                    $total = (int)$row['total_students'];
                    $percentage = $totalStudents > 0 ? round(($total / $totalStudents) * 100, 2) : 0;
                    ?>
                    <div class="bar-item">
                        <div class="bar-top">
                            <span><?php echo e($row['title']); ?></span>
                            <span><?php echo $total; ?> students</span>
                        </div>
                        <div class="bar">
                            <div class="fill" style="width:<?php echo $percentage; ?>%;"></div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty">No course activity data.</div>
            <?php endif; ?>
        </div>

    </div>

</div>

</body>
</html>