<?php
session_start();
// error_reporting(E_ALL); // Uncomment for debugging during development
// ini_set('display_errors', 1); // Uncomment for debugging during development

// Check if user is logged in and is a student
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    header('Location: ../auth/login.php'); // Redirect to login page, corrected path from root
    exit;
}

// Include necessary files (paths relative to student/index.php)
include_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../config/database.php';

$student_id = $_SESSION['user_id'];
$username = htmlspecialchars($_SESSION['username'] ?? ''); // Get username from session for welcome message
$full_name = htmlspecialchars($_SESSION['first_name'] ?? '') . ' ' . htmlspecialchars($_SESSION['last_name'] ?? ''); // Get full name for welcome

// Initialize data arrays for academic summary and overall school averages
$academic_summary = [
    'avg_mark' => 0,
    'attendance_percentage' => 0,
    'total_activity_points' => 0,
    'attended_classes' => 0,
    'total_classes' => 0
];
$overall_school_averages = [
    'avg_mark' => 0,
    'attendance_percentage' => 0,
    'total_activity_points' => 0
];
$notifications = [];
$student_marks = [];
$leaderboard_data = []; // This will hold the comprehensive leaderboard data

$message = '';
$message_type = '';

$conn = null;

try {
    // Attempt to establish a database connection
    $conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

    // Check for connection errors. If connection fails, throw an exception.
    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }

    // --- Fetch Student's Individual Averages (Needed for AI report and Attendance Card) ---

    // Student Average Mark
    $query_avg_mark_student = "
        SELECT AVG(mark_value) AS avg_mark
        FROM marks
        WHERE student_id = ?
    ";
    $stmt_avg_mark_student = $conn->prepare($query_avg_mark_student);
    if ($stmt_avg_mark_student) {
        $stmt_avg_mark_student->bind_param("i", $student_id);
        $stmt_avg_mark_student->execute();
        $result_avg_mark_student = $stmt_avg_mark_student->get_result();
        if ($row = $result_avg_mark_student->fetch_assoc()) {
            $academic_summary['avg_mark'] = $row['avg_mark'] !== null ? (float)$row['avg_mark'] : 0;
        }
        $stmt_avg_mark_student->close();
    } else {
        error_log("Failed to prepare student average mark statement: " . $conn->error);
    }

    // Student Attendance Percentage (and attended/total classes)
    $query_attendance_student = "
        SELECT
            COUNT(*) AS total_records,
            SUM(CASE WHEN status = 'Present' THEN 1 ELSE 0 END) AS present_records
        FROM attendance
        WHERE student_id = ?
    ";
    $stmt_attendance_student = $conn->prepare($query_attendance_student);
    if ($stmt_attendance_student) {
        $stmt_attendance_student->bind_param("i", $student_id);
        $stmt_attendance_student->execute();
        $result_attendance_student = $stmt_attendance_student->get_result();
        if ($row = $result_attendance_student->fetch_assoc()) {
            $total_records = $row['total_records'];
            $present_records = $row['present_records'];
            $academic_summary['attended_classes'] = $present_records;
            $academic_summary['total_classes'] = $total_records;

            if ($total_records > 0) {
                $academic_summary['attendance_percentage'] = ($present_records / $total_records) * 100;
            } else {
                $academic_summary['attendance_percentage'] = 0;
            }
        }
        $stmt_attendance_student->close();
    } else {
        error_log("Failed to prepare student attendance statement: " . $conn->error);
    }

    // Student Total Activity Points
    $query_activity_student = "
        SELECT SUM(activity_points) AS total_activity_points
        FROM activities
        WHERE student_id = ?
    ";
    $stmt_activity_student = $conn->prepare($query_activity_student);
    if ($stmt_activity_student) {
        $stmt_activity_student->bind_param("i", $student_id);
        $stmt_activity_student->execute();
        $result_activity_student = $stmt_activity_student->get_result();
        if ($row = $result_activity_student->fetch_assoc()) {
            $academic_summary['total_activity_points'] = $row['total_activity_points'] !== null ? (float)$row['total_activity_points'] : 0;
        }
        $stmt_activity_student->close();
    } else {
        error_log("Failed to prepare student activity statement: " . $conn->error);
    }

    // --- Fetch Overall School Averages (Needed for AI report and dashboard chart) ---

    // Overall School Average Mark
    $query_avg_mark_school = "
        SELECT AVG(m.mark_value) AS avg_mark
        FROM marks m
        JOIN users u ON m.student_id = u.id
        WHERE u.user_type = 'student'
    ";
    $stmt_avg_mark_school = $conn->prepare($query_avg_mark_school);
    if ($stmt_avg_mark_school) {
        $stmt_avg_mark_school->execute();
        $result_avg_mark_school = $stmt_avg_mark_school->get_result();
        if ($row = $result_avg_mark_school->fetch_assoc()) {
            $overall_school_averages['avg_mark'] = $row['avg_mark'] !== null ? (float)$row['avg_mark'] : 0;
        }
        $stmt_avg_mark_school->close();
    } else {
        error_log("Failed to prepare school average mark statement: " . $conn->error);
    }

    // Overall School Attendance Percentage
    $query_attendance_school = "
        SELECT
            SUM(CASE WHEN a.status = 'Present' THEN 1 ELSE 0 END) AS total_present,
            COUNT(a.attendance_id) AS total_attendance_records
        FROM attendance a
        JOIN users u ON a.student_id = u.id
        WHERE u.user_type = 'student'
    ";
    $stmt_attendance_school = $conn->prepare($query_attendance_school);
    if ($stmt_attendance_school) {
        $stmt_attendance_school->execute();
        $result_attendance_school = $stmt_attendance_school->get_result();
        if ($row = $result_attendance_school->fetch_assoc()) {
            if ($row['total_attendance_records'] > 0) {
                $school_percentage = ($row['total_present'] / $row['total_attendance_records']) * 100;
                $overall_school_averages['attendance_percentage'] = $school_percentage;
            } else {
                $overall_school_averages['attendance_percentage'] = 0;
            }
        }
        $stmt_attendance_school->close();
    } else {
        error_log("Failed to prepare school attendance statement: " . $conn->error);
    }

    // Overall School Average Activity Points per Student
    $query_activity_school = "
        SELECT AVG(total_points_per_student.sum_activity_points) AS avg_school_activity_points
        FROM (
            SELECT SUM(a.activity_points) AS sum_activity_points
            FROM activities a
            JOIN users u ON a.student_id = u.id
            WHERE u.user_type = 'student'
            GROUP BY u.id
        ) AS total_points_per_student
    ";
    $stmt_activity_school = $conn->prepare($query_activity_school);
    if ($stmt_activity_school) {
        $stmt_activity_school->execute();
        $result_activity_school = $stmt_activity_school->get_result();
        if ($row = $result_activity_school->fetch_assoc()) {
            $overall_school_averages['total_activity_points'] = $row['avg_school_activity_points'] !== null ? (float)$row['avg_school_activity_points'] : 0;
        }
        $stmt_activity_school->close();
    } else {
        error_log("Failed to prepare school activity statement: " . $conn->error);
    }

    // --- Fetch Student's Recent Marks (for "Your Marks" card) ---
    // FIXED: Removed 'm.max_mark_value' as it caused an error. Assuming max_mark_value is 100 for display.
    $query_student_marks = "
        SELECT s.subject_name, m.mark_value
        FROM marks m
        JOIN subjects s ON m.subject_id = s.subject_id
        WHERE m.student_id = ?
        ORDER BY m.date_recorded DESC, s.subject_name ASC
        LIMIT 4
    ";
    $stmt_student_marks = $conn->prepare($query_student_marks);
    if ($stmt_student_marks) {
        $stmt_student_marks->bind_param("i", $student_id);
        $stmt_student_marks->execute();
        $result_student_marks = $stmt_student_marks->get_result();
        $student_marks = $result_student_marks->fetch_all(MYSQLI_ASSOC);
        $stmt_student_marks->close();
    } else {
        error_log("Failed to prepare student marks statement: " . $conn->error);
    }

    // --- Leaderboard Data Fetching (Full Logic from Leaderboard Page) ---
    // Fixed period for monthly display
    $selected_period = 'monthly';
    $selected_subject_id = ''; // Still all subjects by default

    // Define attendance point values for calculation
    $attendance_points_map = [
        'present' => 5,
        'late' => 3,
        'excused' => 2,
        'absent' => 0,
    ];

    // Define weights for each component when calculating total score
    $mark_weight = 10;
    $attendance_weight = 10;
    $activity_weight = 1;

    // Determine date range based on fixed period (monthly)
    $start_date = date('Y-m-01'); // Start of the current month
    $end_date = date('Y-m-d'); // Current date
    $period_title = 'Oylik'; // Fixed title for Uzbek

    // Main SQL query to fetch student data, average marks, attendance scores, and activity points
    $query_leaderboard_full = "
        SELECT
            u.id AS student_id,
            u.first_name,
            u.last_name,
            COALESCE(AVG(m.mark_value), 0) AS avg_mark,
            -- Calculate total attendance score points within the period for the student
            COALESCE(SUM(CASE a.status
                WHEN 'Present' THEN ?
                WHEN 'Late' THEN ?
                WHEN 'Excused' THEN ?
                WHEN 'Absent' THEN ?
                ELSE 0
            END), 0) AS total_attendance_score_points,
            -- Count unique attendance records to get a divisor for average attendance score
            COUNT(DISTINCT a.attendance_id) AS attendance_records_count,
            COALESCE(SUM(act.activity_points), 0) AS total_activity_points
        FROM
            users u
        LEFT JOIN
            marks m ON u.id = m.student_id AND m.date_recorded BETWEEN ? AND ?
            " . (!empty($selected_subject_id) ? "AND m.subject_id = ?" : "") . "
        LEFT JOIN
            attendance a ON u.id = a.student_id AND a.date_recorded BETWEEN ? AND ?
            " . (!empty($selected_subject_id) ? "AND a.subject_id = ?" : "") . "
        LEFT JOIN
            activities act ON u.id = act.student_id AND act.date_recorded BETWEEN ? AND ?
            " . (!empty($selected_subject_id) ? "AND act.subject_id = ?" : "") . "
        WHERE
            u.user_type = 'student'
        GROUP BY
            u.id, u.first_name, u.last_name
        ORDER BY
            ( (COALESCE(AVG(m.mark_value), 0) * ?) +
              (COALESCE(SUM(CASE a.status
                    WHEN 'Present' THEN ?
                    WHEN 'Late' THEN ?
                    WHEN 'Excused' THEN ?
                    WHEN 'Absent' THEN ?
                    ELSE 0
                END), 0) / GREATEST(1, COUNT(DISTINCT a.attendance_id)) * ?) +
              (COALESCE(SUM(act.activity_points), 0) * ?)
            ) DESC, u.first_name ASC
    ";

    $stmt_leaderboard_full = $conn->prepare($query_leaderboard_full);

    // Dynamically build bind parameters array and type string for leaderboard query
    $bind_types_leaderboard = "iiii"; // For attendance points (4 of them)
    $bind_params_leaderboard = [
        $attendance_points_map['present'],
        $attendance_points_map['late'],
        $attendance_points_map['excused'],
        $attendance_points_map['absent']
    ];

    // Mark dates and optional subject ID
    $bind_types_leaderboard .= "ss";
    $bind_params_leaderboard[] = $start_date;
    $bind_params_leaderboard[] = $end_date;
    if (!empty($selected_subject_id)) {
        $bind_types_leaderboard .= "i";
        $bind_params_leaderboard[] = (int)$selected_subject_id;
    }

    // Attendance dates and optional subject ID
    $bind_types_leaderboard .= "ss";
    $bind_params_leaderboard[] = $start_date;
    $bind_params_leaderboard[] = $end_date;
    if (!empty($selected_subject_id)) {
        $bind_types_leaderboard .= "i";
        $bind_params_leaderboard[] = (int)$selected_subject_id;
    }

    // Activity dates and optional subject ID
    $bind_types_leaderboard .= "ss";
    $bind_params_leaderboard[] = $start_date;
    $bind_params_leaderboard[] = $end_date;
    if (!empty($selected_subject_id)) {
        $bind_types_leaderboard .= "i";
        $bind_params_leaderboard[] = (int)$selected_subject_id;
    }

    // Weights and attendance points for ORDER BY clause
    $bind_types_leaderboard .= "diiiiid"; // Mark weight (d), 4 attendance points (i), attendance weight (d), activity weight (d)
    $bind_params_leaderboard[] = $mark_weight;
    $bind_params_leaderboard[] = $attendance_points_map['present'];
    $bind_params_leaderboard[] = $attendance_points_map['late'];
    $bind_params_leaderboard[] = $attendance_points_map['excused'];
    $bind_params_leaderboard[] = $attendance_points_map['absent'];
    $bind_params_leaderboard[] = $attendance_weight;
    $bind_params_leaderboard[] = $activity_weight;

    // Use call_user_func_array for dynamic bind_param arguments
    $ref_bind_params_leaderboard = [];
    foreach ($bind_params_leaderboard as $key => $value) {
        $ref_bind_params_leaderboard[$key] = &$bind_params_leaderboard[$key];
    }
    call_user_func_array([$stmt_leaderboard_full, 'bind_param'], array_merge([$bind_types_leaderboard], $ref_bind_params_leaderboard));

    $stmt_leaderboard_full->execute();
    $result_leaderboard_full = $stmt_leaderboard_full->get_result();

    $rank = 0;
    $prev_total_score = null;
    $temp_leaderboard_data = []; // Use a temp array to calculate rank before final assignment
    while ($row = $result_leaderboard_full->fetch_assoc()) {
        // Calculate average attendance score for display (if attendance_records_count is 0, default to 0 to avoid division by zero)
        $avg_attendance_score_for_display = $row['attendance_records_count'] > 0 ?
            $row['total_attendance_score_points'] / $row['attendance_records_count'] : 0;

        // Recalculate total score in PHP to ensure accurate ranking (especially with ties)
        // This must match the ORDER BY clause logic for consistent ranking
        $total_score_for_ranking =
            ($row['avg_mark'] * $mark_weight) +
            ($avg_attendance_score_for_display * $attendance_weight) +
            ($row['total_activity_points'] * $activity_weight);

        $row['avg_attendance_score_display'] = round($avg_attendance_score_for_display, 0);
        $row['total_score_for_ranking'] = $total_score_for_ranking;
        $temp_leaderboard_data[] = $row;
    }

    // Sort the temporary data by the calculated total score for ranking to correctly assign ranks
    usort($temp_leaderboard_data, function($a, $b) {
        if ($a['total_score_for_ranking'] == $b['total_score_for_ranking']) {
            return 0;
        }
        return ($a['total_score_for_ranking'] > $b['total_score_for_ranking']) ? -1 : 1;
    });

    foreach ($temp_leaderboard_data as $row) {
        // Assign rank (handle ties: students with same score get the same rank)
        if ($row['total_score_for_ranking'] !== $prev_total_score) {
            $rank++;
        }
        $prev_total_score = $row['total_score_for_ranking'];

        $row['total_score_display'] = round($row['total_score_for_ranking'], 0); // Round to whole number for display
        $row['rank'] = $rank;
        $leaderboard_data[] = $row;
    }
    $stmt_leaderboard_full->close();

    // --- Existing Notification Fetch Logic ---
    $stmt_notifications = $conn->prepare("SELECT n.message, n.send_date, u.first_name, u.last_name FROM notifications n JOIN users u ON n.sender_id = u.id ORDER BY n.send_date DESC LIMIT 5");
    if ($stmt_notifications) {
        $stmt_notifications->execute();
        $result_notifications = $stmt_notifications->get_result();
        $notifications = $result_notifications->fetch_all(MYSQLI_ASSOC);
        $stmt_notifications->close();
    } else {
        error_log("Failed to prepare notifications statement in student/index.php: " . $conn->error);
        throw new Exception("SQL query preparation failed for notifications. Please check server logs for details.");
    }
    // --- End Existing Notification Fetch Logic ---

} catch (Exception $e) {
    error_log("Error in student/index.php database operations: " . $e->getMessage());
    $message = "Ma'lumotlar yuklanmadi: " . $e->getMessage(); // Translated message
    $message_type = 'danger';
    $leaderboard_data = []; // Ensure data is empty if an error occurs
} finally {
    if (isset($conn) && is_object($conn) && method_exists($conn, 'close')) {
        $conn->close();
    }
}

