<?php
require 'db.php';
require 'helpers.php';
require_committee();

$committeeName = (string)($_SESSION['committee_name'] ?? '');
$mysqli1->set_charset('utf8mb4');

function formatNumber($value) {
    return number_format((float)$value, 0, '.', ',');
}

function formatPercent($value) {
    return number_format((float)$value, 1, '.', ',') . '%';
}

$statistics = [
    'total_grades' => 0,
    'grades_used' => 0,
    'highest_weight' => 0,
    'lowest_weight' => 0,
    'total_subjects' => 0,
    'graded_subjects' => 0,
    'ungraded_subjects' => 0,
];
$gradeDistribution = [];
$universityPerformance = [
    'average_gpa' => 0,
    'pass_rate' => 0,
    'fail_rate' => 0,
    'students_with_grades' => 0,
    'passed_subjects' => 0,
    'failed_subjects' => 0,
    'average_subject_weight' => 0,
];
$dashboardHighlights = [
    'top_batch' => '-',
    'top_college' => '-',
    'top_subject' => '-',
    'top_subject_pass_rate' => 0,
    'top_student' => '-',
    'top_student_gpa' => 0,
    'all_passed_students' => 0,
    'passed_subjects' => 0,
    'failed_subjects' => 0,
    'average_subject_weight' => 0,
    'total_batches' => 0,
    'total_colleges' => 0,
];
$latestBatches = [];
$batchPerformance = [];
$topSubjects = [];
$bottomSubjects = [];
$topStudents = [];
$topAllPassedStudents = [];
$collegePerformance = [];

function formatDecimal($value, $decimals = 2) {
    return number_format((float)$value, $decimals, '.', ',');
}

