<?php
session_start(); // Start the session to access session variables

require_once 'config.php'; // Include the database configuration file. Ensure this path is correct.

// Define role constants.
// IMPORTANT: Ensure these role codes are consistent across your entire application.
// Based on the provided code and comments, ROLE_TEACHER is set to 2.
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', 2); // Set to 2 as per your existing code's explicit comment
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// --- Language Handling and Localization Dictionary ---
$available_languages = ['en', 'lug', 'sw']; // English, Luganda, Kiswahili
$default_language = 'en';

// Check if a language is selected via GET parameter; otherwise, use session or default.
if (isset($_GET['lang']) && in_array($_GET['lang'], $available_languages)) {
    $_SESSION['lang'] = $_GET['lang'];
} elseif (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = $default_language;
}

$current_lang = $_SESSION['lang'];

/**
 * Loads language-specific strings. In a larger application, these would typically
 * be loaded from separate files (e.g., lang/en.php, lang/lug.php).
 * For this example, a simplified array is used.
 * @param string $lang The current language code.
 * @return array An associative array of localized strings.
 */
function load_language_data($lang) {
    $data = [
        'en' => [
            'dashboard_title_prefix' => 'Dashboard',
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_my_classes' => 'My Classes',
            'sidebar_my_students' => 'My Students',
            'sidebar_assignments' => 'Assignments',
            'sidebar_grades' => 'Grades',
            'sidebar_messages' => 'Messages',
            'sidebar_calendar' => 'Calendar',
            'sidebar_profile' => 'Profile',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search students/data',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'manage_records_text' => 'Manage your classes, students, and academic records for',
            'view_my_classes_button' => 'View My Classes',
            'stat_students_label' => 'Students in My Classes',
            'stat_assignments_label' => 'Assignments to Grade',
            'stat_messages_label' => 'Unread Messages',
            'stat_lessons_label' => 'Upcoming Lessons',
            'school_announcements_heading' => 'School Announcements',
            'view_all_button' => 'View All',
            'no_announcements' => 'No new school announcements.',
            'calendar_month_button' => 'Month',
            'calendar_week_button' => 'Week',
            'calendar_day_button' => 'Day',
            'day_mon' => 'Mon', 'day_tue' => 'Tue', 'day_wed' => 'Wed', 'day_thu' => 'Thu',
            'day_fri' => 'Fri', 'day_sat' => 'Sat', 'day_sun' => 'Sun',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS'
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Diisiboodi',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_my_classes' => 'Ebibiina Byange',
            'sidebar_my_students' => 'Bayizi Bange',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_grades' => 'Akaadi',
            'sidebar_messages' => 'Obubaka',
            'sidebar_calendar' => 'Kkalenda',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly’Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya abayizi/data',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'manage_records_text' => 'Kola ku bibiina byo, abayizi, n’ebyafaayo byabwe mu',
            'view_my_classes_button' => 'Laba Ebibiina Byange',
            'stat_students_label' => 'Abayizi mu Bifo Byange',
            'stat_assignments_label' => 'Ebitongole Ebirindiridde Okukolebwa',
            'stat_messages_label' => 'Obubaka Obutatukirwako',
            'stat_lessons_label' => 'Ensiriki Zili Mumaaso',
            'school_announcements_heading' => 'Amanyisibwa g’Essomero',
            'view_all_button' => 'Laba Byonna',
            'no_announcements' => 'Tewali manyisibwa mafulu.',
            'calendar_month_button' => 'Omwezi',
            'calendar_week_button' => 'Wiki',
            'calendar_day_button' => 'Olunaku',
            'day_mon' => 'Bal', 'day_tue' => 'Bbi', 'day_wed' => 'Ggo', 'day_thu' => 'Nna',
            'day_fri' => 'Muu', 'day_sat' => 'Lwa', 'day_sun' => 'San',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU'
        ],
        'sw' => [
            'dashboard_title_prefix' => 'Dashibodi',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_my_classes' => 'Madarasa Yangu',
            'sidebar_my_students' => 'Wanafunzi Wangu',
            'sidebar_assignments' => 'Kazi',
            'sidebar_grades' => 'Alama',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_calendar' => 'Kalenda',
            'sidebar_profile' => 'Wasifu',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta wanafunzi/data',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'manage_records_text' => 'Dhibiti madarasa yako, wanafunzi, na rekodi za masomo kwa',
            'view_my_classes_button' => 'Tazama Madarasa Yangu',
            'stat_students_label' => 'Wanafunzi Katika Madarasa Yangu',
            'stat_assignments_label' => 'Kazi Zinazosubiri Kukaguliwa',
            'stat_messages_label' => 'Ujumbe Usiomaswa',
            'stat_lessons_label' => 'Masomo Yajayo',
            'school_announcements_heading' => 'Matangazo ya Shule',
            'view_all_button' => 'Tazama Yote',
            'no_announcements' => 'Hakuna matangazo mapya ya shule.',
            'calendar_month_button' => 'Mwezi',
            'calendar_week_button' => 'Wiki',
            'calendar_day_button' => 'Siku',
            'day_mon' => 'Jt', 'day_tue' => 'Jnn', 'day_wed' => 'Jtatu', 'day_thu' => 'Jne',
            'day_fri' => 'Ij', 'day_sat' => 'Jmo', 'day_sun' => 'Jpili',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU'
        ]
    ];
    return $data[$lang] ?? $data['en']; // Fallback to English if language not found
}