// --- Calculate Combined Scores for the single bar chart (using academic_summary and overall_school_averages) ---
// For a meaningful combined score, let's normalize Activity Points to a 0-100 scale
$max_activity_points_for_normalization = 500; // Define a reasonable maximum for activity points

$student_normalized_activity = ($academic_summary['total_activity_points'] / $max_activity_points_for_normalization) * 100;
$student_normalized_activity = min(100, max(0, $student_normalized_activity)); // Cap between 0 and 100

$school_normalized_activity = ($overall_school_averages['total_activity_points'] / $max_activity_points_for_normalization) * 100;
$school_normalized_activity = min(100, max(0, $school_normalized_activity)); // Cap between 0 and 100

// Now calculate the average of the three normalized metrics (Marks, Attendance, Normalized Activity)
$student_combined_score = ($academic_summary['avg_mark'] + $academic_summary['attendance_percentage'] + $student_normalized_activity) / 3;
$school_combined_score = ($overall_school_averages['avg_mark'] + $overall_school_averages['attendance_percentage'] + $school_normalized_activity) / 3;

// Ensure scores are formatted nicely for display (optional, but good for labels if displayed)
$student_combined_score_formatted = number_format($student_combined_score, 0);
$school_combined_score_formatted = number_format($school_combined_score, 0);


