<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

// Define role constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3); // Corrected to 3
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// Function to check user role and redirect if unauthorized
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) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            case ROLE_PARENT: // Added parent redirection
                header("location: parent_dashboard.php");
                break;
            case ROLE_STAFF: // Added staff redirection
                header("location: staff_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// Call the check for Admin role
check_role_access(ROLE_ADMIN);

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

// Initialize school name and logo for header/sidebar
$school_name = "School Name Not Found"; // Default if not fetched
$school_name_for_js = "School Name Not Found"; // Default for JS
$school_logo_path = "images/default_school_logo.png"; // Default if not fetched
// Corrected photo placeholder URL
$photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD'; // Default user photo

// Determine role name for display (for header/sidebar)
$role_name = "Unknown";
switch ($_SESSION["role"]) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

$students = [];
$classes = [];
$selected_class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;

// Log the selected class ID for debugging
error_log("Selected Class ID for report: " . $selected_class_id);

// Ensure $conn is available from config.php
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch user's photo for display in header
    $sql_user_photo = "SELECT photo FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_user_photo = $conn->prepare($sql_user_photo)) {
        $stmt_user_photo->bind_param("ii", $user_id, $school_id);
        $stmt_user_photo->execute();
        $stmt_user_photo->bind_result($photo_db);
        if ($stmt_user_photo->fetch()) {
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=AD';
        }
        $stmt_user_photo->close();
    } else {
        error_log("Failed to prepare user photo query: " . $conn->error);
    }

    // Fetch school name, logo, motto and email for header/sidebar
    $sql_school_info = "SELECT school_name, logo, motto, email FROM schools WHERE school_id = ?";
    if ($stmt_school_info = $conn->prepare($sql_school_info)) {
        $stmt_school_info->bind_param("i", $school_id);
        $stmt_school_info->execute();
        $stmt_school_info->bind_result($school_name_fetched, $school_logo_fetched, $school_motto_fetched, $school_email_fetched);
        if ($stmt_school_info->fetch()) {
            $school_name = htmlspecialchars($school_name_fetched);
            $school_name_for_js = addslashes($school_name_fetched); // For JS translation string
            $school_logo_path = !empty($school_logo_fetched) ? htmlspecialchars($school_logo_fetched) : 'images/default_school_logo.png';
            $school_motto = !empty($school_motto_fetched) ? htmlspecialchars($school_motto_fetched) : '';
            $school_email = !empty($school_email_fetched) ? htmlspecialchars($school_email_fetched) : '';
        }
        $stmt_school_info->close();
    } else {
        error_log("Failed to prepare school info query: " . $conn->error);
    }

    // Fetch classes for the dropdown
    $sql_classes = "SELECT class_id, class_name FROM classes WHERE school_id = ? ORDER BY class_name ASC";
    if ($stmt_classes = $conn->prepare($sql_classes)) {
        $stmt_classes->bind_param("i", $school_id);
        $stmt_classes->execute();
        $result_classes = $stmt_classes->get_result();
        while ($row = $result_classes->fetch_assoc()) {
            $classes[] = $row;
        }
        $stmt_classes->close();
    } else {
        error_log("Failed to prepare classes query: " . $conn->error);
    }

    // Fetch students based on selected class or all students if no class selected
    $sql_students = "
        SELECT u.username, s.ADM, c.class_name, st.stream_name, u.email, u.phone_number, u.status
        FROM students s
        JOIN users u ON s.user_id = u.id AND s.school_id = u.school_id
        LEFT JOIN classes c ON s.class_id = c.class_id AND s.school_id = c.school_id
        LEFT JOIN streams st ON s.stream = st.stream_name AND s.class_id = st.class_id AND s.school_id = st.school_id
        WHERE s.school_id = ?
    ";
    $params = [$school_id];
    $types = "i";

    if ($selected_class_id > 0) {
        $sql_students .= " AND c.class_id = ?";
        $params[] = $selected_class_id;
        $types .= "i";
    }
    $sql_students .= " ORDER BY c.class_name ASC, st.stream_name ASC, u.username ASC";


    if ($stmt_students = $conn->prepare($sql_students)) {
        $stmt_students->bind_param($types, ...$params);
        $stmt_students->execute();
        $result_students = $stmt_students->get_result();
        while ($row = $result_students->fetch_assoc()) {
            $students[] = $row;
        }
        $stmt_students->close();
    } else {
        error_log("Failed to prepare students query: " . $conn->error);
    }

    $conn->close(); // Close the database connection
} else {
    error_log("Database connection \$conn not available in admin_student_reports.php");
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Reports - <?php echo $school_name; ?></title>
    <script src="https://cdn.tailwindcss.com"></script> <!-- Re-added Tailwind CSS link -->
    <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">
    <link rel="stylesheet" href="style.css">
    <style>
        @media print {
            .sidebar, .header, .mobile-footer, .no-print {
                display: none !important; /* Hide these elements completely for print */
            }
            .main-content {
                margin-left: 0 !important; /* Remove sidebar margin */
                width: 100% !important; /* Take full width */
                transform: none !important; /* Remove any transform */
                padding: 0; /* Remove padding */
            }
            #report-content {
                position: static !important; /* Reset position for normal flow */
                left: auto !important;
                top: auto !important;
                width: 100% !important;
                padding: 20px !important; /* Ensure padding inside report content */
                box-shadow: none !important; /* Remove shadow for print */
            }
            body {
                background-color: #fff !important; /* White background for print */
                color: #000 !important; /* Black text for print */
            }
            /* Ensure table borders and text are visible */
            table, th, td {
                border-color: #000 !important;
                color: #000 !important;
            }
            th {
                background-color: #f0f0f0 !important; /* Light grey header for tables */
            }
            tr:nth-child(even) {
                background-color: #f8f8f8 !important; /* Slightly different background for even rows */
            }

            /* Removed print column hiding - now using simplified table */
        }
        .report-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 1rem;
        }
        .report-header img {
            max-height: 80px;
            width: auto;
            border-radius: 0; /* Remove circular frame */
        }
        .logo img {
            border-radius: 0; /* Remove circular frame from sidebar logo */
        }
        .report-header h2 {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            text-align: right;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }
        th, td {
            border: 1px solid #000000; /* Black borders for all cells */
            padding: 0.75rem;
            text-align: left;
            font-size: 0.9rem;
            color: #334155;
        }
        th {
            background-color: #e2e8f0;
            font-weight: 600;
            color: #475569;
        }
        tr:nth-child(even) {
            background-color: #f8fafc;
        }
        .print-button {
            background-color: #2563eb;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .print-button:hover {
            background-color: #1d4ed8;
        }
        /* No redundant sidebar/header/dashboard-container styles here as they are in style.css */
    </style>
