<?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 translation string
$school_logo_path = "images/default_school_logo.png"; // Default if not fetched
$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;
}

$teachers = [];

// 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 and logo for header/sidebar
    $sql_school_info = "SELECT school_name, logo 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);
        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';
        }
        $stmt_school_info->close();
    } else {
        error_log("Failed to prepare school info query: " . $conn->error);
    }

    // Fetch teachers and their assigned classes/subjects
    $sql_teachers = "
        SELECT
            u.username AS teacher_name,
            u.email,
            u.phone_number,
            u.status,
            GROUP_CONCAT(DISTINCT c.class_name ORDER BY c.class_name ASC SEPARATOR ', ') AS assigned_classes,
            GROUP_CONCAT(DISTINCT s.subject_name ORDER BY s.subject_name ASC SEPARATOR ', ') AS subjects_taught
        FROM users u
        JOIN teachers t ON u.id = t.user_id AND u.school_id = t.school_id
        LEFT JOIN class_teachers ct ON u.id = ct.teacher_user_id
        LEFT JOIN classes c ON ct.class_id = c.class_id AND c.school_id = u.school_id
        LEFT JOIN teacher_subjects ts ON u.id = ts.teacher_user_id
        LEFT JOIN subjects s ON ts.subject_id = s.subject_id AND s.school_id = u.school_id
        WHERE u.school_id = ? AND u.role = ?
        GROUP BY u.id
        ORDER BY u.username ASC
    ";

    if ($stmt_teachers = $conn->prepare($sql_teachers)) {
        $teacher_role_code = ROLE_TEACHER;
        $stmt_teachers->bind_param("ii", $school_id, $teacher_role_code);
        $stmt_teachers->execute();
        $result_teachers = $stmt_teachers->get_result();
        while ($row = $result_teachers->fetch_assoc()) {
            $teachers[] = $row;
        }
        $stmt_teachers->close();
    } else {
        error_log("Failed to prepare teachers query: " . $conn->error);
    }

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teacher Reports - <?php echo $school_name; ?></title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" xintegrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <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">
    <!-- Include html2pdf.js library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <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 */
            }

            /* NEW: Hide specific columns for print */
            .print-hide-column {
                display: none !important;
            }

            /* Print Header specific styles */
            .report-header {
                display: flex;
                flex-direction: column; /* Stack elements vertically */
                align-items: flex-start; /* Align content to the left */
                margin-bottom: 1rem;
                border-bottom: 2px solid #e2e8f0;
                padding-bottom: 0.5rem;
            }
            .report-header .school-logo-print {
                max-height: 60px; /* Adjust logo size for print */
                width: auto;
                margin-bottom: 0.5rem; /* Space below logo */
            }
            .report-header .school-name-print {
                font-size: 1.5rem; /* Larger font for school name */
                font-weight: bold;
                color: #000;
                text-align: left; /* Align to left */
                width: 100%; /* Take full width */
            }
        }
        .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;
        }
        .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 #cbd5e1;
            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;
        }
        /* Custom styling for print and download buttons, now also applying to Bootstrap buttons */
        .print-button, .download-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, .download-button:hover {
            background-color: #1d4ed8;
        }

        /* Override Bootstrap's default button padding for consistency if needed */
        .btn.download-button {
            padding: 0.75rem 1.5rem; /* Ensures consistent padding with print button */
        }
    </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><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> <span class="nav-text">Students</span></a></li>
                    <li class="active"><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 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 teachers/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">Teacher Reports</h1>

                <div class="bg-white p-6 rounded-lg shadow-md mb-6 no-print flex flex-wrap gap-4 items-start">
                    <button type="button" id="printButton" class="print-button">
                        <i class="fas fa-print"></i> Print Report
                    </button>

                    <!-- Bootstrap 5 Dropdown for Download Options -->
                    <div class="dropdown">
                        <button class="btn btn-primary dropdown-toggle download-button" type="button" id="downloadTriggerButton" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-download"></i> Download List
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="downloadTriggerButton">
                            <li><button class="dropdown-item" type="button" id="downloadCsvButton"><i class="fas fa-file-csv me-2"></i> Download as CSV</button></li>
                            <li><button class="dropdown-item" type="button" id="downloadPdfButton"><i class="fas fa-file-pdf me-2"></i> Download as PDF</button></li>
                        </ul>
                    </div>
                </div>

                <div id="report-content" class="bg-white p-6 rounded-lg shadow-md">
                    <!-- Print-specific header adjusted to match requested style -->
                    <div class="report-header">
                        <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo" class="school-logo-print">
                        <h2 class="school-name-print"><?php echo $school_name; ?></h2>
                    </div>

                    <?php if (empty($teachers)): ?>
                        <p class="text-gray-500 text-center">No teachers found.</p>
                    <?php else: ?>
                        <table class="min-w-full bg-white" id="teachersTable"> <!-- Added ID to table -->
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Name</th>
                                    <th class="print-hide-column">Email</th>
                                    <th class="print-hide-column">Phone</th>
                                    <th class="print-hide-column">Status</th>
                                    <th>Assigned Classes</th>
                                    <th>Subjects Taught</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($teachers as $teacher): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($teacher['teacher_name']); ?></td>
                                        <td class="print-hide-column"><?php echo htmlspecialchars($teacher['email'] ?? 'N/A'); ?></td>
                                        <td class="print-hide-column"><?php echo htmlspecialchars($teacher['phone_number'] ?? 'N/A'); ?></td>
                                        <td class="print-hide-column"><?php echo htmlspecialchars(ucfirst($teacher['status'] ?? 'N/A')); ?></td>
                                        <td><?php echo htmlspecialchars($teacher['assigned_classes'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($teacher['subjects_taught'] ?? '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>

    <!-- Bootstrap 5 JavaScript Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" xintegrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script>
        // Your existing PHP variable for school name for JS translation
        const schoolNameForJs = "<?php echo $school_name_for_js; ?>";

        // Translations object
        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 teachers/data", // Changed for this page
                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 abasomesa/ebirango", // Changed for this page
                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 walimu/data", // Changed for this page
                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 printButton = document.getElementById('printButton');
            // DownloadTriggerButton is now controlled by Bootstrap, no direct JS toggle needed
            const downloadCsvButton = document.getElementById('downloadCsvButton');
            const downloadPdfButton = document.getElementById('downloadPdfButton');


            // 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('staffLink', 'staff'); // Added for Staff link
                updateNavLink('classesLink', 'classes');
                updateNavLink('subjectsLink', 'subjects');
                updateNavLink('gradesLink', 'grades'); // Added for Grades link
                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 Print Report button
            if (printButton) {
                printButton.addEventListener('click', function() {
                    console.log('Print button clicked! Initiating print...');
                    window.print(); // Trigger the print dialog
                });
            }

            // Handle Download as CSV
            if (downloadCsvButton) {
                downloadCsvButton.addEventListener('click', function() {
                    console.log('Download as CSV clicked! Generating CSV...');
                    // Bootstrap handles dropdown closing via data-bs-toggle on the button, so no manual close needed here.

                    const table = document.getElementById('teachersTable');
                    if (!table) {
                        console.error('Teachers table not found!');
                        return;
                    }

                    let csv = [];
                    // Get headers
                    const headers = [];
                    table.querySelectorAll('thead th').forEach(th => {
                        // Only include non-hidden columns for CSV, matching print behavior
                        if (!th.classList.contains('print-hide-column')) {
                            headers.push(th.innerText.trim());
                        }
                    });
                    csv.push(headers.join(','));

                    // Get rows
                    table.querySelectorAll('tbody tr').forEach(row => {
                        const rowData = [];
                        row.querySelectorAll('td').forEach((td, index) => {
                            // Only include data from non-hidden columns
                            const headerTh = table.querySelector(`thead th:nth-child(${index + 1})`);
                            if (headerTh && !headerTh.classList.contains('print-hide-column')) {
                                rowData.push(`"${td.innerText.trim().replace(/"/g, '""')}"`); // Quote and escape double quotes
                            }
                        });
                        csv.push(rowData.join(','));
                    });

                    const csvString = csv.join('\n');
                    const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.setAttribute('href', url);
                    link.setAttribute('download', 'teacher_list.csv');
                    link.style.visibility = 'hidden'; // Hide the link
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link); // Clean up
                    URL.revokeObjectURL(url); // Free up memory
                });
            }

            // Handle Download as PDF (using html2pdf.js)
            if (downloadPdfButton) {
                downloadPdfButton.addEventListener('click', function() {
                    console.log('Download as PDF clicked! Generating PDF using html2pdf.js...');
                    // Bootstrap handles dropdown closing via data-bs-toggle on the button, so no manual close needed here.

                    const element = document.getElementById('report-content'); // Target the report content div

                    // Options for PDF generation (can be customized)
                    const opt = {
                        margin: 10,
                        filename: 'teacher_list.pdf',
                        image: { type: 'jpeg', quality: 0.98 },
                        html2canvas: { scale: 3 }, // Increased scale for better quality
                        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
                    };

                    // Generate and download the PDF
                    html2pdf().from(element).set(opt).save();
                });
            }
        });
    </script>
</body>
</html>