// Prepare data for Chart.js for the SINGLE BAR
$chart_data = [
    'labels' => ['Umumiy ko\'rsatkich balli (normallashtirilgan)'], // Translated label
    'datasets' => [
        [
            'label' => 'Sizning balingiz', // Translated label
            'backgroundColor' => 'rgba(75, 192, 192, 0.6)',
            'borderColor' => 'rgba(75, 192, 192, 1)',
            'borderWidth' => 1,
            'data' => [$student_combined_score],
            'barThickness' => 60,
            'maxBarThickness' => 80
        ],
        [
            'label' => 'Maktabning umumiy o\'rtacha ko\'rsatkichi', // Translated label
            'backgroundColor' => 'rgba(153, 102, 255, 0.6)',
            'borderColor' => 'rgba(153, 102, 255, 1)',
            'borderWidth' => 1,
            'data' => [$school_combined_score],
            'barThickness' => 60,
            'maxBarThickness' => 80
        ]
    ]
];
?>

<!-- Your inc/header.php opens: <div class="wrapper"> <aside class="sidebar"> ... </aside> <main class="content-area"> <header class="top-bar"> ... </header> <div class="container"> -->

<!-- Your content for student/index.php starts here, inside the <div class="container"> opened by header.php -->
<main class="content-area">
    <div class="top-bar">
        <div class="user-info">
            Salom, **<?php echo $username; ?>** (Talaba) <!-- Dynamically display username -->
            <!-- Desktop Logout button -->
            <a href="../auth/logout.php" class="btn btn-danger ml-auto d-none d-md-inline-block">Chiqish</a>
            <!-- Mobile Logout button (visible only on small screens) -->
            <a href="../auth/logout.php" class="btn btn-danger mobile-admin-logout d-md-none">Chiqish</a>
        </div>
    </div>

    <div class="container dashboard-container">
        <h1 class="dashboard-welcome">Xush kelibsiz, <?php echo $full_name; ?>!</h1>
        <p class="dashboard-subheading">Bu sizning bu oygi akademik hisobotingiz.</p>

        <?php if ($message): // Display any informational or error messages ?>
            <div class="alert alert-<?php echo $message_type; ?> mt-3" role="alert">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- AI-Powered Progress Report -->
        <div class="card ai-report-card mb-4">
            <div class="card-body">
                <h5 class="card-title">Sizning Sun'iy Intellektga asoslangan taraqqiyot hisobotingiz</h5>
                <p class="card-text">
                    Ajoyib ish, **<?php echo htmlspecialchars($_SESSION['first_name'] ?? 'Talaba'); ?>**! Sizning joriy o'zlashtirish ko'rsatkichingiz **<?php echo number_format($academic_summary['avg_mark'], 2); ?>** ga teng, bu
                    <?php
                    $relation = "";
                    if ($academic_summary['avg_mark'] > $overall_school_averages['avg_mark']) {
                        $relation = "yuqori";
                    } elseif ($academic_summary['avg_mark'] < $overall_school_averages['avg_mark']) {
                        $relation = "past";
                    } else {
                        $relation = "teng";
                    }
                    echo $relation; // Echo the relation here
                    ?>
                    maktab o'rtacha ko'rsatkichi **<?php echo number_format($overall_school_averages['avg_mark'], 2); ?>** dan! Sizning davomatingiz **<?php echo number_format($academic_summary['attendance_percentage'], 0); ?>%** ga doimiy ravishda yaxshilandi, bu o'tgan oydagi A% dan yuqori. A'lo ishlaringizni davom eting! Agar siz yaxshilashda davom etsangiz, yanada yuqori ball olishingiz mumkin!
                </p>
            </div>
        </div>

        <div class="row dashboard-widgets-row">
            <!-- Your Marks Card -->
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="card dashboard-widget">
                    <div class="card-header">
                        <i class="fas fa-graduation-cap"></i> Sizning Baholaringiz
                    </div>
                    <div class="card-body">
                        <?php if (!empty($student_marks)): ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach ($student_marks as $mark): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <?php echo htmlspecialchars($mark['subject_name']); ?>
                                        <span class="badge badge-primary"><?php echo htmlspecialchars($mark['mark_value'] ?? 'N/A'); ?>/100</span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p class="text-muted text-center">Yaqin orada baholar mavjud emas.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Attendance Card -->
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="card dashboard-widget">
                    <div class="card-header">
                        <i class="fas fa-calendar-check"></i> Davomat
                    </div>
                    <div class="card-body text-center">
                        <div class="attendance-chart-container mb-3"
                             style="background: conic-gradient(#28a745 <?php echo $academic_summary['attendance_percentage']; ?>%, #e0e0e0 <?php echo $academic_summary['attendance_percentage']; ?>%);">
                            <div class="attendance-circle">
                                <span class="attendance-percentage"><?php echo number_format($academic_summary['attendance_percentage'], 0); ?>%</span>
                            </div>
                        </div>
                        <p class="mb-0">Jami **<?php echo $academic_summary['total_classes']; ?>** ta darsdan **<?php echo $academic_summary['attended_classes']; ?>** tasida qatnashdingiz</p>
                    </div>
                </div>
            </div>

            <!-- Leaderboard Card (SIMPLIFIED TO MATCH SCREENSHOT DESIGN) -->
            <div class="col-lg-4 col-md-12 mb-4">
                <div class="card dashboard-widget">
                    <div class="card-header">
                        <i class="fas fa-trophy"></i> Eng yaxshi talabalar - <?php echo $period_title; ?> reytingi
                    </div>
                    <div class="card-body">
                        <?php if (!empty($leaderboard_data)): ?>
                            <ul class="list-group list-group-flush leaderboard-list">
                                <?php foreach ($leaderboard_data as $entry): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center
                                        <?php
                                        // Apply top-rank specific colors for the first 3
                                        if ($entry['rank'] == 1) { echo 'top-1'; }
                                        elseif ($entry['rank'] == 2) { echo 'top-2'; }
                                        elseif ($entry['rank'] == 3) { echo 'top-3'; }
                                        // Highlight current logged-in user
                                        if ($entry['student_id'] === $student_id) { echo ' current-user-rank'; }
                                        ?>
                                        ">
                                        <div class="d-flex align-items-center">
                                            <span class="leaderboard-rank"><?php echo htmlspecialchars($entry['rank']); ?>.</span>
                                            <?php if ($entry['rank'] == 1): ?><span class="rank-medal ml-1">🥇</span>
                                            <?php elseif ($entry['rank'] == 2): ?><span class="rank-medal ml-1">🥈</span>
                                            <?php elseif ($entry['rank'] == 3): ?><span class="rank-medal ml-1">🥉</span>
                                            <?php endif; ?>
                                            <span class="leaderboard-name ml-2"><?php echo htmlspecialchars($entry['first_name'] . ' ' . $entry['last_name']); ?></span>
                                        </div>
                                        <span class="badge badge-success"><?php echo number_format($entry['total_score_display'], 0); ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <div class="alert alert-info mt-3 text-center">
                                Bu oy uchun reyting ma'lumotlari mavjud emas.<br>Iltimos, talabalarning shu davr uchun baholari, davomati yoki faoliyatlari qayd etilganligiga ishonch hosil qiling.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Notifications Card (MOVED HERE: after Marks and Attendance) -->
            <div class="col-12 mb-4">
                <div class="card dashboard-widget">
                    <div class="card-header">
                        <i class="fas fa-bell"></i> E'lonlar va Bildirishnomalar
                    </div>
                    <div class="card-body">
                        <?php if (!empty($notifications)): ?>
                            <ul class="list-group list-group-flush notification-list">
                                <?php foreach ($notifications as $notification): ?>
                                    <li class="list-group-item notification-item">
                                        <div class="notification-message">
                                            <strong><?php echo htmlspecialchars($notification['first_name'] . ' ' . $notification['last_name']); ?>:</strong>
                                            <?php echo htmlspecialchars($notification['message']); ?>
                                        </div>
                                        <small class="text-muted notification-date">Yuborilgan sana: <?php echo date('Y-m-d H:i', strtotime($notification['send_date'])); ?></small>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p class="text-muted no-notifications">Hozircha yangi e'lonlar yo'q.</p>
                        <?php endif; ?>
                        <a href="notifications/index.php" class="btn btn-link mt-3 p-0">Barcha bildirishnomalarni ko'rish</a>
                    </div>
                </div>
            </div>

            <!-- Performance Comparison Chart Section (Moved to appear after Notifications) -->
            <div class="col-12 mb-4">
                <div class="card profile-card">
                    <div class="card-body chart-container">
                        <h3 class="section-heading text-center">Sizning ko'rsatkichlaringiz va Maktabning umumiy o'rtacha ko'rsatkichlari</h3>
                        <canvas id="performanceChart"></canvas>
                        <p class="text-center text-muted mt-3">
                            Sizning umumiy ballingiz: <strong><?php echo $student_combined_score_formatted; ?></strong> |
                            Maktabning o'rtacha umumiy balli: <strong><?php echo $school_combined_score_formatted; ?></strong>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Quick Links -->
            <div class="col-12 mb-4">
                <div class="card dashboard-widget">
                    <div class="card-header">
                        <i class="fas fa-link"></i> Tezkor havolalar
                    </div>
                    <div class="card-body quick-nav-links">
                        <div class="row">
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="marks/index.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-percentage"></i></div>
                                    <div class="quick-link-text">Mening baholarim</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="attendance/index.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-user-check"></i></div>
                                    <div class="quick-link-text">Davomatim</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="schedule/index.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-calendar-day"></i></div>
                                    <div class="quick-link-text">Jadvalim</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="payments/index.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-file-invoice-dollar"></i></div>
                                    <div class="quick-link-text">To'lovlar</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="leaderboard/index.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-trophy"></i></div>
                                    <div class="quick-link-text">Reyting</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="quiz.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-question-circle"></i></div>
                                    <div class="quick-link-text">Viktorina</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="resources.php" class="quick-link-widget">
                                    <div class="quick-link-icon"><i class="fas fa-book"></i></div>
                                    <div class="quick-link-text">Resurslar</div>
                                </a>
                            </div>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-6 mb-3">
                                <a href="../auth/logout.php" class="btn btn-danger btn-block">
                                    <i class="fas fa-sign-out-alt"></i> Chiqish
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<?php include_once __DIR__ . '/../inc/footer.php'; ?>