</head>
<body class="bg-gray-100 font-sans">

    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
               <h4> DIVINE REPORTS</h4>
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> <span class="nav-text">Dashboard</span></a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> <span class="nav-text">Calendar</span></a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> <span class="nav-text">Users</span></a></li>
                    <li class="active"><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <span class="nav-text">Students</span></a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> <span class="nav-text">Teachers</span></a></li>
                    <li class="hidden md:block"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> <span class="nav-text">Classes</span></a></li>
                    <li class="hidden md:block"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> <span class="nav-text">Subjects</span></a></li>
                    <li><a href="admin_grades.php" id="gradesLink"><i class="fas fa-star"></i> <span class="nav-text">Grades</span></a></li>
                    <li class="hidden md:block"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> <span class="nav-text">Exams</span></a></li>
                    <li class="hidden md:block"><a href="admin_messages.php" id="messagesLinkSidebar"><i class="fas fa-envelope"></i> <span class="nav-text">Messages</span></a></li>
                    <li><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> <span class="nav-text">Printouts</span></a></li>
                    <li class="hidden md:block"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> <span class="nav-text">Settings</span></a></li>
                    <li class="hidden md:block"><a href="logout.php" class="logout-btn" id="logoutLinkSidebar"><i class="fas fa-sign-out-alt"></i> <span class="nav-text">Logout</span></a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <!-- Header Section -->
            <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: <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="content-area p-6">
                <h1 class="text-3xl font-bold text-gray-800 mb-6 no-print">Student Reports</h1>

                <div class="bg-white p-6 rounded-lg shadow-md mb-6 no-print">
                    <form action="admin_student_reports.php" method="GET" class="flex flex-col md:flex-row items-center gap-4" id="reportFilterForm">
                        <div class="flex-grow w-full">
                            <label for="class_id" class="block text-sm font-medium text-gray-700 mb-1">Filter by Class:</label>
                            <select id="class_id" name="class_id" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                                <option value="0">All Classes</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo htmlspecialchars($class['class_id']); ?>" <?php echo ($selected_class_id == $class['class_id'] ? 'selected' : ''); ?>>
                                        <?php echo htmlspecialchars($class['class_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" name="generate_report_btn" class="mt-4 md:mt-0 px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition duration-150 ease-in-out">
                            Generate 
                        </button>
                        <button type="button" id="printButton" class="mt-4 md:mt-0 print-button">
                            <i class="fas fa-print"></i> Print 
                        </button>
                    </form>
                </div>

                <div id="report-content" class="bg-white p-6 rounded-lg shadow-md">
                    <div class="report-header">
                        <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                        <div class="text-right">
                            <h2 class="text-right font-bold text-xl"><?php echo $school_name; ?></h2>
                            <?php if (!empty($school_motto)): ?>
                                <p class="text-gray-600 text-sm text-right italic"><?php echo $school_motto; ?></p>
                            <?php endif; ?>
                            <?php if (!empty($school_email)): ?>
                                <p class="text-gray-600 text-sm text-right"><?php echo $school_email; ?></p>
                            <?php endif; ?>
                            <p class="text-gray-600 text-sm text-right mt-2">Student List Report</p>
                            <?php if ($selected_class_id > 0 && !empty($classes)): ?>
                                <?php
                                    $selected_class_name = "N/A";
                                    foreach ($classes as $class) {
                                        if ($class['class_id'] == $selected_class_id) {
                                            $selected_class_name = $class['class_name'];
                                            break;
                                        }
                                    }
                                ?>
                                <p class="text-gray-600 text-sm text-right">For Class: <span class="font-semibold"><?php echo htmlspecialchars($selected_class_name); ?></span></p>
                            <?php else: ?>
                                <p class="text-gray-600 text-sm text-right">For All Classes</p>
                            <?php endif; ?>
                            <p class="text-gray-600 text-xs text-right">Date: <?php echo date('F j, Y'); ?></p>
                        </div>
                    </div>

                    <?php if (empty($students)): ?>
                        <p class="text-gray-500 text-center">No students found for the selected criteria.</p>
                    <?php else: ?>
                        <!-- SIMPLIFIED TABLE WITH ONLY 4 COLUMNS -->
                        <table style="width: 100%; border-collapse: collapse; border: 2px solid black;">
                            <thead>
                                <tr>
                                    <th style="border: 1px solid black; padding: 8px; background-color: #f0f0f0;">Admission Number</th>
                                    <th style="border: 1px solid black; padding: 8px; background-color: #f0f0f0;">Student Name</th>
                                    <th style="border: 1px solid black; padding: 8px; background-color: #f0f0f0;">Class</th>
                                    <th style="border: 1px solid black; padding: 8px; background-color: #f0f0f0;">Stream</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students as $student): ?>
                                    <tr>
                                        <td style="border: 1px solid black; padding: 8px;"><?php echo htmlspecialchars($student['ADM']); ?></td>
                                        <td style="border: 1px solid black; padding: 8px;"><?php echo htmlspecialchars($student['username']); ?></td>
                                        <td style="border: 1px solid black; padding: 8px;"><?php echo htmlspecialchars($student['class_name'] ?? 'N/A'); ?></td>
                                        <td style="border: 1px solid black; padding: 8px;"><?php echo htmlspecialchars($student['stream_name'] ?? 'N/A'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Footer -->
    <footer class="mobile-footer">
        <nav>
            <ul>
                <li><a href="admin_profile.php" id="profileLinkFooter"><i class="fas fa-user-circle"></i> <span id="profileTextFooter">Profile</span></a></li>
                <li><a href="admin_settings.php" id="settingsLinkFooter"><i class="fas fa-cog"></i> <span id="settingsTextFooter">Settings</span></a></li>
                <li><a href="logout.php" id="logoutLinkFooter"><i class="fas fa-sign-out-alt"></i> <span id="logoutTextFooter">Logout</span></a></li>
            </ul>
        </nav>
    </footer>

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

    <script>
        // Your existing PHP variable for school name for JS translation
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";

        // Translations object (ensure it's comprehensive in your actual style.css related JS file)
        const translations = {
            en: {
                dashboard: "Dashboard",
                calendar: "Calendar",
                users: "Users",
                students: "Students",
                teachers: "Teachers",
                classes: "Classes",
                subjects: "Subjects",
                exams: "Exams",
                messages: "Messages",
                printouts: "Printouts",
                systemSettings: "Settings",
                logout: "Logout",
                searchPlaceholder: "Search students/data",
                welcomePrefix: "Welcome ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Manage all aspects of ${schoolNameForJs} school operations.`,
                totalStudents: "Total Students",
                totalTeachers: "Total Teachers",
                totalClasses: "Total Classes",
                unreadMessages: "Unread Messages",
                examAnalysis: "Exam Analysis",
                classLabel: "Class",
                subjectLabel: "Subject",
                avgScoreLabel: "Avg. Score",
                overallClassPerformance: "Overall Class Performance Graph",
                noExamData: "No exam analysis data available for your school.",
                noChartData: "No data available to generate class performance graph.",
                monthView: "Month",
                mon: "Mon",
                tue: "Tue",
                wed: "Wed",
                thu: "Thu",
                fri: "Fri",
                sat: "Sat",
                sun: "Sun",
                monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                // Mobile footer translations
                profileTextFooter: "Profile",
                settingsTextFooter: "Settings",
                logoutTextFooter: "Logout"
            },
            // Example Luganda translations (add full translations as needed)
            lg: {
                dashboard: "Akawungeezi",
                calendar: "Kalenada",
                users: "Abakozesa",
                students: "Abayizi",
                teachers: "Basomesa",
                classes: "Ebibiina",
                subjects: "Ebizibu",
                exams: "Eby'okugezesa",
                messages: "Ebirango",
                printouts: "Ebiwandiiko",
                systemSettings: "Enkola",
                logout: "Ggwe",
                searchPlaceholder: "Noonya abayizi/ebirango",
                welcomePrefix: "Mukulike ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Fuga ebintu byonna mu ${schoolNameForJs} ebya buli lunaku.`,
                totalStudents: "Abayizi Bonna",
                totalTeachers: "Basomesa Bonna",
                totalClasses: "Ebibiina Byonna",
                unreadMessages: "Ebirango Ebitasomeddwa",
                // ... add other translations
                profileTextFooter: "Profayiro",
                settingsTextFooter: "Enkola",
                logoutTextFooter: "Ggwe"
            },
            // Example Kiswahili translations (add full translations as needed)
            sw: {
                dashboard: "Dashibodi",
                calendar: "Kalenda",
                users: "Watumiaji",
                students: "Wanafunzi",
                teachers: "Walimu",
                classes: "Madarasa",
                subjects: "Masomo",
                exams: "Mitihani",
                messages: "Ujumbe",
                printouts: "Machapisho",
                systemSettings: "Mipangilio",
                logout: "Ondoka",
                searchPlaceholder: "Tafuta wanafunzi/data",
                welcomePrefix: "Karibu ",
                welcomeSuffix: "!",
                manageSchoolOperations: `Dhibiti shughuli zote za shule ya ${schoolNameForJs}.`,
                totalStudents: "Jumla ya Wanafunzi",
                totalTeachers: "Jumla ya Walimu",
                totalClasses: "Jumla ya Madarasa",
                unreadMessages: "Ujumbe Usiosomwa",
                // ... add other translations
                profileTextFooter: "Profaili",
                settingsTextFooter: "Mipangilio",
                logoutTextFooter: "Ondoka"
            }
        };

        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');
            const overlay = document.getElementById('overlay');
            const reportFilterForm = document.getElementById('reportFilterForm'); // Get the form
            const printButton = document.getElementById('printButton'); // Get the print button

            // Function to update texts based on selected language
            function updateTexts(lang) {
                const currentTranslations = translations[lang] || translations.en;

                // Sidebar links
                const updateNavLink = (id, translationKey) => {
                    const linkElement = document.getElementById(id);
                    if (linkElement) {
                        const spanElement = linkElement.querySelector('.nav-text');
                        if (spanElement) {
                            spanElement.textContent = currentTranslations[translationKey];
                        }
                    }
                };

                updateNavLink('dashboardLink', 'dashboard');
                updateNavLink('calendarLink', 'calendar');
                updateNavLink('usersLink', 'users');
                updateNavLink('studentsLink', 'students');
                updateNavLink('teachersLink', 'teachers');
                updateNavLink('classesLink', 'classes');
                updateNavLink('subjectsLink', 'subjects');
                updateNavLink('examsLink', 'exams');
                updateNavLink('messagesLinkSidebar', 'messages');
                updateNavLink('printoutsLink', 'printouts');
                updateNavLink('systemSettingsLink', 'systemSettings');
                updateNavLink('logoutLinkSidebar', 'logout');


                // Header search placeholder
                const searchPlaceholder = document.getElementById('searchPlaceholder');
                if (searchPlaceholder) {
                    searchPlaceholder.placeholder = currentTranslations.searchPlaceholder;
                }

                // Mobile Footer
                const profileTextFooter = document.getElementById('profileTextFooter');
                if (profileTextFooter) {
                    profileTextFooter.textContent = currentTranslations.profileTextFooter;
                }
                const settingsTextFooter = document.getElementById('settingsTextFooter');
                if (settingsTextFooter) {
                    settingsTextFooter.textContent = currentTranslations.settingsTextFooter;
                }
                const logoutTextFooter = document.getElementById('logoutTextFooter');
                if (logoutTextFooter) {
                    logoutTextFooter.textContent = currentTranslations.logoutTextFooter;
                }
            }


            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                dashboardContainer.classList.toggle('sidebar-open');
                overlay.classList.toggle('active');
            });

            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                dashboardContainer.classList.remove('sidebar-open');
                overlay.classList.remove('active');
            });

            // Handle language selection if element exists
            const languageSelect = document.getElementById('languageSelect');
            if (languageSelect) {
                languageSelect.addEventListener('change', function() {
                    updateTexts(this.value);
                });
                // Initial update based on default language
                updateTexts(languageSelect.value);
            }

            // Event listener for the form submission
            if (reportFilterForm) {
                reportFilterForm.addEventListener('submit', function(event) {
                    console.log('Report filter form submitted!');
                    // The form will naturally submit via GET, so no need for event.preventDefault()
                });
            }

            // Event listener for the Print Report button
            if (printButton) {
                printButton.addEventListener('click', function() {
                    console.log('Print button clicked! Initiating print...');
                    window.print(); // Trigger the print dialog
                });
            }
        });
    </script>
</body>
</html>