$_L = load_language_data($current_lang);

/**
 * Function to check the user's role and redirect if they are unauthorized to access the current page.
 * @param int $required_role_code The role code required to access this page.
 */
function check_role_access($required_role_code) {
    // Check if the user is logged in and has a school_id in their session.
    // If not, redirect to the login page.
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit; // Terminate script execution after redirection
    }

    // Check if the user's current role matches the required role for this page.
    if ($_SESSION["role"] !== $required_role_code) {
        // If roles don't match, redirect the user to their respective dashboard based on their actual role.
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            default: // Catch-all for any other unexpected or undefined roles
                header("location: login.php"); // Redirect to login for unknown roles
                break;
        }
        exit; // Terminate script execution after redirection
    }
}

// !! CRITICAL: Call the check for Teacher role to ensure only teachers can access this page !!
check_role_access(ROLE_TEACHER);

// This variable is used by the sidebar to highlight the active link in the navigation.
$currentPage = 'profile';

// User is authorized, now fetch additional details for display on the dashboard.
$user_id = $_SESSION["id"]; // Get the user's ID from the session.
$username = htmlspecialchars($_SESSION["username"]); // Sanitize username for safe display to prevent XSS.
$user_role_code = $_SESSION["role"]; // Get the numeric role code from the session.
$current_user_school_id = $_SESSION["school_id"]; // Get the school ID associated with the logged-in user.

// Initialize teacher and school details with default values.
$teacher_phone = "N/A";
$teacher_email = "N/A";
$teacher_photo = "images/default_teacher_photo.png"; // Default local photo if none found in DB
$teacher_status = "N/A";

$school_name = $_L['school_name_not_found']; // Default school name if not fetched.
$school_logo_path = "images/default_school_logo.png"; // Default logo path.
$school_address = "N/A";
$school_contact_phone = "N/A";
$school_contact_email = "N/A";
$school_motto = "N/A";
$school_website = "N/A";

// Determine the human-readable role name for display purposes.
$role_name = "Unknown";
switch ($user_role_code) {
    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;
}