<!-- Chart.js CDN (Add this to your footer or header if not already there) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var ctx = document.getElementById('performanceChart'); // Get the canvas element
    if (ctx) {
        console.log('Canvas element found for performanceChart!');
        if (typeof Chart !== 'undefined') {
            console.log('Chart.js library is loaded!');
            var performanceChart = new Chart(ctx.getContext('2d'), {
                type: 'bar',
                data: <?php echo json_encode($chart_data); ?>,
                options: {
                    responsive: true,
                    maintainAspectRatio: false, // Allows the chart to adapt to its container
                    indexAxis: 'y', // Makes it a horizontal bar chart
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                font: {
                                    size: 14
                                }
                            }
                        },
                        title: {
                            display: false,
                            text: 'Sizning ko\'rsatkichlaringiz va Maktabning umumiy o\'rtacha ko\'rsatkichlari' // Translated title
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.x !== null) {
                                        label += Math.round(context.parsed.x) + '%';
                                    }
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true,
                            max: 100, // Scores are normalized to 0-100
                            title: {
                                display: true,
                                text: 'Ball (100% ga normallashtirilgan)', // Translated title
                                font: {
                                    size: 14
                                }
                            },
                            ticks: {
                                callback: function(value) {
                                    return value + '%';
                                }
                            }
                        },
                        y: {
                            display: false // Hide Y-axis labels as there's only one category
                        }
                    }
                }
            });
        } else {
            console.error('XATO: Chart.js kutubxonasi yuklanmagan. CDN havolasini tekshiring.'); // Translated error
        }
    } else {
        console.error('XATO: "performanceChart" ID li canvas elementi topilmadi.'); // Translated error
    }
});
</script>