try {
    $gradeStatsQuery = $mysqli1->prepare(
        'SELECT
            (SELECT COUNT(*) FROM tblgrade) AS total_grades,
            (SELECT COUNT(DISTINCT grade_id) FROM studentsubjects WHERE grade_id IS NOT NULL AND deleted_at IS NULL) AS grades_used,
            (SELECT MAX(weight) FROM tblgrade) AS highest_weight,
            (SELECT MIN(weight) FROM tblgrade) AS lowest_weight,
            (SELECT COUNT(*) FROM studentsubjects WHERE deleted_at IS NULL) AS total_subjects,
            (SELECT COUNT(*) FROM studentsubjects WHERE grade_id IS NOT NULL AND deleted_at IS NULL) AS graded_subjects'
    );
    if ($gradeStatsQuery) {
        $gradeStatsQuery->execute();
        $row = $gradeStatsQuery->get_result()->fetch_assoc();
        $statistics['total_grades'] = (int)($row['total_grades'] ?? 0);
        $statistics['grades_used'] = (int)($row['grades_used'] ?? 0);
        $statistics['highest_weight'] = $row['highest_weight'] !== null ? (float)$row['highest_weight'] : 0;
        $statistics['lowest_weight'] = $row['lowest_weight'] !== null ? (float)$row['lowest_weight'] : 0;
        $statistics['total_subjects'] = (int)($row['total_subjects'] ?? 0);
        $statistics['graded_subjects'] = (int)($row['graded_subjects'] ?? 0);
        $statistics['ungraded_subjects'] = max(0, $statistics['total_subjects'] - $statistics['graded_subjects']);
        $gradeStatsQuery->close();
    }

    $universityQuery = $mysqli1->prepare(
        'SELECT
            COUNT(DISTINCT ss.student_id) AS students_with_grades,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_count,
            SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) AS failed_count,
            COUNT(ss.id) AS total_records,
            AVG(ss.weight) AS average_subject_weight
        FROM studentsubjects ss
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL'
    );
    if ($universityQuery) {
        $universityQuery->execute();
        $row = $universityQuery->get_result()->fetch_assoc();
        $universityPerformance['students_with_grades'] = (int)($row['students_with_grades'] ?? 0);
        $totalPoints = (float)($row['total_weighted_points'] ?? 0);
        $totalCredits = (float)($row['total_credits'] ?? 0);
        $universityPerformance['average_gpa'] = $totalCredits > 0 ? $totalPoints / $totalCredits : 0;
        $universityPerformance['pass_rate'] = $row['total_records'] > 0 ? ((int)$row['passed_count'] / (int)$row['total_records']) * 100 : 0;
        $universityPerformance['fail_rate'] = $row['total_records'] > 0 ? ((int)$row['failed_count'] / (int)$row['total_records']) * 100 : 0;
        $universityPerformance['passed_subjects'] = (int)($row['passed_count'] ?? 0);
        $universityPerformance['failed_subjects'] = (int)($row['failed_count'] ?? 0);
        $universityPerformance['average_subject_weight'] = $row['average_subject_weight'] !== null ? (float)$row['average_subject_weight'] : 0;
        $universityQuery->close();
    }

    $batchQuery = $mysqli1->prepare(
        'SELECT b.id, b.value AS batch_name,
            COUNT(ss.id) AS total_records,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_count,
            SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) AS failed_count,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits
        FROM batches b
        LEFT JOIN studentsubjects ss ON ss.batch_id = b.id AND ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE b.deleted_at IS NULL
        GROUP BY b.id, b.value
        ORDER BY b.value DESC, b.id DESC
        LIMIT 5'
    );
    if ($batchQuery) {
        $batchQuery->execute();
        $result = $batchQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $credits = (float)($row['total_credits'] ?? 0);
            $latestBatches[] = [
                'batch_name' => $row['batch_name'] ?: 'غير محدد',
                'graded_subjects' => (int)$row['total_records'],
                'pass_rate' => $row['total_records'] > 0 ? ((int)$row['passed_count'] / (int)$row['total_records']) * 100 : 0,
                'average_gpa' => $credits > 0 ? ((float)$row['total_weighted_points'] / $credits) : 0,
            ];
        }
        $batchQuery->close();
    }

    $batchPerformanceQuery = $mysqli1->prepare(
        'SELECT b.id, b.value AS batch_name,
            COUNT(ss.id) AS total_records,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_count,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits
        FROM batches b
        LEFT JOIN studentsubjects ss ON ss.batch_id = b.id AND ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE b.deleted_at IS NULL
        GROUP BY b.id, b.value
        HAVING total_records > 0
        ORDER BY (total_weighted_points / NULLIF(total_credits,0)) DESC
        LIMIT 10'
    );
    if ($batchPerformanceQuery) {
        $batchPerformanceQuery->execute();
        $result = $batchPerformanceQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $credits = (float)($row['total_credits'] ?? 0);
            $batchPerformance[] = [
                'batch_name' => $row['batch_name'] ?: 'غير محدد',
                'average_gpa' => $credits > 0 ? ((float)$row['total_weighted_points'] / $credits) : 0,
                'pass_rate' => (int)$row['total_records'] > 0 ? ((int)$row['passed_count'] / (int)$row['total_records']) * 100 : 0,
                'graded_subjects' => (int)$row['total_records'],
            ];
        }
        $batchPerformanceQuery->close();
    }

    $subjectQuery = $mysqli1->prepare(
        'SELECT ss.subjectcode, sub.subjectnamea AS subject_name,
            COUNT(ss.id) AS attempts,
            AVG(ss.weight) AS avg_weight,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_count
        FROM studentsubjects ss
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        GROUP BY ss.subjectcode, sub.subjectnamea
        HAVING attempts > 0
        ORDER BY avg_weight DESC, passed_count DESC
        LIMIT 10'
    );
    if ($subjectQuery) {
        $subjectQuery->execute();
        $result = $subjectQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $topSubjects[] = [
                'subject_code' => $row['subjectcode'],
                'subject_name' => $row['subject_name'] ?: 'غير معروف',
                'attempts' => (int)$row['attempts'],
                'avg_weight' => (float)$row['avg_weight'],
                'pass_rate' => (int)$row['attempts'] > 0 ? ((int)$row['passed_count'] / (int)$row['attempts']) * 100 : 0,
            ];
        }
        $subjectQuery->close();
    }

    $bottomSubjectsQuery = $mysqli1->prepare(
        'SELECT ss.subjectcode, sub.subjectnamea AS subject_name,
            COUNT(ss.id) AS attempts,
            SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) AS failed_count,
            AVG(ss.weight) AS avg_weight
        FROM studentsubjects ss
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        GROUP BY ss.subjectcode, sub.subjectnamea
        HAVING attempts > 0
        ORDER BY failed_count DESC, avg_weight ASC
        LIMIT 10'
    );
    if ($bottomSubjectsQuery) {
        $bottomSubjectsQuery->execute();
        $result = $bottomSubjectsQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $bottomSubjects[] = [
                'subject_code' => $row['subjectcode'],
                'subject_name' => $row['subject_name'] ?: 'غير معروف',
                'attempts' => (int)$row['attempts'],
                'failed_count' => (int)$row['failed_count'],
                'avg_weight' => (float)$row['avg_weight'],
            ];
        }
        $bottomSubjectsQuery->close();
    }

    $studentQuery = $mysqli1->prepare(
        'SELECT ss.student_id,
            COALESCE(s.student_name, s.student_name_eng, ss.student_id) AS student_name,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits,
            COUNT(ss.id) AS total_courses,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_courses,
            SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) AS failed_courses
        FROM studentsubjects ss
        LEFT JOIN students s ON s.student_id = ss.student_id
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        GROUP BY ss.student_id
        HAVING total_credits > 0
        ORDER BY total_weighted_points / total_credits DESC
        LIMIT 10'
    );
    if ($studentQuery) {
        $studentQuery->execute();
        $result = $studentQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $credits = (float)($row['total_credits'] ?? 0);
            $topStudents[] = [
                'student_id' => $row['student_id'],
                'student_name' => $row['student_name'],
                'cgpa' => $credits > 0 ? ((float)$row['total_weighted_points'] / $credits) : 0,
                'pass_rate' => (int)$row['total_courses'] > 0 ? ((int)$row['passed_courses'] / (int)$row['total_courses']) * 100 : 0,
                'graded_courses' => (int)$row['total_courses'],
            ];
        }
        $studentQuery->close();
    }

    $allPassedQuery = $mysqli1->prepare(
        'SELECT ss.student_id,
            COALESCE(s.student_name, s.student_name_eng, ss.student_id) AS student_name,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits,
            COUNT(ss.id) AS total_courses
        FROM studentsubjects ss
        LEFT JOIN students s ON s.student_id = ss.student_id
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        GROUP BY ss.student_id
        HAVING SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) = 0
        AND total_credits > 0
        ORDER BY total_weighted_points / total_credits DESC
        LIMIT 10'
    );
    if ($allPassedQuery) {
        $allPassedQuery->execute();
        $result = $allPassedQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $credits = (float)($row['total_credits'] ?? 0);
            $topAllPassedStudents[] = [
                'student_id' => $row['student_id'],
                'student_name' => $row['student_name'],
                'cgpa' => $credits > 0 ? ((float)$row['total_weighted_points'] / $credits) : 0,
                'graded_courses' => (int)$row['total_courses'],
            ];
        }
        $allPassedQuery->close();
    }

    $allPassedCountQuery = $mysqli1->prepare(
        'SELECT COUNT(*) AS all_passed_students
         FROM (
             SELECT ss.student_id
             FROM studentsubjects ss
             LEFT JOIN tblgrade g ON ss.grade_id = g.id
             WHERE ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
             GROUP BY ss.student_id
             HAVING SUM(CASE WHEN g.grade = "F" THEN 1 ELSE 0 END) = 0
         ) AS passed_students'
    );
    if ($allPassedCountQuery) {
        $allPassedCountQuery->execute();
        $row = $allPassedCountQuery->get_result()->fetch_assoc();
        $dashboardHighlights['all_passed_students'] = (int)($row['all_passed_students'] ?? 0);
        $allPassedCountQuery->close();
    }

    $collegeQuery = $mysqli1->prepare(
        'SELECT c.id,
            c.name AS college_name,
            COUNT(DISTINCT ss.student_id) AS student_count,
            SUM(ss.weight * COALESCE(sub.credit_hours, 1)) AS total_weighted_points,
            SUM(COALESCE(sub.credit_hours, 1)) AS total_credits,
            SUM(CASE WHEN g.grade != "F" THEN 1 ELSE 0 END) AS passed_count,
            COUNT(ss.id) AS total_records
        FROM colleges c
        LEFT JOIN students s ON s.college_id = c.id
        LEFT JOIN studentsubjects ss ON ss.student_id = s.student_id AND ss.deleted_at IS NULL AND ss.grade_id IS NOT NULL
        LEFT JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN tblgrade g ON ss.grade_id = g.id
        WHERE c.deleted_at IS NULL
        GROUP BY c.id, c.name
        HAVING total_records > 0
        ORDER BY total_weighted_points / NULLIF(total_credits, 0) DESC
        LIMIT 10'
    );
    if ($collegeQuery) {
        $collegeQuery->execute();
        $result = $collegeQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $credits = (float)($row['total_credits'] ?? 0);
            $collegePerformance[] = [
                'college_name' => $row['college_name'] ?: 'غير معروف',
                'avg_gpa' => $credits > 0 ? ((float)$row['total_weighted_points'] / $credits) : 0,
                'pass_rate' => (int)$row['total_records'] > 0 ? ((int)$row['passed_count'] / (int)$row['total_records']) * 100 : 0,
                'student_count' => (int)$row['student_count'],
            ];
        }
        $collegeQuery->close();
    }

    $dashboardHighlights['top_batch'] = $batchPerformance[0]['batch_name'] ?? '-';
    $dashboardHighlights['top_college'] = $collegePerformance[0]['college_name'] ?? '-';
    $dashboardHighlights['top_subject'] = $topSubjects[0]['subject_name'] ?? '-';
    $dashboardHighlights['top_subject_pass_rate'] = $topSubjects[0]['pass_rate'] ?? 0;
    $dashboardHighlights['top_student'] = $topStudents[0]['student_name'] ?? '-';
    $dashboardHighlights['top_student_gpa'] = $topStudents[0]['cgpa'] ?? 0;
    $dashboardHighlights['passed_subjects'] = $universityPerformance['passed_subjects'];
    $dashboardHighlights['failed_subjects'] = $universityPerformance['failed_subjects'];
    $dashboardHighlights['average_subject_weight'] = $universityPerformance['average_subject_weight'];
    $dashboardHighlights['total_batches'] = count($latestBatches);
    $dashboardHighlights['total_colleges'] = count($collegePerformance);

    $distributionQuery = $mysqli1->prepare(
        'SELECT g.id, g.grade, g.garde_ar, g.xmin, g.xmax, g.weight, COUNT(ss.id) AS subjects_count
            FROM tblgrade g
            LEFT JOIN studentsubjects ss ON ss.grade_id = g.id AND ss.deleted_at IS NULL
            GROUP BY g.id
            ORDER BY g.weight DESC, g.xmax DESC'
    );
    if ($distributionQuery) {
        $distributionQuery->execute();
        $result = $distributionQuery->get_result();
        while ($row = $result->fetch_assoc()) {
            $gradeDistribution[] = [
                'id' => (int)$row['id'],
                'grade' => $row['grade'] ?? '-',
                'grade_ar' => $row['garde_ar'] ?: '-',
                'range' => ($row['xmin'] !== null && $row['xmax'] !== null) ? sprintf('%s - %s', round($row['xmin'], 0), round($row['xmax'], 0)) : 'غير محدد',
                'weight' => $row['weight'] !== null ? (float)$row['weight'] : 0,
                'subjects_count' => (int)$row['subjects_count'],
                'percentage' => $statistics['graded_subjects'] > 0 ? ((int)$row['subjects_count'] / $statistics['graded_subjects']) * 100 : 0,
                'label' => trim(($row['garde_ar'] ?: $row['grade']) . ' (' . ($row['grade'] ?: '-') . ')'),
            ];
        }
        $distributionQuery->close();
    }
} catch (Exception $e) {
    error_log('Grade statistics error: ' . $e->getMessage());
}