// Fetch teacher and school data from database
if (isset($conn) && $conn instanceof mysqli) {
    // Fetch teacher details from users table
    $sql_teacher_details = "SELECT phone_number, email, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_teacher = $conn->prepare($sql_teacher_details)) {
        $stmt_teacher->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_teacher->execute()) {
            $stmt_teacher->bind_result($phone_db, $email_db, $photo_db, $status_db);
            if ($stmt_teacher->fetch()) {
                $teacher_phone = htmlspecialchars($phone_db ?? 'N/A');
                $teacher_email = htmlspecialchars($email_db ?? 'N/A');
                // Use fetched photo if available and not empty, otherwise use local default
                $teacher_photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'images/default_teacher_photo.png';
                $teacher_status = htmlspecialchars($status_db ?? 'N/A');
            } else {
                error_log("Teacher details not found for user_id: " . $user_id);
            }
        } else {
            error_log("Execute failed for teacher details query: " . $stmt_teacher->error);
        }
        $stmt_teacher->close();
    } else {
        error_log("Prepare failed for teacher details query: " . $conn->error);
    }

    // Fetch school details
    $sql_school_details = "SELECT school_name, logo, address, phone, email, motto, website FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school_details)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db, $address_db, $school_phone_db, $email_db, $motto_db, $website_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_address = htmlspecialchars($address_db ?? 'N/A');
                $school_contact_phone = htmlspecialchars($school_phone_db ?? 'N/A');
                $school_contact_email = htmlspecialchars($email_db ?? 'N/A');
                $school_motto = htmlspecialchars($motto_db ?? 'N/A');
                $school_website = htmlspecialchars($website_db ?? 'N/A');
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school details query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school details query: " . $conn->error);
    }

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

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $_L['sidebar_profile']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css"> <!-- Link to the main stylesheet -->
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png"> <!-- School logo as favicon -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Font Awesome for icons (using 5.15.4 for consistency with dashboard) -->
    <!-- Custom styles for the ID card look (moved here from inline) -->
    <style>
    /* Fixed Header and Sidebar Layout */
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100vh;
        }

        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
            width: 250px;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            margin-left: 250px;
            overflow: hidden;
        }

        .header {
            position: fixed;
            top: 0;
            left: 250px;
            right: 0;
            z-index: 900;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        /* Scrollable content area */
        .main-content > div:not(.header) {
            margin-top: 80px;
            overflow-y: auto;
            flex: 1;
            padding-bottom: 20px;
        }

        /* Mobile adjustments */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }

            .sidebar.active {
                transform: translateX(0);
            }

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

            .header {
                left: 0;
            }

            .main-content > div:not(.header) {
                padding-bottom: 110px !important;
            }
        }

        
        .id-card-container {
            display: flex;
            flex-direction: row; /* Display side-by-side */
            flex-wrap: wrap; /* Allow wrapping on smaller screens */
            gap: 2rem; /* Space between cards */
            max-width: 840px; /* 2 * 400px (card width) + 2rem (gap) */
            margin: 2rem auto; /* Center the container */
            justify-content: center; /* Center cards horizontally */
            align-items: flex-start; /* Align cards to the top */
        }

        .id-card-front, .id-card-back {
            background: linear-gradient(135deg, #e0f2f7, #ccecf5); /* Consistent light blue gradient */
            border: 1px solid #a7d9f7;
            border-radius: 1.5rem;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1), 0 5px 10px rgba(0, 0, 0, 0.05);
            padding: 1.5rem;
            width: 400px; /* Fixed width for landscape */
            height: 600px; /* Increased height to prevent QR code cutting */
            flex-shrink: 0; /* Prevent shrinking when in a flex container */
            position: relative;
            overflow: hidden;
            font-family: 'Poppins', sans-serif; /* Using Poppins for consistency */
            color: #334155;
            display: flex;
            flex-direction: column; /* Keep internal content vertical flow */
            justify-content: space-between; /* Distribute content vertically */
        }

        .id-card-back {
            /* Now exactly the same as front in terms of size, background, border, shadow */
            /* Internal layout adjusted to mimic front */
        }

        /* Vertical "TEACHER ID" text (only on front) */
        .vertical-text {
            position: absolute;
            top: 50%;
            right: -20px; /* Move slightly outside to ensure full text is visible after rotation */
            transform: translateY(-50%) rotate(90deg);
            transform-origin: center right; /* Rotate around the right edge, centered vertically */
            font-size: 2.2rem; /* Slightly smaller for better fit */
            font-weight: 900;
            color: rgba(59, 130, 246, 0.3); /* Lighter transparency */
            letter-spacing: 0.1em; /* Slightly less letter spacing */
            text-transform: uppercase;
            white-space: nowrap;
            opacity: 0.8; /* Slightly more opaque */
            z-index: 10; /* Ensure it's above other content if needed */
        }

        .id-card-header {
            display: flex;
            align-items: center;
            justify-content: flex-start; /* Align to start */
            padding-bottom: 1rem;
            margin-bottom: 1rem;
            border-bottom: 2px solid #a7d9f7; /* Light blue border */
        }
        .id-card-header img {
            max-width: 70px; /* Smaller logo */
            height: auto;
            margin-right: 1rem; /* Space between logo and text */
            border-radius: 0.5rem;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .school-name-text {
            text-align: left;
            line-height: 1.2;
        }
        .school-name-text h2 {
            font-size: 1.5rem; /* Smaller for two lines */
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.2rem;
        }
        .school-name-text p {
            font-size: 0.85rem;
            color: #475569;
        }

        .main-content-area {
            display: flex;
            align-items: flex-start; /* Align items to the top */
            gap: 1.5rem; /* Space between photo and details */
            flex-grow: 1; /* Allow this section to grow */
        }
        .profile-photo {
            width: 120px;
            height: 120px;
            border-radius: 0.75rem; /* Rounded corners for photo */
            object-fit: cover;
            border: 4px solid #a7d9f7;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
            flex-shrink: 0; /* Prevent photo from shrinking */
        }
        .teacher-details {
            text-align: left;
            flex-grow: 1;
        }
        .teacher-details h3 {
            font-size: 1.75rem; /* text-3xl equivalent */
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        .teacher-details p {
            font-size: 1.1rem; /* Larger for role */
            font-weight: 600;
            color: #3b82f6; /* Blue 500 */
            margin-bottom: 1rem;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.3rem 0; /* Reduced padding */
            border-bottom: 1px dashed #e2e8f0;
            font-size: 0.95rem; /* Slightly smaller font */
        }
        .info-item:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #475569;
            flex: 1;
            text-align: left;
        }
        .info-value {
            color: #334155;
            flex: 2;
            text-align: right;
            word-break: break-all; /* Break long words like email */
        }

        .qr-code-container {
            margin-top: auto; /* Pushes to bottom */
            padding-top: 1rem;
            border-top: 2px solid #cbd5e1;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .qr-code-container canvas {
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 0.5rem;
            background-color: white;
        }
        .footer-status {
            margin-top: 0.5rem; /* Reduced margin */
            padding-top: 0.5rem; /* Reduced padding */
            border-top: 2px solid #cbd5e1;
            font-size: 0.9rem;
            color: #64748b;
        }
        .footer-status span {
            font-weight: 700;
            color: #10b981;
        }
        .footer-status span.inactive {
            color: #ef4444;
        }
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin-top: 2rem;
        }
        .action-buttons button {
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .action-buttons button.download-btn {
            background-color: #3b82f6;
            color: white;
        }
        .action-buttons button.download-btn:hover {
            background-color: #2563eb;
            box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
        }
        .action-buttons button.print-btn {
            background-color: #6b7280;
            color: white;
        }
        .action-buttons button.print-btn:hover {
            background-color: #4b5563;
            box-shadow: 0 4px 10px rgba(107, 114, 128, 0.3);
        }

        /* Styles for the back of the card - adjusted to match front layout */
        .school-details-back-content {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
            text-align: left; /* Align text to left within this section */
        }
        .school-details-back-content .school-logo-back {
            width: 120px; /* Match teacher photo size */
            height: 120px; /* Match teacher photo size */
            object-fit: contain; /* Use contain for logos to prevent cropping */
            border-radius: 0.75rem;
            border: 4px solid #a7d9f7;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
            margin: 0 auto 1.5rem auto; /* Center and add margin */
        }
        .school-details-back-content .school-motto {
            font-style: italic;
            margin-top: 0.5rem;
            margin-bottom: 1rem;
            color: #64748b;
            text-align: center; /* Center motto */
            font-size: 1.1rem; /* Match role font size */
            font-weight: 600;
        }
        .school-details-back-content .info-section {
            width: 100%;
            padding: 0 0; /* Remove horizontal padding as info-item handles it */
        }
        /* Re-using info-item, info-label, info-value from front */
        .school-details-back-content .info-label i {
            margin-right: 0.5rem;
            color: #3b82f6; /* Consistent icon color */
        }
        .school-details-back-content .school-website-link {
            color: #3b82f6;
            text-decoration: underline;
            margin-top: auto; /* Push to bottom */
            display: block;
            text-align: center;
            padding-top: 1rem;
            border-top: 2px solid #cbd5e1;
        }
        .school-details-back-content .school-website-link i {
            margin-right: 0.5rem;
        }


        /* Print-specific styles */
        @media print {
            body {
                background-color: #fff;
            }
            .id-card-container {
                box-shadow: none;
                border: none;
                margin: 0;
                flex-direction: row; /* Try to keep them side-by-side */
                justify-content: center;
                align-items: flex-start;
                gap: 1rem; /* Smaller gap for print */
            }
            .id-card-front, .id-card-back {
                box-shadow: none;
                border: 1px solid #ccc;
                margin-bottom: 0; /* No extra margin between cards on print */
                page-break-inside: avoid; /* Avoid breaking card across pages */
            }
            .container, .main-content, .dashboard-container {
                margin: 0 !important;
                padding: 0 !important;
                width: 100% !important;
                max-width: none !important;
            }
            .teacher-navbar, .action-buttons, h1, .sidebar, .header { /* Hide all navigation elements for print */
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <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 class="<?php echo ($currentPage == 'dashboard' ? 'active' : ''); ?>"><a href="teacher_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'my_classes' ? 'active' : ''); ?>"><a href="teacher_my_classes.php"><i class="fas fa-chalkboard"></i> <?php echo $_L['sidebar_my_classes']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'my_students' ? 'active' : ''); ?>"><a href="teacher_my_students.php"><i class="fas fa-user-graduate"></i> <?php echo $_L['sidebar_my_students']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'assignments' ? 'active' : ''); ?>"><a href="create_assignment.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'grades' ? 'active' : ''); ?>"><a href="teacher_exams.php"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'messages' ? 'active' : ''); ?>"><a href="teacher_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'calendar' ? 'active' : ''); ?>"><a href="teacher_calendar.php"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'profile' ? 'active' : ''); ?>"><a href="teacher_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'settings' ? 'active' : ''); ?>"><a href="teacher_settings.php"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
                    <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_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="languageSelector" onchange="changeLanguage(this.value)">
                           <option value="en" <?php if ($current_lang === 'en') echo 'selected'; ?>>🇬🇧 English</option>
                           <option value="lug" <?php if ($current_lang === 'lug') echo 'selected'; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php if ($current_lang === 'sw') echo 'selected'; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $_L['search_placeholder']; ?>">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span> <!-- Hardcoded notification count -->
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $teacher_photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?php echo $_L['logged_in_as']; ?> <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="container mx-auto mt-8 p-6">
                <h1 class="text-4xl font-extrabold text-gray-900 text-center mb-8">My Profile</h1>

                <div class="id-card-container" id="idCardContainer">
                    <div class="id-card-front" id="teacherIdCardFront">
                        <div class="vertical-text">Teacher ID</div>
                        <div class="id-card-header">
                            <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo" class="w-20 h-auto rounded-xl shadow-md">
                            <div class="school-name-text">
                                <h2><?php echo $school_name; ?></h2>
                                <p>OFFICIAL TEACHER ID</p>
                            </div>
                        </div>

                        <div class="main-content-area">
                            <img src="<?php echo $teacher_photo; ?>" alt="Teacher Photo" class="profile-photo">
                            <div class="teacher-details">
                                <h3 class="text-2xl font-bold text-gray-900 mb-1"><?php echo $username; ?></h3>
                                <p class="text-xl font-semibold text-blue-700 mb-3"><?php echo $role_name; ?></p>

                                <div class="info-section text-left">
                                    <div class="info-item">
                                        <span class="info-label">ID No:</span>
                                        <span class="info-value"><?php echo htmlspecialchars($user_id); ?></span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">Email:</span>
                                        <span class="info-value"><?php echo $teacher_email; ?></span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">Phone:</span>
                                        <span class="info-value"><?php echo $teacher_phone; ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="qr-code-container">
                            <div id="qrcode"></div>
                            <p class="text-gray-600 text-xs mt-2">Scan for details</p>
                        </div>

                        <div class="footer-status">
                            Status: <span class="<?php echo ($teacher_status === 'active' ? 'text-green-600' : 'text-red-600'); ?> font-bold"><?php echo htmlspecialchars(ucfirst($teacher_status)); ?></span>
                        </div>
                    </div>

                    <div class="id-card-back" id="teacherIdCardBack">
                        <div class="id-card-header">
                            <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo" class="w-20 h-auto rounded-xl shadow-md">
                            <div class="school-name-text">
                                <h2><?php echo $school_name; ?></h2>
                                <p>SCHOOL INFORMATION</p>
                            </div>
                        </div>

                        <div class="school-details-back-content">
                            <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo" class="school-logo-back">
                            <p class="school-motto">"<?php echo $school_motto; ?>"</p>

                            <div class="info-section">
                                <div class="info-item">
                                    <span class="info-label"><i class="fas fa-map-marker-alt"></i>Address:</span>
                                    <span class="info-value"><?php echo $school_address; ?></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label"><i class="fas fa-phone"></i>Phone:</span>
                                    <span class="info-value"><?php echo $school_contact_phone; ?></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label"><i class="fas fa-envelope"></i>Email:</span>
                                    <span class="info-value"><?php echo $school_contact_email; ?></span>
                                </div>
                                <?php if ($school_website !== 'N/A'): ?>
                                    <div class="info-item">
                                        <span class="info-label"><i class="fas fa-globe"></i>Website:</span>
                                        <span class="info-value"><a href="<?php echo $school_website; ?>" target="_blank" class="text-blue-600 hover:underline"><?php echo $school_website; ?></a></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="footer-status">
                            <p>For official use only. Do not duplicate.</p>
                        </div>
                    </div>
                </div>

                <div class="action-buttons">
                    <button id="downloadCardBtn" class="download-btn">
                        <i class="fas fa-download"></i> Download as Image
                    </button>
                    <button id="printCardBtn" class="print-btn">
                        <i class="fas fa-print"></i> Print Card
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="js/qrcode.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script>
        // Function to change language
        function changeLanguage(lang) {
            window.location.href = `?lang=${lang}`;
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Get PHP variables into JavaScript
            const teacherName = "<?php echo $username; ?>";
            const userId = "<?php echo $user_id; ?>";
            const schoolName = "<?php echo $school_name; ?>";
            const roleName = "<?php echo $role_name; ?>";
            const teacherEmail = "<?php echo $teacher_email; ?>";
            const teacherPhone = "<?php echo $teacher_phone; ?>";
            const teacherStatus = "<?php echo htmlspecialchars(ucfirst($teacher_status)); ?>";

            // School details for the back of the card
            const schoolAddress = "<?php echo $school_address; ?>";
            const schoolContactPhone = "<?php echo $school_contact_phone; ?>";
            const schoolContactEmail = "<?php echo $school_contact_email; ?>";
            const schoolMotto = "<?php echo $school_motto; ?>";
            const schoolWebsite = "<?php echo $school_website; ?>";

            // Data to encode in the QR code - now includes back card details and teacher status
            const qrData = `Teacher Name: ${teacherName}\n` +
                           `User ID: ${userId}\n` +
                           `Role: ${roleName}\n` +
                           `Teacher Email: ${teacherEmail}\n` +
                           `Teacher Phone: ${teacherPhone}\n` +
                           `Status: ${teacherStatus}\n\n` + // Included teacherStatus here
                           `School: ${schoolName}\n` +
                           `Motto: ${schoolMotto}\n` +
                           `Address: ${schoolAddress}\n` +
                           `School Phone: ${schoolContactPhone}\n` +
                           `School Email: ${schoolContactEmail}\n` +
                           `Website: ${schoolWebsite}`;

            // Create and append the message div for download/print errors
            const downloadPrintMessageDiv = document.createElement('div');
            downloadPrintMessageDiv.id = 'downloadPrintMessage';
            downloadPrintMessageDiv.className = 'mt-4 p-3 rounded text-center text-sm hidden'; // Initially hidden
            document.querySelector('.action-buttons').insertAdjacentElement('afterend', downloadPrintMessageDiv);

            // Generate QR Code
            try {
                const qrcodeContainer = document.getElementById("qrcode");
                if (qrcodeContainer) {
                    // Clear any existing content in the QR code container (e.g., error messages)
                    qrcodeContainer.innerHTML = '';
                    new QRCode(qrcodeContainer, {
                        text: qrData,
                        width: 128,
                        height: 128,
                        colorDark : "#1e293b", // Slate 900
                        colorLight : "#ffffff",
                        correctLevel : QRCode.CorrectLevel.H // High error correction
                    });
                } else {
                    console.error("QR code container not found.");
                }
            } catch (e) {
                console.error("Error generating QR code:", e);
                const qrcodeContainer = document.getElementById("qrcode");
                if (qrcodeContainer) {
                    qrcodeContainer.innerHTML = `<p class='text-red-500 text-xs'>Error generating QR code. Check console for details.</p>`;
                }
            }

            // Handle Download as Image button
            const downloadCardBtn = document.getElementById('downloadCardBtn');
            const idCardContainer = document.getElementById('idCardContainer'); // Target the new parent container for html2canvas

            if (downloadCardBtn && idCardContainer) {
                downloadCardBtn.addEventListener('click', function() {
                    // Clear previous messages
                    downloadPrintMessageDiv.classList.add('hidden');
                    downloadPrintMessageDiv.classList.remove('bg-red-100', 'text-red-700', 'bg-green-100', 'text-green-700');
                    downloadPrintMessageDiv.textContent = '';

                    // Show a loading message
                    downloadPrintMessageDiv.classList.remove('hidden');
                    downloadPrintMessageDiv.classList.add('bg-blue-100', 'text-blue-700');
                    downloadPrintMessageDiv.textContent = 'Generating image... Please wait.';

                    // Use html2canvas to render the entire container div as a canvas
                    html2canvas(idCardContainer, {
                        scale: 2, // Increase scale for better quality
                        useCORS: true, // Important if images (like photo/logo) are from different origins
                        logging: false // Disable logging to console
                    }).then(function(canvas) {
                        // Create a temporary link element
                        const link = document.createElement('a');
                        link.download = `Teacher_ID_Card_${teacherName.replace(/\s/g, '_')}.png`; // Filename
                        link.href = canvas.toDataURL('image/png'); // Convert canvas to PNG data URL
                        document.body.appendChild(link); // Append to body (required for Firefox)
                        link.click(); // Programmatically click the link to trigger download
                        document.body.removeChild(link); // Clean up

                        downloadPrintMessageDiv.classList.remove('bg-blue-100', 'text-blue-700');
                        downloadPrintMessageDiv.classList.add('bg-green-100', 'text-green-700');
                        downloadPrintMessageDiv.textContent = 'ID Card downloaded successfully!';
                        setTimeout(() => { downloadPrintMessageDiv.classList.add('hidden'); }, 3000); // Hide after 3 seconds

                    }).catch(err => {
                        console.error("Error generating image for download:", err);
                        downloadPrintMessageDiv.classList.remove('bg-blue-100', 'text-blue-700');
                        downloadPrintMessageDiv.classList.add('bg-red-100', 'text-red-700');
                        downloadPrintMessageDiv.textContent = 'Failed to download ID card. This might be due to images (like your profile photo or school logo) not being served with proper CORS headers, or the image file is missing. Check browser console (F12) for details.';
                    });
                });
            } else {
                console.error("Download button or ID card container element not found.");
            }

            // Handle Print Card button
            const printCardBtn = document.getElementById('printCardBtn');
            if (printCardBtn) {
                printCardBtn.addEventListener('click', function() {
                    // Clear previous messages
                    downloadPrintMessageDiv.classList.add('hidden');
                    downloadPrintMessageDiv.classList.remove('bg-red-100', 'text-red-700', 'bg-green-100', 'text-green-700');
                    downloadPrintMessageDiv.textContent = '';

                    window.print(); // Triggers the browser's print dialog
                });
            } else {
                console.error("Print button not found.");
            }

            // Menu Toggle functionality for sidebar
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');

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

                // Close sidebar when clicking outside on mobile
                dashboardContainer.addEventListener('click', function(event) {
                    // Check if sidebar is active and click is outside sidebar and menu toggle button
                    if (sidebar.classList.contains('active') && !sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                });
            } else {
                console.error("Menu toggle, sidebar, or dashboard container elements for responsive behavior not found.");
            }
        });
    </script>

    <div id="mobile-footer-nav">
        <ul>
            <li>
                <a href="teacher_dashboard.php" data-section="dashboard">
                    <i class="fas fa-th-large"></i>
                    <span><?php echo $_L['sidebar_dashboard'] ?? 'Dashboard'; ?></span>
                </a>
            </li>
            <li>
                <a href="teacher_my_classes.php" data-section="my-classes">
                    <i class="fas fa-chalkboard"></i>
                    <span><?php echo $_L['sidebar_my_classes'] ?? 'Classes'; ?></span>
                </a>
            </li>
            <li>
                <a href="teacher_my_students.php" data-section="my-students">
                    <i class="fas fa-user-graduate"></i>
                    <span><?php echo $_L['sidebar_my_students'] ?? 'Students'; ?></span>
                </a>
            </li>
            <li>
                <a href="#" id="moreMenuButton" data-section="more">
                    <i class="fas fa-ellipsis-h"></i>
                    <span><?php echo $_L['more_menu'] ?? 'More'; ?></span>
                </a>
            </li>
        </ul>
    </div>
    <div id="more-menu-modal">
        <div id="more-menu-modal-header">
            <h3><?php echo $_L['more_menu'] ?? 'More'; ?></h3>
            <button id="more-menu-close-btn"><i class="fas fa-times"></i></button>
        </div>
        <ul id="more-menu-list">
            <li><a href="create_assignment.php" id="modalAssignmentsLink"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments'] ?? 'Assignments'; ?></a></li>
            <li><a href="teacher_exams.php" id="modalGradesLink"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades'] ?? 'Grades'; ?></a></li>
            <li><a href="teacher_messages.php" id="modalMessagesLink"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages'] ?? 'Messages'; ?></a></li>
            <li><a href="teacher_calendar.php" id="modalCalendarLink"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar'] ?? 'Calendar'; ?></a></li>
            <li><a href="teacher_profile.php" id="modalProfileLink" class="active"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile'] ?? 'Profile'; ?></a></li>
            <li><a href="teacher_settings.php" id="modalSettingsLink"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings'] ?? 'Settings'; ?></a></li>
            <li class="logout"><a href="logout.php" id="modalLogoutLink"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout'] ?? 'Logout'; ?></a></li>
        </ul>
    </div>
    <div class="overlay" id="overlay"></div>

    <style>
        /* Overlay for mobile sidebar and modal */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1500; /* Higher than the main content */
            display: none; /* Hidden by default */
        }
        .overlay.show {
            display: block; /* Show when active */
        }

        /* --- Mobile Footer Navigation (Betpawa-Style) --- */
        #mobile-footer-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 70px;
            background: #ffffff;
            border-top: 1px solid #e0e0e0;
            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; /* Indigo color for active state */
        }

        #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;
        }
        
        /* --- 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; /* Higher than overlay */
            transform: translateY(100%); /* Start off-screen */
            transition: transform 0.3s ease-in-out;
            padding-bottom: env(safe-area-inset-bottom, 20px);
            overflow-y: auto; /* Enable scrolling for long lists */
            display: none; /* Hide modal initially for all screen sizes */
            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 #e0e0e0;
            position: sticky; /* Keep header visible when scrolling list */
            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;
        }

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

        @media (max-width: 768px) {
            #mobile-footer-nav {
                display: block;
            }
            #more-menu-modal {
                display: block;
            }
            /* Adjust main content padding to account for fixed footer */
            .main-content {
                padding-bottom: 90px;
            }
            /* Hide specific items from sidebar on mobile when footer is active (matching hide-on-mobile class) */
            .sidebar nav ul li.hide-on-mobile {
                display: none;
            }
        }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');
            const overlay = document.getElementById('overlay');

            // Toggle sidebar visibility and add/remove overlay when menu toggle button is clicked
            if (menuToggle) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('active'); // Activates/deactivates sidebar
                    dashboardContainer.classList.toggle('sidebar-open'); // Adjusts main content margin
                    overlay.classList.toggle('active'); // Shows/hides overlay
                });
            }

            // Close sidebar and hide overlay when overlay is clicked (for mobile/tablet)
            if (overlay) {
                overlay.addEventListener('click', function() {
                    sidebar.classList.remove('active');
                    dashboardContainer.classList.remove('sidebar-open');
                    overlay.classList.remove('active');
                    // Also close more menu if open
                    toggleMoreMenu(false);
                });
            }
        });

        // --- START: Mobile Footer Modal Logic ---
        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'; // Prevent scrolling background
            } else {
                moreMenuModal.classList.remove('show');
                overlay.classList.remove('show');
                document.body.style.overflow = ''; // Restore scrolling
            }
        }

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

        if (moreMenuCloseBtn) {
            moreMenuCloseBtn.addEventListener('click', () => {
                toggleMoreMenu(false);
            });
        }
        // --- END: Mobile Footer Modal Logic ---
    </script>
</body>
</html>