---

## 🎨 `assets/css/style.css` (Yangilangan CSS)

Iltimos, ushbu CSS kodini `assets/css/style.css` faylingizdagi barcha mavjud kontent bilan **almashtiring**. Bu tezkor havolalar uchun yangi vidjet stilini, reyting jadvali va AI hisoboti matni rangini to'g'irlaydi, shuningdek diagramma ko'rinishini ta'minlash uchun kerakli sozlamalarni o'z ichiga oladi.

```css
/* General Body Styling & Global Resets */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Modern, clean font */
    background-color: #f0f2f5; /* Light grayish-white background for entire application */
    margin: 0;
    color: #333;
    line-height: 1.6;
    padding-top: 20px;
    padding-bottom: 20px;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

/* --- Login Page Specific Styles --- */
.login-container {
    background-color: #ffffff;
    padding: 25px 30px;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 90%;
    max-width: 350px;
    margin: auto;
    position: relative;
    top: auto;
    left: auto;
    transform: none;
}

.login-container h2 {
    margin-bottom: 20px;
    color: #333;
    font-size: 1.8em;
}

/* Form Group - used in login and potentially other forms */
.form-group {
    margin-bottom: 15px;
    text-align: left;
}

.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: bold;
    color: #555;
    font-size: 0.95em;
}

.form-group input[type="text"],
.form-group input[type="email"],
.form-group input[type="password"],
.form-group textarea,
.form-group select {
    width: calc(100% - 16px);
    padding: 10px 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 1em;
    box-sizing: border-box;
}

.form-group input[type="text"]:focus,
.form-group input[type="email"]:focus,
.form-group input[type="password"]:focus,
.form-group textarea:focus,
.form-group select:focus {
    border-color: #555;
    outline: none;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}

/* Button - used throughout the app */
button[type="submit"],
.btn {
    background-color: #333;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1.1em;
    font-weight: bold;
    transition: background-color 0.3s ease, transform 0.2s ease; /* Added transform for hover effect */
    text-decoration: none;
    display: inline-block;
}

button[type="submit"]:hover,
.btn:hover {
    background-color: #555;
    transform: translateY(-2px); /* Slight lift effect */
}

/* Error Message - used throughout the app */
.error-message, .alert-danger {
    color: #d9534f;
    background-color: #f2dede;
    border: 1px solid #ebccd1;
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 15px;
    text-align: center;
    font-weight: bold;
    font-size: 0.9em;
}

/* Success Message */
.success-message, .alert-success {
    color: #3c763d;
    background-color: #dff0d8;
    border: 1px solid #d6e9c6;
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 15px;
    text-align: center;
    font-weight: bold;
    font-size: 0.9em;
}

/* --- Dashboard Layout (Applies to both Admin & Student) --- */
.wrapper {
    display: flex;
    min-height: 100vh;
}

/* Sidebar Styling */
.sidebar {
    width: 250px;
    background-color: #333;
    color: #fff;
    padding: 20px 0;
    box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;
}

.sidebar .logo {
    text-align: center;
    margin-bottom: 30px;
}

.sidebar .logo a {
    color: #fff;
    font-size: 1.8em;
    font-weight: bold;
    text-decoration: none;
}

.sidebar .main-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar .main-nav ul li a {
    display: block;
    padding: 15px 20px;
    color: #bbb;
    text-decoration: none;
    transition: background-color 0.3s ease, color 0.3s ease;
}

.sidebar .main-nav ul li a:hover,
.sidebar .main-nav ul li a.active {
    background-color: #555;
    color: #fff;
}

/* Content Area (main content wrapper) */
.content-area {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    padding-top: 20px;
    padding-bottom: 20px;
    width: 100%;
}

/* Top Bar */
.top-bar {
    background-color: #fff;
    padding: 15px 20px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: sticky; /* Make top bar sticky */
    top: 0;
    z-index: 1000; /* Ensure it stays on top of other content */
}

.top-bar .user-info {
    font-weight: bold;
    color: #555;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
}

/* --- ADMIN MOBILE LOGOUT BUTTON --- */
.mobile-admin-logout {
    display: none;
}

/* Main Content Area (this now acts as the primary content padding) */
.dashboard-container { /* Renamed from .main-content to be more specific */
    padding: 20px; /* Consistent padding for the dashboard content */
    flex-grow: 1; /* Allows it to take remaining space */
    width: 100%; /* Ensure it uses full width of content-area */
    box-sizing: border-box; /* Include padding in width */
}

.dashboard-welcome {
    font-size: 2.2em;
    font-weight: 700;
    color: #2c3e50; /* Darker blue-gray */
    margin-bottom: 10px;
}

.dashboard-subheading {
    font-size: 1.1em;
    color: #7f8c8d; /* Muted gray */
    margin-bottom: 30px;
}

.section-heading {
    font-size: 1.8em;
    font-weight: 600;
    color: #34495e; /* Slightly darker blue-gray */
    margin-top: 40px;
    margin-bottom: 20px;
    border-bottom: 2px solid #ecf0f1; /* Light separator */
    padding-bottom: 10px;
    text-align: left; /* Default alignment */
}

/* --- AI-Powered Progress Report Card --- */
.ai-report-card {
    background-color: #e8f5e9; /* Light green background */
    border: 1px solid #c8e6c9; /* Green border */
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
    padding: 20px;
    margin-bottom: 30px;
}

.ai-report-card .card-title {
    color: #2e7d32; /* Darker green for title */
    font-size: 1.5em;
    font-weight: bold;
    margin-bottom: 15px;
}

/* FIXED: AI-Powered Progress Report text color to black */
.ai-report-card .card-text {
    font-size: 1.1em;
    line-height: 1.8;
    color: #000000; /* Changed to black */
}

.ai-report-card .card-text strong {
    color: #000000; /* Changed to black */
}

/* Dashboard Widgets - General Card Styling (applies to marks, attendance, leaderboard) */
.dashboard-widgets-row {
    margin-top: 30px;
}

.dashboard-widget {
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
    border: none; /* Remove default Bootstrap border */
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    height: 100%; /* Ensure cards in a row have equal height */
    display: flex;
    flex-direction: column;
}

.dashboard-widget:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.12);
}

.dashboard-widget .card-header {
    background-color: #f8f9fa; /* Light background for header */
    border-bottom: 1px solid #e9ecef;
    color: #495057; /* Darker text */
    font-weight: bold;
    font-size: 1.1em;
    padding: 15px 20px;
    border-top-left-radius: 10px; /* Inherit border-radius from parent */
    border-top-right-radius: 10px;
    display: flex;
    align-items: center;
}

.dashboard-widget .card-header i {
    margin-right: 10px;
    color: #007bff; /* Accent color for icons */
}

.dashboard-widget .card-body {
    padding: 20px;
    flex-grow: 1; /* Allow body to take available space */
}

/* Your Marks Specifics */
.dashboard-widget .list-group-item {
    padding: 12px 0;
    font-size: 1em;
    color: #555;
    border-color: #f0f2f5; /* Lighter border between list items */
}

.dashboard-widget .list-group-item .badge {
    font-size: 0.9em;
    padding: 0.5em 0.8em;
    border-radius: 5px;
}

/* Attendance Card Specifics */
.attendance-chart-container {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto 15px auto; /* Center the circle */
    position: relative;
    overflow: hidden; /* Important for conic-gradient */
}

.attendance-circle {
    background-color: #fff; /* Inner circle background */
    width: 120px;
    height: 120px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.8em;
    font-weight: bold;
    color: #28a745; /* Green for percentage */
    z-index: 2; /* Ensure it's above the conic-gradient */
}

/* --- Performance Comparison Chart Section --- */
.profile-card { /* Renamed and repurposed for chart */
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    padding: 25px; /* Default desktop padding */
    margin-bottom: 30px;
    text-align: center;
}

.chart-container {
    position: relative;
    height: 350px; /* Default desktop height */
    width: 100%; /* Takes full width of parent */
    margin: auto; /* Center within its container */
}

.chart-container h3.section-heading {
    text-align: center;
    margin-top: 0; /* Override default margin-top */
    margin-bottom: 20px;
}

/* --- Quick Links Section (NEW STYLING) --- */
.quick-nav-links .row {
    margin-left: -7.5px; /* Adjust row margins for column padding */
    margin-right: -7.5px;
}

.quick-nav-links .col-lg-2,
.quick-nav-links .col-md-3,
.quick-nav-links .col-sm-4,
.quick-nav-links .col-6 {
    padding-left: 7.5px; /* Adjust column padding */
    padding-right: 7.5px;
}

.quick-nav-links .quick-link-widget {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); /* Lighter shadow than main widgets */
    padding: 20px 10px; /* Adjust padding to make it square-ish */
    height: 120px; /* Fixed height for a uniform square-ish appearance */
    text-align: center;
    color: #555; /* Default text color */
    text-decoration: none; /* Remove underline */
    transition: transform 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
    cursor: pointer;
    width: 100%; /* Ensure it takes full column width */
}

.quick-nav-links .quick-link-widget:hover {
    transform: translateY(-3px); /* Slight lift */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12); /* Enhanced shadow */
    background-color: #f8f9fa; /* Slightly lighter background on hover */
}

.quick-nav-links .quick-link-icon {
    font-size: 2.5em; /* Larger icon */
    color: #007bff; /* Primary blue for icons */
    margin-bottom: 8px; /* Space between icon and text */
}

.quick-nav-links .quick-link-text {
    font-size: 0.9em;
    font-weight: 600; /* Slightly bold text */
    color: #495057; /* Darker text for readability */
    line-height: 1.2;
}

/* Footer Styling */
.footer {
    background-color: #eee;
    padding: 15px 20px;
    text-align: center;
    color: #777;
    font-size: 0.9em;
    margin-top: 30px;
}

/* --- Table Styling (General Tables - NOT Leaderboard) --- */
.table-container {
    width: 100%;
    overflow-x: auto;
    margin-top: 20px;
    margin-bottom: 20px;
}

table:not(.leaderboard-table) {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    background-color: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border-radius: 8px;
    overflow: hidden;
}

table:not(.leaderboard-table) thead tr {
    background-color: #e9ecef;
    color: #343a40;
    text-align: left;
    border-bottom: 2px solid #dee2e6;
}

table:not(.leaderboard-table) th,
table:not(.leaderboard-table) td {
    padding: 12px 15px;
    vertical-align: middle;
}

table:not(.leaderboard-table) th {
    font-weight: 600;
    font-size: 0.95em;
    text-transform: uppercase;
    color: #495057;
}

table:not(.leaderboard-table) tbody tr {
    border-bottom: 1px solid #e0e0e0;
}

table:not(.leaderboard-table) tbody tr:nth-of-type(even) {
    background-color: #f8f9fa;
}

table:not(.leaderboard-table) tbody tr:hover {
    background-color: #e2f2ff;
    cursor: pointer;
}

table:not(.leaderboard-table) tbody tr:last-of-type {
    border-bottom: none;
}

/* --- Notifications Styling --- */
.notification-card {
    border: 1px solid #b3e0ff;
    border-radius: 10px; /* Slightly more rounded */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    background-color: #ffffff;
}

.notification-header {
    background-color: #007bff !important;
    color: white !important;
    padding: 15px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.notification-header h5 {
    font-size: 1.25rem;
    margin-bottom: 0;
    font-weight: 600;
}

.notification-header h5::before {
    content: '📢'; /* Changed to megaphone for announcement tone */
    margin-right: 10px;
    font-size: 1.2em;
    vertical-align: middle;
}

.notification-body {
    padding: 20px;
}

.notification-list {
    padding-left: 0;
    list-style: none;
}

.notification-item {
    border-bottom: 1px solid #eee;
    padding: 15px 0;
    transition: background-color 0.3s ease;
    display: flex;
    flex-direction: column;
}

.notification-item:last-child {
    border-bottom: none;
}

.notification-item:hover {
    background-color: #f8f9fa;
}

.notification-message {
    font-size: 1rem;
    line-height: 1.5;
    color: #333;
    margin-bottom: 5px;
}

.notification-message strong {
    color: #0056b3;
    font-weight: 700;
}

.notification-date {
    font-size: 0.85rem;
    color: #6c757d;
    align-self: flex-end;
}

.no-notifications {
    font-style: italic;
    color: #999;
    text-align: center;
    padding: 20px;
}

/* View All Notifications link */
.notification-card .btn-link {
    color: #007bff;
    font-weight: bold;
    text-decoration: none;
    transition: color 0.2s ease;
}

.notification-card .btn-link:hover {
    color: #0056b3;
    text-decoration: underline;
}

/* --- Responsive Layout & Mobile Navigation --- */
.container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
    max-width: 1200px;
    box-sizing: border-box;
}

img, video, iframe {
    max-width: 100%;
    height: auto;
    display: block;
}

/* Mobile Bottom Navigation Specific Styles */
.mobile-bottom-nav {
    display: none; /* Hidden by default on desktop for all users */
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #333; /* Dark background */
    color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.15);
    z-index: 1050; /* Above most content */
    display: flex;
    justify-content: space-around;
    padding: 8px 0; /* Reduced padding */
    align-items: center;
}

.mobile-bottom-nav a {
    flex: 1;
    text-align: center;
    color: #bbb; /* Muted color */
    text-decoration: none;
    padding: 5px 0; /* Reduced padding */
    font-size: 0.8em; /* Smaller font for text */
    transition: color 0.3s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.mobile-bottom-nav a i {
    font-size: 1.3em; /* Larger icons */
    margin-bottom: 3px; /* Space between icon and text */
}

.mobile-bottom-nav a:hover,
.mobile-bottom-nav a.active {
    color: #fff; /* White on hover/active */
}

/* --- LEADERBOARD SPECIFIC STYLES (REFINED TO MATCH SCREENSHOT) --- */

/* Styles for the unified leaderboard list within dashboard-widget */
.leaderboard-list .list-group-item {
    font-size: 1em;
    padding: 8px 15px; /* Reduced vertical padding */
    border-bottom: 1px solid #f0f2f5; /* Light separator */
    transition: background-color 0.2s ease;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #333; /* Default text color to dark */
}

.leaderboard-list .list-group-item:last-child {
    border-bottom: none;
}

.leaderboard-list .list-group-item:hover {
    background-color: #f8f9fa;
}

.leaderboard-list .list-group-item .leaderboard-rank {
    font-weight: bold;
    min-width: 25px; /* Fixed width for rank alignment */
    text-align: center; /* Center rank number */
}

.leaderboard-list .list-group-item .rank-medal {
    font-size: 1em;
    margin-left: 3px; /* Space between rank and medal */
    vertical-align: middle;
}

.leaderboard-list .list-group-item .leaderboard-name {
    font-weight: normal; /* As seen in screenshot */
    flex-grow: 1; /* Allows name to take available space */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 8px; /* Space after rank/medal block */
    margin-right: 10px; /* Space before score badge */
}

.leaderboard-list .list-group-item .badge {
    background-color: #f0f2f5; /* Light grey background for score badge */
    color: #333; /* Dark text for score */
    font-weight: bold;
    font-size: 0.9em;
    padding: 0.4em 0.7em;
    border-radius: 5px;
    min-width: 50px; /* Ensure badge has consistent width */
    text-align: center;
}

/* Specific styles for top 1, 2, 3 ranks */
.leaderboard-list .list-group-item.top-1 {
    background-color: #ffffff; /* White for 1st place */
    color: #333;
    border-color: #f0f2f5; /* Maintain light border */
}
.leaderboard-list .list-group-item.top-1 .badge {
    background-color: #f0f2f5; /* Light grey badge for 1st */
    color: #333;
}
.leaderboard-list .list-group-item.top-1 .rank-medal {
    filter: grayscale(100%); /* Make gold medal greyscale to match color scheme */
}


.leaderboard-list .list-group-item.top-2 {
    background-color: #e6f7ff; /* Light blue-gray for 2nd place */
    color: #333;
    border-color: #d1ecf1;
}
.leaderboard-list .list-group-item.top-2 .badge {
    background-color: #d1ecf1; /* Darker blue-gray badge for 2nd */
    color: #333;
}
.leaderboard-list .list-group-item.top-2 .rank-medal {
    filter: grayscale(100%); /* Make silver medal greyscale */
}

.leaderboard-list .list-group-item.top-3 {
    background-color: #e6f7ff; /* Light blue-gray for 3rd place (same as 2nd in screenshot) */
    color: #333;
    border-color: #d1ecf1;
}
.leaderboard-list .list-group-item.top-3 .badge {
    background-color: #d1ecf1; /* Darker blue-gray badge for 3rd */
    color: #333;
}
.leaderboard-list .list-group-item.top-3 .rank-medal {
    filter: grayscale(100%); /* Make bronze medal greyscale */
}

/* Highlight current user in leaderboard list (keep original blue theme for this for distinction) */
.leaderboard-list .list-group-item.current-user-rank {
    background-color: #e6f7ff !important; /* Light blue highlight for current user */
    border-left: 3px solid #007bff; /* Blue border */
    color: #0056b3 !important; /* Darker blue text */
}
.leaderboard-list .list-group-item.current-user-rank .badge {
    background-color: #0056b3 !important; /* Darker badge background for current user */
    color: #fff !important;
}
.leaderboard-list .list-group-item.current-user-rank .rank-medal {
    filter: none; /* Restore color for current user's medal if they are top 3 */
}


/* --- Media Queries for Overall Responsiveness --- */

/* Mobile-first approach: Styles below are for screens smaller than 768px */
@media (max-width: 767.98px) {
    /* Hide the sidebar on mobile */
    .sidebar {
        display: none;
    }

    /* Show mobile bottom navigation */
    .mobile-bottom-nav {
        display: flex;
    }

    /* Ensure the content area takes full width on mobile */
    .content-area {
        width: 100%;
        padding-left: 0 !important;
        padding-right: 0 !important;
        padding-top: 15px; /* Adjust top padding */
        padding-bottom: 80px; /* Space for fixed bottom nav */
    }

    /* Adjust the container within the main content for mobile */
    .container {
        padding-left: 15px !important; /* Keep a bit of padding for content */
        padding-right: 15px !important;
        width: 100% !important;
        max-width: unset !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
    }

    /* Hide the desktop logout button in the top bar on mobile */
    .top-bar .user-info .btn-danger:not(.mobile-admin-logout) {
        display: none;
    }
    /* Show the mobile logout button in the top bar */
    .mobile-admin-logout {
        display: inline-block;
        margin-left: 10px;
    }

    /* Global mobile padding reduction for the body */
    body {
        padding-left: 0 !important;
        padding-right: 0 !important;
        padding-bottom: 60px; /* Ensure space for bottom nav */
    }

    /* Make the dashboard container fill width and remove card-like styling at the top */
    .dashboard-container {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }
    .dashboard-welcome, .dashboard-subheading {
        padding-left: 15px;
        padding-right: 15px;
    }

    /* AI Report Card: Make it full width on mobile */
    .ai-report-card {
        margin-left: 0;
        margin-right: 0;
        border-radius: 0;
        box-shadow: none;
        border-left: none;
        border-right: none;
        padding-left: 15px;
        padding-right: 15px;
    }

    /* Adjust padding/margins for sections that are now within a full-width flow */
    .section-heading,
    .quick-nav-links,
    .notification-card {
        padding-left: 15px !important;
        padding-right: 15px !important;
        max-width: unset !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
        border-radius: 0 !important; /* Remove card-like border-radius for full width sections */
        box-shadow: none !important; /* Remove shadows for full width sections */
    }
    .notification-card {
        border-left: none;
        border-right: none;
    }

    /* Chart Container specific mobile adjustments */
    .profile-card { /* Now solely for the chart on mobile */
        padding: 0 !important; /* No padding on the card itself */
        width: 100% !important;
        max-width: unset !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
        border-radius: 0 !important;
        box-shadow: none !important;
        background-color: transparent; /* Make card background transparent, chart itself will have white */
    }

    .chart-container {
        padding: 15px !important; /* Padding for the chart area inside the transparent card */
        height: 250px !important; /* Taller chart height on mobile */
        border-radius: 10px !important; /* Keep rounded corners for the chart area itself */
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08) !important; /* Add shadow back to chart area */
        background-color: #ffffff; /* White background for the chart area */
    }

    /* Leaderboard: Mobile adjustments for the unified list */
    .leaderboard-list .list-group-item .leaderboard-name {
        font-size: 0.9em; /* Adjust name font for mobile */
    }
    .leaderboard-list .list-group-item .badge {
        font-size: 0.8em; /* Adjust badge font for mobile */
        min-width: 45px; /* Slightly smaller min-width for mobile badge */
    }

    /* Dashboard Widgets: Ensure they respond well within the grid */
    .dashboard-widgets-row .col-lg-4,
    .dashboard-widgets-row .col-md-6,
    .dashboard-widgets-row .col-12 {
        padding-left: 15px; /* Ensure column padding for grid */
        padding-right: 15px;
    }

    /* Adjust padding for the quick links row to avoid excessive inner padding */
    .quick-nav-links .row {
        margin-left: 0;
        margin-right: 0;
    }
    .quick-nav-links .col-lg-2,
    .quick-nav-links .col-md-3,
    .quick-nav-links .col-sm-4,
    .quick-nav-links .col-6 {
        padding-left: 7.5px;
        padding-right: 7.5px;
    }
    .quick-nav-links .quick-link-widget {
        height: 100px; /* Slightly smaller height for mobile */
        padding: 15px 10px;
    }
    .quick-nav-links .quick-link-icon {
        font-size: 2em; /* Smaller icon for mobile */
    }
    .quick-nav-links .quick-link-text {
        font-size: 0.8em; /* Smaller text for mobile */
    }

    /* Ensure logout button stays the same on mobile too */
    .quick-nav-links .btn-danger.btn-block {
        flex-direction: row;
        height: auto;
        padding: 10px 20px;
        font-size: 1.1em;
    }
    .quick-nav-links .btn-danger.btn-block i {
        margin-right: 10px;
        margin-bottom: 0;
        font-size: 1.3em;
    }
}

/* Desktop-first approach: Styles below are for screens 768px and larger */
@media (min-width: 768px) {
    /* Hide the mobile bottom nav on desktop */
    .mobile-bottom-nav {
        display: none !important;
    }

    /* Restore desktop-specific container padding for main content */
    .dashboard-container {
        padding-left: 20px;
        padding-right: 20px;
        width: auto; /* Reset width for max-width to apply */
        max-width: 1200px; /* Max width for desktop content */
        margin-left: auto;
        margin-right: auto;
    }

    /* Restore card styling for AI report card, quick links, notifications */
    .ai-report-card,
    .notification-card {
        border-radius: 10px;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
        border: 1px solid #c8e6c9; /* Specific to AI card */
    }
    .notification-card {
        border: 1px solid #b3e0ff; /* Specific to notification card */
    }
    .profile-card { /* Ensure chart container uses desktop styles */
        padding: 25px !important;
        border-radius: 10px !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;
        background-color: #ffffff; /* Explicitly white for desktop chart card */
    }
    .chart-container {
        height: 350px !important;
        padding: 20px !important;
        border-radius: 8px !important;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
        background-color: transparent; /* Chart JS draws its own background */
    }

    /* Reset mobile specific paddings/margins for desktop */
    .section-heading,
    .quick-nav-links {
        padding-left: 0 !important;
        padding-right: 0 !important;
        margin-left: auto !important;
        margin-right: auto !important;
        max-width: 100% !important; /* Ensure they fit within dashboard container */
    }

    /* Adjust padding for the quick links row on desktop */
    .quick-nav-links .row {
        margin-left: -7.5px;
        margin-right: -7.5px;
    }
    .quick-nav-links .col-lg-2,
    .quick-nav-links .col-md-3,
    .quick-nav-links .col-sm-4,
    .quick-nav-links .col-6 {
        padding-left: 7.5px;
        padding-right: 7.5px;
    }
    .quick-nav-links .quick-link-widget {
        height: 120px; /* Restore desktop height */
        padding: 20px 10px; /* Restore desktop padding */
    }
    .quick-nav-links .quick-link-icon {
        font-size: 2.5em; /* Restore desktop icon size */
    }
    .quick-nav-links .quick-link-text {
        font-size: 0.9em; /* Restore desktop text size */
    }
}