$pageTitle = 'إحصائيات النتائج';
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?> - <?= htmlspecialchars($committeeName, ENT_QUOTES, 'UTF-8') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        body { font-family: 'Cairo', sans-serif; background: #f5f7fb; color: #2c3e50; }
        .page-title { font-size: 2rem; font-weight: 700; margin-bottom: .25rem; }
        .page-subtitle { color: #6b7280; }
        .stat-card { border: 1px solid #e5e7eb; border-radius: 18px; background: #fff; box-shadow: 0 8px 22px rgba(15, 23, 42, 0.05); }
        .stat-card .icon { width: 52px; height: 52px; display: inline-flex; align-items: center; justify-content: center; border-radius: 16px; background: rgba(59, 130, 246, 0.12); color: #2563eb; }
        .stat-card .stat-value { font-size: 2rem; font-weight: 700; margin-top: .5rem; }
        .stat-card .stat-label { color: #6b7280; margin-top: .25rem; font-size: .88rem; }
        .card-header { background: #fff; border-bottom: 1px solid #e5e7eb; font-weight: 700; }
        .grade-badge { display: inline-flex; justify-content: center; align-items: center; padding: .45rem .9rem; border-radius: 999px; background: #eff6ff; color: #1d4ed8; font-weight: 700; font-size: .92rem; }
        .kpi-card { border-radius: 22px; background: linear-gradient(135deg, rgba(255,255,255,.95), rgba(248,250,252,.95)); box-shadow: 0 18px 40px rgba(15, 23, 42, 0.08); border: 1px solid rgba(229, 231, 235, 0.8); }
        .kpi-card .kpi-value { font-size: 2rem; font-weight: 700; margin-top: .4rem; }
        .kpi-card .kpi-meta { color: #64748b; font-size: .92rem; margin-top: .35rem; }
        .dashboard-note { border-left: 4px solid #2563eb; background: #eff6ff; padding: 1.25rem 1.3rem; border-radius: 18px; }
        .dashboard-note h5 { font-size: 1rem; margin-bottom: .65rem; }
        .dashboard-note p { color: #334155; margin-bottom: .65rem; }
        .dashboard-note ul { padding-inline-start: 1rem; color: #475569; }
        .dashboard-note li { margin-bottom: .45rem; }
        .table thead th { border-bottom: 2px solid #e5e7eb; }
        .table tbody tr:hover { background: #f8fafc; }
        .chart-card { min-height: 320px; }
        .empty-state { padding: 3rem 1rem; text-align: center; color: #475569; }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start gap-3 mb-4">
        <div>
            <h1 class="page-title"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
            <p class="page-subtitle">عرض التوزيع العام للتقديرات وحالة المقررات المصنفة.</p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="admin_dashboard.php" class="btn btn-outline-primary"><i class="fas fa-house"></i> الرئيسية</a>
            <a href="grades.php" class="btn btn-primary text-white"><i class="fas fa-graduation-cap"></i> إدارة التقديرات</a>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon"><i class="fas fa-list"></i></div>
                    <div>
                        <div class="stat-label">إجمالي التقديرات</div>
                        <div class="stat-value"><?= formatNumber($statistics['total_grades']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(16, 185, 129, 0.15); color: #047857;"><i class="fas fa-chart-line"></i></div>
                    <div>
                        <div class="stat-label">التقديرات المستخدمة</div>
                        <div class="stat-value"><?= formatNumber($statistics['grades_used']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(248, 113, 113, 0.15); color: #b91c1c;"><i class="fas fa-angle-up"></i></div>
                    <div>
                        <div class="stat-label">أعلى وزن</div>
                        <div class="stat-value"><?= $statistics['highest_weight'] !== 0 ? number_format($statistics['highest_weight'], 2) : '-' ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(59, 130, 246, 0.12); color: #1d4ed8;"><i class="fas fa-angle-down"></i></div>
                    <div>
                        <div class="stat-label">أقل وزن</div>
                        <div class="stat-value"><?= $statistics['lowest_weight'] !== 0 ? number_format($statistics['lowest_weight'], 2) : '-' ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(13, 148, 136, 0.15); color: #0f766e;"><i class="fas fa-book"></i></div>
                    <div>
                        <div class="stat-label">إجمالي المقررات</div>
                        <div class="stat-value"><?= formatNumber($statistics['total_subjects']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-4">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(251, 191, 36, 0.15); color: #b45309;"><i class="fas fa-circle-notch"></i></div>
                    <div>
                        <div class="stat-label">مواد بدون تقدير</div>
                        <div class="stat-value"><?= formatNumber($statistics['ungraded_subjects']) ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-sm-6 col-xl-3">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(16, 185, 129, 0.15); color: #047857;"><i class="fas fa-university"></i></div>
                    <div>
                        <div class="stat-label">متوسط الجامعة</div>
                        <div class="stat-value"><?= formatDecimal($universityPerformance['average_gpa'], 2) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(59, 130, 246, 0.12); color: #1d4ed8;"><i class="fas fa-check-circle"></i></div>
                    <div>
                        <div class="stat-label">نسبة النجاح</div>
                        <div class="stat-value"><?= formatPercent($universityPerformance['pass_rate']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(248, 113, 113, 0.15); color: #b91c1c;"><i class="fas fa-times-circle"></i></div>
                    <div>
                        <div class="stat-label">نسبة الرسوب</div>
                        <div class="stat-value"><?= formatPercent($universityPerformance['fail_rate']) ?></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="stat-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(14, 165, 233, 0.15); color: #0ea5e9;"><i class="fas fa-user-graduate"></i></div>
                    <div>
                        <div class="stat-label">طلاب لديهم درجات</div>
                        <div class="stat-value"><?= formatNumber($universityPerformance['students_with_grades']) ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row gy-4 mb-4">
        <div class="col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(59, 130, 246, 0.12); color: #2563eb;"><i class="fas fa-building"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatNumber($dashboardHighlights['total_colleges']) ?></div>
                        <div class="kpi-meta">كليات فعالة في التقرير</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(16, 185, 129, 0.12); color: #047857;"><i class="fas fa-layer-group"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatNumber($dashboardHighlights['total_batches']) ?></div>
                        <div class="kpi-meta">دفعات مقيّمة</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(248, 113, 113, 0.12); color: #b91c1c;"><i class="fas fa-user-check"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatNumber($dashboardHighlights['all_passed_students']) ?></div>
                        <div class="kpi-meta">طلاب نجحوا في جميع المقررات</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(251, 191, 36, 0.12); color: #b45309;"><i class="fas fa-fire"></i></div>
                    <div>
                        <div class="kpi-value"><?= htmlspecialchars($dashboardHighlights['top_subject'], ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="kpi-meta">المادة الأقوى الآن</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-sm-6 col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(16, 185, 129, 0.12); color: #047857;"><i class="fas fa-graduation-cap"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatNumber($dashboardHighlights['passed_subjects']) ?></div>
                        <div class="kpi-meta">المقررات الناجحة</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(248, 113, 113, 0.12); color: #b91c1c;"><i class="fas fa-exclamation-triangle"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatNumber($dashboardHighlights['failed_subjects']) ?></div>
                        <div class="kpi-meta">المقررات الراسبة</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(59, 130, 246, 0.12); color: #1d4ed8;"><i class="fas fa-weight-scale"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatDecimal($dashboardHighlights['average_subject_weight'], 2) ?></div>
                        <div class="kpi-meta">متوسط وزن المادة</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(14, 165, 233, 0.12); color: #0ea5e9;"><i class="fas fa-star"></i></div>
                    <div>
                        <div class="kpi-value"><?= formatDecimal($dashboardHighlights['top_student_gpa'], 2) ?></div>
                        <div class="kpi-meta">أفضل GPA طالب</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row gy-4 mb-4">
        <div class="col-xl-8">
            <div class="dashboard-note">
                <h5>ملاحظات هامة</h5>
                <p>يركز هذا التقرير على مؤشرات الأداء الأساسية لتسهيل اتخاذ القرار السريع وتحسين جودة النتائج.</p>
                <ul>
                    <li>متوسط الجامعة يمثل متوسط معدل المادة المرجح باعتماد ساعات المادة.</li>
                    <li>متوسط وزن المادة يساعدك على قياس قوة توزيع الفواصل بين التقديرات.</li>
                    <li>عدد المقررات الناجحة والراسبة يكشف نقاط الضعف في المقررات التي تحتاج تدخل.</li>
                    <li>المادة الأقوى والطالب الأفضل يعكسان أفضل الممارسات التي يمكن تعميمها.</li>
                </ul>
            </div>
        </div>
        <div class="col-xl-4">
            <div class="card h-100">
                <div class="card-header">توصيات سريعة</div>
                <div class="card-body">
                    <p>هذه الرؤى تساعدك في تحويل الأرقام إلى خطة عمل:</p>
                    <ul class="mb-0">
                        <li>ركز على المقررات ذات المتوسط المرتفع لدعم عروضها وتوسيعها.</li>
                        <li>راقب الدفعات ذات الانخفاض في نسبة النجاح وحدد الأسباب.</li>
                        <li>استخدم الكليات الأفضل أداءً كنموذج لتعزيز عمليات التعليم والتقييم.</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(59, 130, 246, 0.12); color: #1d4ed8;"><i class="fas fa-crown"></i></div>
                    <div>
                        <div class="kpi-value"><?= htmlspecialchars($dashboardHighlights['top_batch'], ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="kpi-meta">أعلى دفعة أداءً</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(16, 185, 129, 0.12); color: #047857;"><i class="fas fa-university"></i></div>
                    <div>
                        <div class="kpi-value"><?= htmlspecialchars($dashboardHighlights['top_college'], ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="kpi-meta">أفضل كلية</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="kpi-card p-4 h-100">
                <div class="d-flex align-items-center gap-3">
                    <div class="icon" style="background: rgba(248, 113, 113, 0.12); color: #b91c1c;"><i class="fas fa-user-tie"></i></div>
                    <div>
                        <div class="kpi-value"><?= htmlspecialchars($dashboardHighlights['top_student'], ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="kpi-meta">أفضل طالب</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row gy-4">
        <div class="col-lg-7">
            <div class="card chart-card p-4 h-100">
                <div class="card-header mb-3">توزيع التقديرات</div>
                <div class="card-body p-0">
                    <?php if (!empty($gradeDistribution) && $statistics['graded_subjects'] > 0): ?>
                        <canvas id="gradeDistributionChart" height="260"></canvas>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-chart-bar fa-2x"></i></p>
                            <p>لا توجد بيانات كافية لعرض الرسم البياني.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="card p-4 h-100">
                <div class="card-header mb-3">نظرة عامة سريعة</div>
                <div class="card-body">
                    <p>هذه الأرقام تعكس حالة توزيع التقديرات ضمن المقررات المسجلة حالياً.</p>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span>المقررات المصنفة</span>
                            <span class="badge bg-primary rounded-pill"><?= formatNumber($statistics['graded_subjects']) ?></span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span>النسبة من إجمالي المقررات</span>
                            <span class="badge bg-secondary rounded-pill"><?= $statistics['total_subjects'] > 0 ? formatPercent(($statistics['graded_subjects'] / $statistics['total_subjects']) * 100) : '0.0%' ?></span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span>المقررات غير المصنفة</span>
                            <span class="badge bg-warning rounded-pill"><?= formatNumber($statistics['ungraded_subjects']) ?></span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span>متوسط المقررات لكل تقدير</span>
                            <span class="badge bg-success rounded-pill"><?= $statistics['grades_used'] > 0 ? number_format($statistics['graded_subjects'] / $statistics['grades_used'], 2) : '-' ?></span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">جدول توزيع التقديرات</div>
        <div class="card-body p-0">
            <?php if (!empty($gradeDistribution)): ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th scope="col">التقدير</th>
                                <th scope="col">الاسم العربي</th>
                                <th scope="col">الوزن</th>
                                <th scope="col">نطاق الدرجات</th>
                                <th scope="col">عدد المقررات</th>
                                <th scope="col">النسبة</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($gradeDistribution as $item): ?>
                                <tr>
                                    <td><span class="grade-badge"><?= htmlspecialchars($item['grade'], ENT_QUOTES, 'UTF-8') ?></span></td>
                                    <td><?= htmlspecialchars($item['grade_ar'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= number_format($item['weight'], 2) ?></td>
                                    <td><?= htmlspecialchars($item['range'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= formatNumber($item['subjects_count']) ?></td>
                                    <td><?= formatPercent($item['percentage']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <p class="mb-2"><i class="fas fa-info-circle fa-2x"></i></p>
                    <p>لم يتم العثور على تقديرات أو بيانات مواد لعرضها.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="row gy-4 mt-4">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">آخر الدفعات</div>
                <div class="card-body p-0">
                    <?php if (!empty($latestBatches)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>الدفعة</th>
                                        <th>مواد مصنفة</th>
                                        <th>متوسط GPA</th>
                                        <th>نسبة النجاح</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($latestBatches as $batch): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($batch['batch_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatNumber($batch['graded_subjects']) ?></td>
                                            <td><?= formatDecimal($batch['average_gpa'], 2) ?></td>
                                            <td><?= formatPercent($batch['pass_rate']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-box-open fa-2x"></i></p>
                            <p>لا توجد دفعات حديثة لعرضها.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أعلى أداء دفعات</div>
                <div class="card-body p-0">
                    <?php if (!empty($batchPerformance)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>الدفعة</th>
                                        <th>متوسط GPA</th>
                                        <th>نسبة النجاح</th>
                                        <th>مواد مصنفة</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($batchPerformance as $batch): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($batch['batch_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatDecimal($batch['average_gpa'], 2) ?></td>
                                            <td><?= formatPercent($batch['pass_rate']) ?></td>
                                            <td><?= formatNumber($batch['graded_subjects']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-trophy fa-2x"></i></p>
                            <p>لا توجد بيانات أداء دفعات.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row gy-4 mt-4">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أفضل 10 مواد</div>
                <div class="card-body p-0">
                    <?php if (!empty($topSubjects)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>المادة</th>
                                        <th>المعدل</th>
                                        <th>نسبة النجاح</th>
                                        <th>عدد المحاولات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topSubjects as $subject): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($subject['subject_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatDecimal($subject['avg_weight'], 2) ?></td>
                                            <td><?= formatPercent($subject['pass_rate']) ?></td>
                                            <td><?= formatNumber($subject['attempts']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-book-open fa-2x"></i></p>
                            <p>لا توجد بيانات مواد كافية.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أكثر 10 مواد رسباً</div>
                <div class="card-body p-0">
                    <?php if (!empty($bottomSubjects)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>المادة</th>
                                        <th>عدد المحاولات</th>
                                        <th>عدد الرسوب</th>
                                        <th>متوسط الوزن</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($bottomSubjects as $subject): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($subject['subject_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatNumber($subject['attempts']) ?></td>
                                            <td><?= formatNumber($subject['failed_count']) ?></td>
                                            <td><?= formatDecimal($subject['avg_weight'], 2) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-book-dead fa-2x"></i></p>
                            <p>لا توجد بيانات مواد راسبة لعرضها.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أفضل 10 طلاب</div>
                <div class="card-body p-0">
                    <?php if (!empty($topStudents)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>الطالب</th>
                                        <th>GPA</th>
                                        <th>نسبة النجاح</th>
                                        <th>المقررات المصنفة</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topStudents as $student): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatDecimal($student['cgpa'], 2) ?></td>
                                            <td><?= formatPercent($student['pass_rate']) ?></td>
                                            <td><?= formatNumber($student['graded_courses']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-user-graduate fa-2x"></i></p>
                            <p>لا توجد بيانات أداء طلاب.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row gy-4 mt-4">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أفضل الطلاب الذين نجحوا في جميع المقررات</div>
                <div class="card-body p-0">
                    <?php if (!empty($topAllPassedStudents)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>الطالب</th>
                                        <th>GPA</th>
                                        <th>المقررات المصنفة</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topAllPassedStudents as $student): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatDecimal($student['cgpa'], 2) ?></td>
                                            <td><?= formatNumber($student['graded_courses']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-award fa-2x"></i></p>
                            <p>لا توجد طلاب استوفوا شرط النجاح الكامل.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header">أفضل 10 كليات</div>
                <div class="card-body p-0">
                    <?php if (!empty($collegePerformance)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>الكلية</th>
                                        <th>متوسط GPA</th>
                                        <th>نسبة النجاح</th>
                                        <th>عدد الطلاب</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($collegePerformance as $college): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($college['college_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                            <td><?= formatDecimal($college['avg_gpa'], 2) ?></td>
                                            <td><?= formatPercent($college['pass_rate']) ?></td>
                                            <td><?= formatNumber($college['student_count']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <p class="mb-2"><i class="fas fa-building fa-2x"></i></p>
                            <p>لا توجد بيانات كليات لعرضها.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const distributionLabels = <?= json_encode(array_column($gradeDistribution, 'label'), JSON_UNESCAPED_UNICODE) ?>;
    const distributionData = <?= json_encode(array_map(fn($item) => $item['subjects_count'], $gradeDistribution), JSON_UNESCAPED_UNICODE) ?>;

    if (distributionLabels.length > 0 && document.getElementById('gradeDistributionChart')) {
        const ctx = document.getElementById('gradeDistributionChart');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: distributionLabels,
                datasets: [{
                    label: 'عدد المقررات',
                    data: distributionData,
                    backgroundColor: 'rgba(59, 130, 246, 0.75)',
                    borderColor: 'rgba(37, 99, 235, 0.9)',
                    borderWidth: 1,
                    borderRadius: 12,
                    maxBarThickness: 48,
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: { grid: { display: false }, ticks: { color: '#475569' } },
                    y: { beginAtZero: true, ticks: { color: '#475569', precision: 0 }, grid: { color: 'rgba(148, 163, 184, 0.2)' } }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: { mode: 'index', intersect: false }
                }
            }
        });
    }
</script>
</body>
</html>
