<?php
session_start();
require_once 'config.php';

// Define role constants
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);

// Check admin access
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }
    if ($_SESSION["role"] !== $required_role_code) {
        header("location: login.php");
        exit;
    }
}

check_role_access(ROLE_ADMIN);

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables
$phone_number = $photo = $status = ""; // Initialize variables for DB fetch

// Initialize school variables
$school_name = "School Name Not Found";
$school_logo_path = "images/default_school_logo.png";

// Fetch school details
if (isset($conn) && $conn instanceof mysqli) {
    $sql_school = "SELECT school_name, logo, motto, email FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db, $school_motto_db, $school_email_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
                $school_motto = !empty($school_motto_db) ? htmlspecialchars($school_motto_db) : '';
                $school_email = !empty($school_email_db) ? htmlspecialchars($school_email_db) : '';
            }
        }
        $stmt_school->close();
    }

    // Fetch additional user details from the database (phone, photo, status) from the 'users' table
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            // Default photo for Admin if not set
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiBmaWxsPSIjQ0NDQ0NDIi8+Cjx0ZXh0IHg9IjQwIiB5PSI0NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjE4IiBmb250LXdlaWdodD0iYm9sZCIgZmlsbD0iI0ZGRkZGRiIgdGV4dC1hbmNob3I9Im1pZGRsZSI+QUQ8L3RleHQ+Cjwvc3ZnPgo=';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query for Admin: " . $stmt->error);
        }
        $stmt->close(); // This $stmt is closed here
    } else {
        error_log("Prepare failed for user details query for Admin: " . $conn->error);
        // Set default photo if query fails
        $photo = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiBmaWxsPSIjQ0NDQ0NDIi8+Cjx0ZXh0IHg9IjQwIiB5PSI0NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjE4IiBmb250LXdlaWdodD0iYm9sZCIgZmlsbD0iI0ZGRkZGRiIgdGV4dC1hbmNob3I9Im1pZGRsZSI+QUQ8L3RleHQ+Cjwvc3ZnPgo=';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports & Printouts - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .reports-container {
            padding: 20px;
            background-color: #f8f9fa;
            min-height: 100vh;
        }

        .reports-header {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            text-align: center;
        }

        .reports-header h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 600;
        }

        .reports-header p {
            margin: 10px 0 0 0;
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .reports-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .report-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            border: 1px solid #000000;
            position: relative;
            overflow: hidden;
        }

        .report-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
        }

        .report-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #007bff, #28a745);
        }

        .report-icon {
            width: 70px;
            height: 70px;
            border-radius: 10px;
            background: linear-gradient(135deg, #007bff, #0056b3);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            color: white;
            font-size: 2rem;
        }

        .report-card h3 {
            color: #333;
            margin: 0 0 15px 0;
            font-size: 1.4rem;
            font-weight: 600;
            text-align: center;
        }

        .report-card p {
            color: #666;
            margin: 0 0 25px 0;
            line-height: 1.6;
            text-align: center;
            font-size: 0.95rem;
        }

        .view-options-btn {
            width: 100%;
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .view-options-btn:hover {
            background: linear-gradient(135deg, #0056b3, #004494);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
        }

        .breadcrumb {
            background: white;
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .breadcrumb a {
            color: #007bff;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        @media (max-width: 768px) {
            .reports-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .reports-header h1 {
                font-size: 2rem;
            }
            
            .report-card {
                padding: 25px 20px;
            }
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }

        .modal-header {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 20px 30px;
            border-radius: 12px 12px 0 0;
            position: relative;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 1.5rem;
        }

        .close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 2rem;
            font-weight: bold;
            cursor: pointer;
            color: white;
            opacity: 0.8;
        }

        .close:hover {
            opacity: 1;
        }

        .modal-body {
            padding: 30px;
        }

        .report-options {
            display: grid;
            gap: 15px;
        }

        .report-option {
            padding: 20px;
            border: 2px solid #000000;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }

        .report-option:hover {
            border-color: #007bff;
            background: #f8f9ff;
        }

        .report-option h4 {
            margin: 0 0 10px 0;
            color: #333;
            font-size: 1.1rem;
        }

        .report-option p {
            margin: 0;
            color: #666;
            font-size: 0.9rem;
        }

        .generate-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            margin-top: 10px;
        }

        .generate-btn:hover {
            background: #218838;
        }

        .download-btn {
            background: #17a2b8;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            margin: 10px 5px 0 0;
        }

        .download-btn:hover {
            background: #138496;
        }

        /* --- HEADER STYLES --- */
        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 10px 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        /* Main Content Area */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
            transition: margin-left 0.3s ease;
        }

        .sidebar-collapsed .main-content {
            margin-left: 0;
        }

        /* Scrollable Content Area */
        .reports-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .reports-content::-webkit-scrollbar {
            width: 8px;
        }

        .reports-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .reports-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .reports-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            height: 100vh;
            background: #080424d2;
            color: white;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 1000;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 3px;
        }

        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #333;
            padding: 8px;
            border-radius: 4px;
            transition: background-color 0.2s ease;
        }

        .menu-toggle:hover {
            background-color: #f0f0f0;
        }

        .school-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }

        .school-info img {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            object-fit: contain;
        }

        .school-info h1 {
            margin: 0;
            font-size: 1.3em;
            font-weight: 600;
            color: #333;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Language Selection Styles */
        .language-select {
            position: relative;
        }

        .language-select select {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 0.85em;
            color: #333;
            cursor: pointer;
            min-width: 120px;
            appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="%23666" d="M2 0L0 2h4zm0 5L0 3h4z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 10px;
            transition: all 0.2s ease;
        }

        .language-select select:hover {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }

        .language-select select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* Search Bar Styles */
        .search-bar {
            position: relative;
            display: flex;
            align-items: center;
        }

        .search-bar i {
            position: absolute;
            left: 10px;
            color: #666;
            font-size: 0.9em;
        }

        .search-bar input {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 20px;
            padding: 8px 12px 8px 35px;
            font-size: 0.85em;
            color: #333;
            width: 200px;
            transition: all 0.2s ease;
        }

        .search-bar input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
            width: 250px;
        }

        /* Notifications Styles */
        .notifications {
            position: relative;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: background-color 0.2s ease;
        }

        .notifications:hover {
            background-color: #f0f0f0;
        }

        .notifications i {
            font-size: 1.2em;
            color: #666;
        }

        .notifications .badge {
            position: absolute;
            top: 2px;
            right: 2px;
            background: #dc3545;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 0.7em;
            font-weight: bold;
            min-width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* User Profile Styles */
        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            padding: 8px;
            border-radius: 8px;
            transition: background-color 0.2s ease;
        }

        .user-profile:hover {
            background-color: #f0f0f0;
        }

        .user-profile img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #e0e0e0;
        }

        .user-profile div {
            display: flex;
            flex-direction: column;
        }

        .user-profile .user-name {
            font-weight: 600;
            font-size: 0.9em;
            color: #333;
            line-height: 1.2;
        }

        .user-profile .user-email {
            font-size: 0.75em;
            color: #666;
            line-height: 1.2;
        }

        .user-profile i {
            color: #666;
            font-size: 0.8em;
            transition: transform 0.2s ease;
        }

        .user-profile:hover i {
            transform: rotate(180deg);
        }

        /* --- MOBILE FOOTER NAVIGATION STYLES --- */
        
        /* Mobile Footer Navigation */
        #mobile-footer-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 70px;
            background: #ffffff;
            border-top: 1px solid #000000;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            padding-bottom: env(safe-area-inset-bottom, 0px);
            display: none; /* Hidden by default on desktop */
        }

        #mobile-footer-nav ul {
            display: flex;
            list-style: none;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #mobile-footer-nav li {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #mobile-footer-nav a {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #666666;
            font-size: 10px;
            font-weight: 500;
            width: 100%;
            height: 100%;
            transition: all 0.3s ease;
            position: relative;
        }

        #mobile-footer-nav a i {
            font-size: 22px;
            margin-bottom: 4px;
            transition: all 0.3s ease;
        }

        #mobile-footer-nav a.active {
            color: #4f46e5;
        }

        #mobile-footer-nav a.active::after {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 3px;
            background: #4f46e5;
            border-radius: 2px;
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            .reports-content {
                padding: 15px 10px 20px;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.show {
                transform: translateX(0);
            }
            
            /* Mobile header adjustments */
            .header-right {
                gap: 10px;
            }
            
            .language-select select {
                font-size: 0.8em;
                padding: 4px 8px;
                min-width: 100px;
            }
            
            .search-bar input {
                width: 120px;
            }
            
            .user-profile img {
                width: 35px;
                height: 35px;
            }
            
            .user-name {
                font-size: 0.85em;
            }
            
            .user-email {
                font-size: 0.75em;
            }
        }

        /* Small Mobile Devices */
        @media (max-width: 360px) {
            .reports-content {
                padding: 10px 5px 15px;
            }
            
            .header-right {
                gap: 8px;
            }
            
            .language-select select {
                font-size: 0.75em;
                padding: 4px 6px;
                min-width: 90px;
            }
            
            .search-bar input {
                width: 100px;
            }
        }

        @media (max-width: 360px) {
            .header-right {
                gap: 8px;
            }
            
            .language-select select {
                font-size: 0.75em;
                padding: 4px 6px;
                min-width: 90px;
            }

            .search-bar input {
                width: 120px;
            }

            .search-bar input:focus {
                width: 150px;
            }
        }

        @media (max-width: 360px) {
            #mobile-footer-nav a {
                font-size: 9px;
            }
            
            #mobile-footer-nav a i {
                font-size: 20px;
            }
        }

        /* More Menu Modal */
        #more-menu-modal {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: auto;
            max-height: 80vh;
            background-color: #fff;
            border-top-left-radius: 20px;
            border-top-right-radius: 20px;
            box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.15);
            z-index: 2000;
            transform: translateY(100%);
            transition: transform 0.3s ease-in-out;
            padding-bottom: env(safe-area-inset-bottom, 20px);
            overflow-y: auto;
            visibility: hidden;
            pointer-events: none;
        }

        #more-menu-modal.show {
            transform: translateY(0) !important;
            visibility: visible !important;
            pointer-events: auto !important;
            z-index: 99999 !important;
            display: block !important;
        }
        
        #more-menu-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #000000;
            position: sticky;
            top: 0;
            background-color: #fff;
        }

        #more-menu-close-btn {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #666;
        }

        #more-menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        #more-menu-list li a {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            transition: background-color 0.2s ease;
        }

        #more-menu-list li a:hover {
            background-color: #f4f4f4;
        }

        #more-menu-list li a i {
            font-size: 1.2em;
            width: 30px;
            color: #555;
            margin-right: 15px;
        }

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500;
            display: none;
        }
        
        .overlay.show {
            display: block;
        }

        @media (max-width: 768px) {
        }

        /* Message Form Styles */
        .message-form-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .message-form-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: messageFormSlideIn 0.3s ease-out;
        }

        @keyframes messageFormSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .message-form-header {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 20px;
            border-radius: 12px 12px 0 0;
            position: relative;
        }

        .message-form-header h3 {
            margin: 0;
            font-size: 1.3rem;
            font-weight: 600;
        }

        .message-form-header.success {
            background: linear-gradient(135deg, #28a745, #20c997);
        }

        .message-form-header.error {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }

        .message-form-header.warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
        }

        .message-form-header.info {
            background: linear-gradient(135deg, #17a2b8, #138496);
        }

        .message-form-close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
            opacity: 0.8;
            transition: opacity 0.2s ease;
        }

        .message-form-close:hover {
            opacity: 1;
        }

        .message-form-body {
            padding: 25px;
        }

        .message-form-content {
            margin-bottom: 20px;
        }

        .message-form-content p {
            margin: 0;
            font-size: 1rem;
            line-height: 1.5;
            color: #333;
        }

        .message-form-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .message-form-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 0.95rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 80px;
        }

        .message-form-btn.primary {
            background: #007bff;
            color: white;
        }

        .message-form-btn.primary:hover {
            background: #0056b3;
        }

        .message-form-btn.success {
            background: #28a745;
            color: white;
        }

        .message-form-btn.success:hover {
            background: #218838;
        }

        .message-form-btn.secondary {
            background: #6c757d;
            color: white;
        }

        .message-form-btn.secondary:hover {
            background: #545b62;
        }

        .message-form-btn.danger {
            background: #dc3545;
            color: white;
        }

        .message-form-btn.danger:hover {
            background: #c82333;
        }

        /* PRINT STYLES FOR BLACK BORDERS */
        @media print {
            body {
                background-color: #fff !important;
                color: #000 !important;
            }
            
            table, th, td {
                border-color: #000000 !important;
                border: 1px solid #000000 !important;
                color: #000 !important;
            }
            
            th {
                background-color: #f0f0f0 !important;
            }
            
            .reports-header, .sidebar, .header, .mobile-footer, .no-print {
                display: none !important;
            }
            
            .main-content {
                margin-left: 0 !important;
                width: 100% !important;
                padding: 0 !important;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar is hidden on mobile via CSS but kept for desktop -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
               <br><H8> DIVINE REPORTS</H8></br>
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li class="hide-on-mobile"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li class="hide-on-mobile"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> Subjects</a></li>
                    <li class="hide-on-mobile"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li class="hide-on-mobile"><a href="admin_messages.php" id="messagesLink"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li class="active"><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li class="hide-on-mobile"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> Settings</a></li>
                    <li class="hide-on-mobile"><a href="logout.php" class="logout-btn" id="logoutLink"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect">
                           <option value="en">🇬🇧 English</option>
                           <option value="lg">🇺🇬 Luganda</option>
                           <option value="sw">🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search students/data" id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span> </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email">Logged in as: Admin</div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="reports-content">
                <div class="reports-grid">
                    <!-- Student Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-user-graduate"></i>
                        </div>
                        <h3>Student Reports</h3>
                        <p>Generate lists of students along with relevant background details</p>
                        <button class="view-options-btn" onclick="openModal('studentModal')">View Options</button>
                    </div>

                    <!-- Teacher Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-chalkboard-teacher"></i>
                        </div>
                        <h3>Teacher Reports</h3>
                        <p>Access teacher profiles, contact information, and performance summaries</p>
                        <button class="view-options-btn" onclick="openModal('teacherModal')">View Options</button>
                    </div>

                    <!-- Class & Subject Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-chalkboard"></i>
                        </div>
                        <h3>Class & Subject Reports</h3>
                        <p>Print class rosters, subject allocations, and curriculum activities</p>
                        <button class="view-options-btn" onclick="openModal('classModal')">View Options</button>
                    </div>

                    <!-- Attendance Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-calendar-check"></i>
                        </div>
                        <h3>Attendance Reports</h3>
                        <p>Summarize student and staff attendance records over various periods</p>
                        <button class="view-options-btn" onclick="openModal('attendanceModal')">View Options</button>
                    </div>

                    <!-- Exam & Grade Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-graduation-cap"></i>
                        </div>
                        <h3>Exam & Grade Reports</h3>
                        <p>Generate result slips, academic transcripts, and grade distribution reports</p>
                        <button class="view-options-btn" onclick="openModal('examModal')">View Options</button>
                    </div>

                    <!-- Financial Reports -->
                    <div class="report-card">
                        <div class="report-icon">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <h3>Financial Reports</h3>
                        <p>Overview of fees, payments, and financial summaries (requires integration)</p>
                        <button class="view-options-btn" onclick="openModal('financialModal')">View Options</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Student Reports Modal -->
    <div id="studentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Student Reports</h2>
                <span class="close" onclick="closeModal('studentModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="report-options">
                    <div class="report-option">
                        <h4>Complete Student List</h4>
                        <p>Full list of all students with personal details</p>
                        <button class="generate-btn" onclick="generateReport('student_list', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Students by Class</h4>
                        <p>Student lists organized by class and stream</p>
                        <button class="generate-btn" onclick="generateReport('student_by_class', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Student Contact Information</h4>
                        <p>Contact details for students and guardians</p>
                        <button class="generate-btn" onclick="generateReport('student_contacts', this)">Generate Report</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Teacher Reports Modal -->
    <div id="teacherModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Teacher Reports</h2>
                <span class="close" onclick="closeModal('teacherModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="report-options">
                    <div class="report-option">
                        <h4>Complete Teacher List</h4>
                        <p>Full list of all teachers with contact details</p>
                        <button class="generate-btn" onclick="generateReport('teacher_list', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Teacher Subject Assignments</h4>
                        <p>Teachers and their assigned subjects and classes</p>
                        <button class="generate-btn" onclick="generateReport('teacher_subjects', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Teacher Workload Report</h4>
                        <p>Teaching load distribution across teachers</p>
                        <button class="generate-btn" onclick="generateReport('teacher_workload', this)">Generate Report</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Class & Subject Reports Modal -->
    <div id="classModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Class & Subject Reports</h2>
                <span class="close" onclick="closeModal('classModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="report-options">
                    <div class="report-option">
                        <h4>Class Lists</h4>
                        <p>Student rosters for each class and stream</p>
                        <button class="generate-btn" onclick="generateReport('class_list', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Subject Allocation</h4>
                        <p>Subject distribution across classes</p>
                        <button class="generate-btn" onclick="generateReport('subject_allocation', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Class Timetables</h4>
                        <p>Weekly schedules for each class</p>
                        <button class="generate-btn" onclick="generateReport('class_timetable', this)">Generate Report</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Attendance Reports Modal -->
    <div id="attendanceModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Attendance Reports</h2>
                <span class="close" onclick="closeModal('attendanceModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="report-options">
                    <div class="report-option">
                        <h4>Daily Attendance</h4>
                        <p>Daily attendance records for students</p>
                        <button class="generate-btn" onclick="generateReport('daily_attendance', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Monthly Attendance Summary</h4>
                        <p>Monthly attendance statistics and trends</p>
                        <button class="generate-btn" onclick="generateReport('monthly_attendance', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Attendance Defaulters</h4>
                        <p>Students with poor attendance records</p>
                        <button class="generate-btn" onclick="generateReport('attendance_defaulters', this)">Generate Report</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Exam & Grade Reports Modal -->
    <div id="examModal" class="modal">
        <div class="modal-content" style="max-width: 1000px;">
            <div class="modal-header">
                <h2>Exam & Grade Reports</h2>
                <span class="close" onclick="closeModal('examModal')">&times;</span>
            </div>
            <div class="modal-body">
                <!-- Comprehensive Report Card Generator Section -->
                <div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); margin-bottom: 20px;">
                    <h3 style="margin: 0 0 20px 0; text-align: center; color: #333; font-size: 1.5rem;">Generate Comprehensive Report Cards</h3>
                    <form id="examReportForm" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                        <div>
                            <label for="exam_academic_year" style="display: block; font-weight: 600; color: #374151; margin-bottom: 5px;">Academic Year</label>
                            <div style="position: relative;">
                                <select id="exam_academic_year" name="academic_year" style="width: 100%; padding: 8px 12px; border: 2px solid #D1D5DB; border-radius: 6px; background: white; appearance: none; padding-right: 30px;" required>
                                    <option value="">Select Year</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                <div style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #6B7280;">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                        <div>
                            <label for="exam_term" style="display: block; font-weight: 600; color: #374151; margin-bottom: 5px;">Term</label>
                            <div style="position: relative;">
                                <select id="exam_term" name="term" style="width: 100%; padding: 8px 12px; border: 2px solid #D1D5DB; border-radius: 6px; background: white; appearance: none; padding-right: 30px;" required>
                                    <option value="">Select Term</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                <div style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #6B7280;">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                        <div>
                            <label for="exam_exam_id" style="display: block; font-weight: 600; color: #374151; margin-bottom: 5px;">Exam</label>
                            <div style="position: relative;">
                                <select id="exam_exam_id" name="exam_id" style="width: 100%; padding: 8px 12px; border: 2px solid #D1D5DB; border-radius: 6px; background: white; appearance: none; padding-right: 30px;" required>
                                    <option value="0">Select Exam</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                <div style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #6B7280;">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                        <div>
                            <label for="exam_class_id" style="display: block; font-weight: 600; color: #374151; margin-bottom: 5px;">Class</label>
                            <div style="position: relative;">
                                <select id="exam_class_id" name="class_id" style="width: 100%; padding: 8px 12px; border: 2px solid #D1D5DB; border-radius: 6px; background: white; appearance: none; padding-right: 30px;" required>
                                    <option value="0">Select Class</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                <div style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #6B7280;">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                        <div>
                            <label for="exam_grading_scale" style="display: block; font-weight: 600; color: #374151; margin-bottom: 5px;">Grading Scale</label>
                            <div style="position: relative;">
                                <select id="exam_grading_scale" name="grading_scale" style="width: 100%; padding: 8px 12px; border: 2px solid #D1D5DB; border-radius: 6px; background: white; appearance: none; padding-right: 30px;" required>
                                    <option value="">Select Grading Scale</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                <div style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #6B7280;">
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                            </div>
                        </div>
                    </form>
                    
                    <div style="text-align: center; margin-top: 25px;">
                        <button type="button" id="generateExamReport" style="padding: 12px 30px; background: linear-gradient(135deg, #7C3AED, #3B82F6); color: white; border: none; border-radius: 8px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.3s ease; margin-right: 10px;" onclick="console.log('🔥 Inline onclick fired!'); generateComprehensiveReportCards(); return false;">
                            <i class="fas fa-chart-line" style="margin-right: 8px;"></i> Generate Report Cards
                        </button>
                        <button type="button" id="printExamReport" style="padding: 12px 30px; background: linear-gradient(135deg, #10B981, #059669); color: white; border: none; border-radius: 8px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.3s ease; margin-right: 10px;" disabled>
                            <i class="fas fa-print" style="margin-right: 8px;"></i> Print Reports
                        </button>
                        <button type="button" id="downloadExamReport" style="padding: 12px 30px; background: linear-gradient(135deg, #3B82F6, #1D4ED8); color: white; border: none; border-radius: 8px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.3s ease;" disabled>
                            <i class="fas fa-download" style="margin-right: 8px;"></i> Download PDF
                        </button>
                    </div>
                </div>

                <!-- Report Preview Section -->
                <div id="examReportPreview" style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 8px; min-height: 100px; display: none;">
                    <div style="text-align: center; color: #6c757d;">
                        <i class="fas fa-file-alt" style="font-size: 3rem; margin-bottom: 15px;"></i>
                        <h4>Report Preview</h4>
                        <p>Generated report cards will appear here</p>
                    </div>
                </div>

                <!-- Additional Report Options -->
                <div class="report-options" style="margin-top: 30px; border-top: 1px solid #000000; padding-top: 20px;">
                    <h4 style="margin-bottom: 15px; color: #333;">Additional Report Options</h4>
                    <div class="report-option">
                        <h4>Exam Results Summary</h4>
                        <p>Complete exam results by class and subject</p>
                        <button class="generate-btn" onclick="generateReport('exam_results', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Grade Analysis</h4>
                        <p>Statistical analysis of academic performance</p>
                        <button class="generate-btn" onclick="generateReport('grade_analysis', this)">Generate Report</button>
                    </div>
                    <div class="report-option">
                        <h4>Academic Transcripts</h4>
                        <p>Official academic transcripts for students</p>
                        <button class="generate-btn" onclick="generateReport('transcripts', this)">Generate Report</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Financial Reports Modal -->
    <div id="financialModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Financial Reports</h2>
                <span class="close" onclick="closeModal('financialModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div class="report-options">
                    <div class="report-option">
                        <h4>Fee Collection Report</h4>
                        <p>Summary of fee collections and outstanding balances</p>
                        <button class="generate-btn" disabled>Coming Soon</button>
                    </div>
                    <div class="report-option">
                        <h4>Payment History</h4>
                        <p>Detailed payment history for each student</p>
                        <button class="generate-btn" disabled>Coming Soon</button>
                    </div>
                    <div class="report-option">
                        <h4>Financial Summary</h4>
                        <p>Overall financial status and summaries</p>
                        <button class="generate-btn" disabled>Coming Soon</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Message Form Overlay -->
    <div id="messageFormOverlay" class="message-form-overlay">
        <div class="message-form-container">
            <div id="messageFormHeader" class="message-form-header">
                <h3 id="messageFormTitle">Message</h3>
                <button id="messageFormClose" class="message-form-close">&times;</button>
            </div>
            <div class="message-form-body">
                <div class="message-form-content">
                    <p id="messageFormContent">Message content will appear here.</p>
                </div>
                <div class="message-form-buttons">
                    <button id="messageFormBtn" class="message-form-btn primary">OK</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function openModal(modalId) {
            document.getElementById(modalId).style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // Message Form Functions
        function showMessageForm(message, title = 'Message', type = 'info', buttonText = 'OK', buttonClass = 'primary') {
            const overlay = document.getElementById('messageFormOverlay');
            const header = document.getElementById('messageFormHeader');
            const titleElement = document.getElementById('messageFormTitle');
            const contentElement = document.getElementById('messageFormContent');
            const button = document.getElementById('messageFormBtn');

            // Set header class based on type
            header.className = `message-form-header ${type}`;
            
            // Set content
            titleElement.textContent = title;
            contentElement.textContent = message;
            
            // Set button properties
            button.textContent = buttonText;
            button.className = `message-form-btn ${buttonClass}`;
            
            // Show overlay
            overlay.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function hideMessageForm() {
            const overlay = document.getElementById('messageFormOverlay');
            overlay.style.display = 'none';
            document.body.style.overflow = '';
        }

        // Confirmation Form Functions (for future use)
        function showConfirmForm(message, title = 'Confirm Action', onConfirm = null, onCancel = null) {
            const overlay = document.getElementById('messageFormOverlay');
            const header = document.getElementById('messageFormHeader');
            const titleElement = document.getElementById('messageFormTitle');
            const contentElement = document.getElementById('messageFormContent');
            const buttonsContainer = document.querySelector('.message-form-buttons');

            // Set header for confirmation
            header.className = 'message-form-header warning';
            titleElement.textContent = title;
            contentElement.textContent = message;
            
            // Replace buttons container with confirmation buttons
            buttonsContainer.innerHTML = `
                <button id="confirmBtn" class="message-form-btn success">Confirm</button>
                <button id="cancelBtn" class="message-form-btn secondary">Cancel</button>
            `;
            
            // Add event listeners for confirmation buttons
            const confirmBtn = document.getElementById('confirmBtn');
            const cancelBtn = document.getElementById('cancelBtn');
            
            confirmBtn.addEventListener('click', function() {
                hideMessageForm();
                if (onConfirm) onConfirm();
            });
            
            cancelBtn.addEventListener('click', function() {
                hideMessageForm();
                if (onCancel) onCancel();
            });
            
            // Show overlay
            overlay.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        // Initialize message form event listeners
        document.addEventListener('DOMContentLoaded', function() {
            const closeBtn = document.getElementById('messageFormClose');
            const okBtn = document.getElementById('messageFormBtn');
            const overlay = document.getElementById('messageFormOverlay');

            closeBtn.addEventListener('click', hideMessageForm);
            okBtn.addEventListener('click', hideMessageForm);
            
            // Close when clicking outside the message container
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) {
                    hideMessageForm();
                }
            });
        });

        function generateReport(reportType, buttonElement) {
            // Get the button element that was clicked
            const originalText = buttonElement.innerText;
            buttonElement.innerText = 'Generating...';
            buttonElement.disabled = true;

            // Make AJAX request to generate report
            fetch('generate_report.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    report_type: reportType,
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => {
                // Check if response is ok
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Check content type
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    // If not JSON, get text to see what the error is
                    return response.text().then(text => {
                        console.error('Non-JSON response:', text);
                        throw new Error('Server returned an invalid response. Please check browser console for details.');
                    });
                }
                
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Create download links
                    const downloadSection = buttonElement.parentElement;
                    downloadSection.innerHTML += `
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #000000;">
                            <button class="download-btn" onclick="downloadFile('${data.pdf_file}')">
                                <i class="fas fa-file-pdf"></i> Download PDF
                            </button>
                            <button class="download-btn" onclick="downloadFile('${data.excel_file}')">
                                <i class="fas fa-file-excel"></i> Download Excel
                            </button>
                            <button class="download-btn" onclick="printReport('${data.pdf_file}')">
                                <i class="fas fa-print"></i> Print
                            </button>
                        </div>
                    `;
                } else {
                    showMessageForm('Error generating report: ' + data.message, 'Error', 'error', 'OK', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessageForm('Error generating report: ' + error.message, 'Error', 'error', 'OK', 'danger');
            })
            .finally(() => {
                // Restore button state
                buttonElement.innerText = originalText;
                buttonElement.disabled = false;
            });
        }

        function downloadFile(filename) {
            window.open('download_report.php?file=' + encodeURIComponent(filename), '_blank');
        }

        function printReport(filename) {
            window.open('print_report.php?file=' + encodeURIComponent(filename), '_blank');
        }

        // Comprehensive Exam Report Functions
        function loadExamReportData() {
            console.log('Loading exam report data...');
            
            // Load Academic Years
            fetch('ajax/get_academic_years.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Academic years response:', data);
                if (data.success) {
                    const academicYearSelect = document.getElementById('exam_academic_year');
                    academicYearSelect.innerHTML = '<option value="">Select Year</option>';
                    data.academic_years.forEach(year => {
                        academicYearSelect.innerHTML += `<option value="${year}">${year}</option>`;
                    });
                    console.log('Loaded', data.academic_years.length, 'academic years');
                } else {
                    console.error('Failed to load academic years:', data.message);
                }
            })
            .catch(error => {
                console.error('Error loading academic years:', error);
            });

            // Load Terms
            fetch('ajax/get_terms.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Terms response:', data);
                if (data.success) {
                    const termSelect = document.getElementById('exam_term');
                    termSelect.innerHTML = '<option value="">Select Term</option>';
                    data.terms.forEach(term => {
                        termSelect.innerHTML += `<option value="${term}">${term}</option>`;
                    });
                    console.log('Loaded', data.terms.length, 'terms');
                } else {
                    console.error('Failed to load terms:', data.message);
                }
            })
            .catch(error => {
                console.error('Error loading terms:', error);
            });

            // Load Classes
            fetch('ajax/get_classes.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const classSelect = document.getElementById('exam_class_id');
                    classSelect.innerHTML = '<option value="0">Select Class</option>';
                    data.classes.forEach(cls => {
                        classSelect.innerHTML += `<option value="${cls.class_id}">${cls.class_name}</option>`;
                    });
                }
            })
            .catch(error => console.error('Error loading classes:', error));

            // Load Grading Scales
            fetch('ajax/get_grading_scales.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Grading scales response:', data);
                if (data.success) {
                    const gradingScaleSelect = document.getElementById('exam_grading_scale');
                    gradingScaleSelect.innerHTML = '<option value="">Select Grading Scale</option>';
                    data.grading_scales.forEach(scale => {
                        gradingScaleSelect.innerHTML += `<option value="${scale.grade_name}">${scale.grade_name}</option>`;
                    });
                    console.log('Loaded', data.grading_scales.length, 'grading scales');
                } else {
                    console.error('Failed to load grading scales:', data.message);
                }
            })
            .catch(error => {
                console.error('Error loading grading scales:', error);
            });
        }

        function loadExams() {
            const academicYear = document.getElementById('exam_academic_year').value;
            const term = document.getElementById('exam_term').value;
            
            console.log('loadExams called with:', { academicYear, term });
            
            if (!academicYear || !term) {
                console.log('Academic year or term not selected, clearing exam dropdown');
                document.getElementById('exam_exam_id').innerHTML = '<option value="0">Select Exam</option>';
                return;
            }

            console.log('Fetching exams for:', academicYear, term);

            fetch('ajax/get_exams.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    school_id: <?php echo $current_user_school_id; ?>,
                    academic_year: academicYear,
                    term: term
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Exams response:', data);
                if (data.success) {
                    const examSelect = document.getElementById('exam_exam_id');
                    examSelect.innerHTML = '<option value="0">Select Exam</option>';
                    data.exams.forEach(exam => {
                        examSelect.innerHTML += `<option value="${exam.exam_id}">${exam.exam_name} (${exam.term} ${exam.year})</option>`;
                    });
                    console.log('Loaded', data.exams.length, 'exams');
                } else {
                    console.error('Failed to load exams:', data.message);
                    showMessageForm('Error loading exams: ' + data.message, 'Error', 'error', 'OK', 'danger');
                }
            })
            .catch(error => {
                console.error('Error loading exams:', error);
                showMessageForm('Network error loading exams: ' + error.message, 'Error', 'error', 'OK', 'danger');
            });
        }

        function generateComprehensiveReportCards() {
            console.log("🔥 generateComprehensiveReportCards() function called!");
            
            const academicYear = document.getElementById('exam_academic_year').value;
            const term = document.getElementById('exam_term').value;
            const examId = document.getElementById('exam_exam_id').value;
            const classId = document.getElementById('exam_class_id').value;
            const gradingScale = document.getElementById('exam_grading_scale').value;
            
            console.log("✅ Form values retrieved successfully");

            if (!academicYear || !term || !examId || examId === '0' || !classId || classId === '0' || !gradingScale) {
                showMessageForm('Please select all required fields: Academic Year, Term, Exam, Class, and Grading Scale', 'Validation Error', 'warning', 'OK', 'secondary');
                return;
            }

            const generateBtn = document.getElementById('generateExamReport');
            const printBtn = document.getElementById('printExamReport');
            const downloadBtn = document.getElementById('downloadExamReport');
            const previewDiv = document.getElementById('examReportPreview');

            // Update button states
            generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right: 8px;"></i> Generating...';
            generateBtn.disabled = true;

            // Construct URL for comprehensive report
            const reportUrl = `admin_exam_grade_reports.php?academic_year=${encodeURIComponent(academicYear)}&term=${encodeURIComponent(term)}&exam_id=${examId}&class_id=${classId}&grading_scale=${encodeURIComponent(gradingScale)}`;

            // Log the URL that will be opened - for debugging
            console.log("=== REPORT GENERATION DEBUG ===");
            console.log("Generated URL:", reportUrl);
            console.log("Parameters:");
            console.log("- Academic Year:", academicYear);
            console.log("- Term:", term);
            console.log("- Exam ID:", examId);
            console.log("- Class ID:", classId);
            console.log("- Grading Scale:", gradingScale);
            console.log("- School ID from session:", <?php echo $current_user_school_id; ?>);
            console.log("=== END DEBUG ===");

            // Show loading message and direct link
            previewDiv.style.display = 'block';
            previewDiv.innerHTML = `
                <div style="text-align: center; color: #007bff;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 3rem; margin-bottom: 15px;"></i>
                    <h4>Report is Ready!</h4>
                    <p style="margin: 15px 0;">
                        <strong>Academic Year:</strong> ${academicYear} | 
                        <strong>Term:</strong> ${term} | 
                        <strong>Class:</strong> ${document.getElementById('exam_class_id').selectedOptions[0].text}
                    </p>
                    <div style="margin: 20px 0;">
                        <button onclick="window.location.href='${reportUrl}'" style="padding: 15px 30px; background: #28a745; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1.1rem; margin-right: 10px;">
                            <i class="fas fa-eye" style="margin-right: 8px;"></i> View Report Cards
                        </button>
                        <button onclick="window.open('${reportUrl}', '_blank')" style="padding: 15px 30px; background: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1.1rem;">
                            <i class="fas fa-external-link-alt" style="margin-right: 8px;"></i> Open in New Tab
                        </button>
                    </div>
                    <p style="font-size: 0.9rem; color: #666;">Click "View Report Cards" to see the report, or "Open in New Tab" if you prefer.</p>
                </div>
            `;

            // Enable print and download buttons
            printBtn.disabled = false;
            downloadBtn.disabled = false;

            // Store report URL for print and download functions
            printBtn.onclick = () => {
                window.open(reportUrl, '_blank');
            };

            downloadBtn.onclick = () => {
                showMessageForm('PDF download functionality would be implemented here', 'Information', 'info', 'OK', 'primary');
            };

            // Restore generate button
            setTimeout(() => {
                generateBtn.innerHTML = '<i class="fas fa-chart-line" style="margin-right: 8px;"></i> Generate Report Cards';
                generateBtn.disabled = false;
            }, 2000);
        }

        // Event Listeners for Exam Report Modal
        document.addEventListener('DOMContentLoaded', function() {
            console.log("🚀 JavaScript loaded successfully!");
            
            // Add event listener for generate button
            const generateBtn = document.getElementById('generateExamReport');
            if (generateBtn) {
                console.log("✅ Generate button found, adding event listener");
                generateBtn.addEventListener('click', function(e) {
                    console.log("🎯 Generate button clicked!");
                    e.preventDefault(); // Prevent form submission
                    e.stopPropagation(); // Stop event bubbling
                    generateComprehensiveReportCards();
                });
            } else {
                console.error("❌ Generate button not found!");
            }
            // Load initial data when modal is opened
            const examModalObserver = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                        const examModal = document.getElementById('examModal');
                        if (examModal.style.display === 'block') {
                            loadExamReportData();
                        }
                    }
                });
            });

            const examModal = document.getElementById('examModal');
            if (examModal) {
                examModalObserver.observe(examModal, { attributes: true });
            }

            // Add event listeners for dropdowns
            document.getElementById('exam_academic_year').addEventListener('change', loadExams);
            document.getElementById('exam_term').addEventListener('change', loadExams);
        });

        // Modal functions
        function openModal(modalId) {
            console.log("📂 Opening modal:", modalId);
            document.getElementById(modalId).style.display = 'block';
            
            // Load exam data when exam modal is opened
            if (modalId === 'examModal') {
                loadExamReportData();
            }
        }

        function closeModal(modalId) {
            console.log("📂 Closing modal:", modalId);
            document.getElementById(modalId).style.display = 'none';
        }

        function generateReport(reportType, buttonElement) {
            console.log("📊 Generating report:", reportType);
            // Get the button element that was clicked
            const originalText = buttonElement.innerText;
            buttonElement.innerText = 'Generating...';
            buttonElement.disabled = true;

            // Make AJAX request to generate report
            fetch('generate_report.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    report_type: reportType,
                    school_id: <?php echo $current_user_school_id; ?>
                })
            })
            .then(response => {
                // Check if response is ok
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // Check content type
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    // If not JSON, get text to see what the error is
                    return response.text().then(text => {
                        console.error('Non-JSON response:', text);
                        throw new Error('Server returned an invalid response. Please check browser console for details.');
                    });
                }
                
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Create download links
                    const downloadSection = buttonElement.parentElement;
                    downloadSection.innerHTML += `
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #000000;">
                            <button class="download-btn" onclick="downloadFile('${data.pdf_file}')">
                                <i class="fas fa-file-pdf"></i> Download PDF
                            </button>
                            <button class="download-btn" onclick="downloadFile('${data.excel_file}')">
                                <i class="fas fa-file-excel"></i> Download Excel
                            </button>
                            <button class="download-btn" onclick="printReport('${data.pdf_file}')">
                                <i class="fas fa-print"></i> Print
                            </button>
                        </div>
                    `;
                } else {
                    showMessageForm('Error generating report: ' + data.message, 'Error', 'error', 'OK', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessageForm('Error generating report: ' + error.message, 'Error', 'error', 'OK', 'danger');
            })
            .finally(() => {
                // Restore button state
                buttonElement.innerText = originalText;
                buttonElement.disabled = false;
            });
        }

        function downloadFile(filename) {
            console.log("💾 Downloading file:", filename);
            window.open('download_report.php?file=' + encodeURIComponent(filename), '_blank');
        }

        function printReport(filename) {
            console.log("🖨️ Printing report:", filename);
            window.open('print_report.php?file=' + encodeURIComponent(filename), '_blank');
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target && event.target.classList && event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Menu toggle functionality
        document.getElementById('menuToggle').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('collapsed');
        });
    </script>

    <!-- Mobile Footer Navigation -->
    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="admin_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span>Dashboard</span>
                </a>
            </li>
            <li>
                <a href="admin_user_management.php" data-section="user-management">
                    <i class="fas fa-users-cog"></i>
                    <span>Users</span>
                </a>
            </li>
            <li>
                <a href="admin_messages.php" data-section="messages">
                    <i class="fas fa-envelope"></i>
                    <span>Messages</span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span>More</span>
                </a>
            </li>
        </ul>
    </div>

    <!-- More Menu Modal -->
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3>More</h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="admin_students.php"><i class="fas fa-user-graduate"></i> Students</a></li>
            <li><a href="admin_teachers.php"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
            <li><a href="admin_staff.php"><i class="fas fa-user-tie"></i> Staff</a></li>
            <li><a href="admin_classes.php"><i class="fas fa-chalkboard"></i> Classes</a></li>
            <li><a href="admin_subjects.php"><i class="fas fa-book"></i> Subjects</a></li>
            <li><a href="admin_exams.php"><i class="fas fa-file-alt"></i> Exams</a></li>
            <li><a href="admin_reports_printouts.php"><i class="fas fa-print"></i> Reports</a></li>
            <li><a href="admin_system_settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li class="logout"><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <div class="overlay" id="overlay"></div>

    <script>
        // Mobile Footer Navigation Logic
        document.addEventListener('DOMContentLoaded', function() {
            
            const moreMenuButton = document.getElementById('moreMenuButton');
            const moreMenuModal = document.getElementById('more-menu-modal');
            const moreMenuCloseBtn = document.getElementById('more-menu-close-btn');
            const overlay = document.getElementById('overlay');

            function toggleMoreMenu(show) {
                if (show) {
                    moreMenuModal.classList.add('show');
                    overlay.classList.add('show');
                    document.body.style.overflow = 'hidden';
                } else {
                    moreMenuModal.classList.remove('show');
                    overlay.classList.remove('show');
                    document.body.style.overflow = '';
                }
            }

            if (moreMenuButton) {
                moreMenuButton.addEventListener('click', (e) => {
                    e.preventDefault();
                    toggleMoreMenu(true);
                });
            }

            if (moreMenuCloseBtn) {
                moreMenuCloseBtn.addEventListener('click', () => {
                    toggleMoreMenu(false);
                });
            }

            if (overlay) {
                overlay.addEventListener('click', () => {
                    toggleMoreMenu(false);
                });
            }
        });
    </script>

</body>
</html>