<?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 if they are not already defined.
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);
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.
 * @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', // Added
            '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',
            // New strings for settings page
            'settings_title' => 'Settings',
            'profile_settings_heading' => 'Profile Settings',
            'username_label' => 'Username',
            'email_label' => 'Email',
            'phone_label' => 'Phone Number',
            'photo_label' => 'Profile Photo',
            'current_password_label' => 'Current Password',
            'new_password_label' => 'New Password',
            'confirm_password_label' => 'Confirm New Password',
            'update_profile_button' => 'Update Profile',
            'update_password_button' => 'Update Password',
            'password_mismatch_error' => 'New password and confirmation do not match.',
            'password_too_short_error' => 'Password must be at least 6 characters long.',
            'username_exists_error' => 'This username is already taken.',
            'email_exists_error' => 'This email is already in use.',
            'update_success_message' => 'Profile updated successfully!',
            'update_error_message' => 'Error updating profile. Please try again.',
            'password_update_success' => 'Password updated successfully!',
            'old_password_incorrect_error' => 'Current password is incorrect.',
            'invalid_file_type' => 'Invalid file type. Only JPG, JPEG, PNG, GIF are allowed.',
            'file_upload_error' => 'Error uploading file. Please try again.',
            'fill_all_fields' => 'Please fill all required fields.',
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Enteekateeka',
            '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', // Added
            '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',
            // New strings for settings page
            'settings_title' => 'Enteekateeka',
            'profile_settings_heading' => 'Enteekateeka za Purofayiro',
            'username_label' => 'Erinnya ly\'Omukozesa',
            'email_label' => 'E-mail',
            'phone_label' => 'Ekiragiro ky\'Essimu',
            'photo_label' => 'Ekifaananyi kya Purofayiro',
            'current_password_label' => 'Ekiragiro Ky\'Ekiseera Kino',
            'new_password_label' => 'Ekiragiro Ekiggya',
            'confirm_password_label' => 'Kakasa Ekiragiro Ekiggya',
            'update_profile_button' => 'Tegeka Purofayiro',
            'update_password_button' => 'Tegeka Ekiragiro',
            'password_mismatch_error' => 'Ekiragiro ekiggya n’okukakasa tebikwatagana.',
            'password_too_short_error' => 'Ekiragiro kirina okubaamu bukkulwe namba ezitali wansi wa 6.',
            'username_exists_error' => 'Erinnya lino lyakulaba dda.',
            'email_exists_error' => 'E-mail eno ekozesebwa dda.',
            'update_success_message' => 'Purofayiro yaakaziyizibwa obulungi!',
            'update_error_message' => 'Waliwo ensobi mu kutegeka purofayiro. Gyezaako nate.',
            'password_update_success' => 'Ekiragiro ky\'akaziyizibwa obulungi!',
            'old_password_incorrect_error' => 'Ekiragiro ky\'ekiseera kino si kituufu.',
            'invalid_file_type' => 'Ekika kya fayiro si kituufu. JPG, JPEG, PNG, GIF byokka bye bikkirizibwa.',
            'file_upload_error' => 'Ensobi mu kuteeka fayiro. Gyezaako nate.',
            'fill_all_fields' => 'Jjuzaawo amabaluwa gonna agaalimu.',
        ],
        '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', // Added
            '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',
            // New strings for settings page
            'settings_title' => 'Mipangilio',
            'profile_settings_heading' => 'Mipangilio ya Wasifu',
            'username_label' => 'Jina la Mtumiaji',
            'email_label' => 'Barua Pepe',
            'phone_label' => 'Nambari ya Simu',
            'photo_label' => 'Picha ya Wasifu',
            'current_password_label' => 'Neno Siri la Sasa',
            'new_password_label' => 'Neno Siri Jipya',
            'confirm_password_label' => 'Thibitisha Neno Siri Jipya',
            'update_profile_button' => 'Sasisha Wasifu',
            'update_password_button' => 'Sasisha Neno Siri',
            'password_mismatch_error' => 'Neno siri jipya na uthibitisho hailingani.',
            'password_too_short_error' => 'Neno siri lazima liwe na angalau herufi 6.',
            'username_exists_error' => 'Jina hili la mtumiaji tayari limetumika.',
            'email_exists_error' => 'Barua pepe hii tayari inatumika.',
            'update_success_message' => 'Wasifu umesasishwa kwa ufanisi!',
            'update_error_message' => 'Hitilafu wakati wa kusasisha wasifu. Tafadhali jaribu tena.',
            'password_update_success' => 'Neno siri limesasishwa kwa ufanisi!',
            'old_password_incorrect_error' => 'Neno siri la sasa si sahihi.',
            'invalid_file_type' => 'Aina ya faili si sahihi. JPG, JPEG, PNG, GIF pekee ndizo zinazoruhusiwa.',
            'file_upload_error' => 'Hitilafu wakati wa kupakia faili. Tafadhali jaribu tena.',
            'fill_all_fields' => 'Tafadhali jaza sehemu zote zinazohitajika.',
        ]
    ];
    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 includes/sidebar.php (or similar) to highlight the active link in the navigation.
$currentPage = 'settings'; // Set current page for sidebar highlighting

// 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_session = 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 variables that will be fetched from the database or updated from form.
$current_username = $current_email = $current_phone_number = $current_photo = "";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";

$message = ''; // For success or error messages

// Ensure $conn (database connection) is available and is a mysqli object from config.php.
if (isset($conn) && $conn instanceof mysqli) {

    // Fetch existing user details for pre-filling the form
    $sql_fetch_user = "SELECT username, email, phone_number, photo, password FROM users WHERE id = ? AND school_id = ?";
    if ($stmt_fetch_user = $conn->prepare($sql_fetch_user)) {
        $stmt_fetch_user->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt_fetch_user->execute()) {
            $stmt_fetch_user->bind_result($current_username, $current_email, $current_phone_number, $current_photo_db, $hashed_password_db);
            $stmt_fetch_user->fetch();
            $current_photo = !empty($current_photo_db) ? htmlspecialchars($current_photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
        } else {
            error_log("Execute failed for fetching user details: " . $stmt_fetch_user->error);
            $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
        }
        $stmt_fetch_user->close();
    } else {
        error_log("Prepare failed for fetching user details: " . $conn->error);
        $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
    }

    // Fetch School Name and Logo from the 'schools' table.
    // Corrected SQL: Removed duplicate 'WHERE' keyword
    $sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school)) {
        $stmt_school->bind_param("i", $current_user_school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            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';
            } else {
                error_log("School details not found for school_id: " . $current_user_school_id);
            }
        } else {
            error_log("Execute failed for school data query: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // Handle form submission for profile update
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_profile'])) {
        $new_username = trim($_POST['username']);
        $new_email = trim($_POST['email']);
        $new_phone_number = trim($_POST['phone_number']);
        $photo_path = $current_photo_db; // Default to existing photo path

        // Validate inputs
        if (empty($new_username) || empty($new_email)) {
            $message = "<div class='error'>" . $_L['fill_all_fields'] . "</div>";
        } else {
            // Check if username or email already exists (excluding current user)
            $sql_check_duplicate = "SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ? AND school_id = ?";
            if ($stmt_check = $conn->prepare($sql_check_duplicate)) {
                $stmt_check->bind_param("ssii", $new_username, $new_email, $user_id, $current_user_school_id);
                $stmt_check->execute();
                $stmt_check->store_result();
                if ($stmt_check->num_rows > 0) {
                    $message = "<div class='error'>";
                    // Check specifically which one exists to give more precise error
                    $sql_check_username = "SELECT id FROM users WHERE username = ? AND id != ? AND school_id = ?";
                    $stmt_check_username = $conn->prepare($sql_check_username);
                    $stmt_check_username->bind_param("sii", $new_username, $user_id, $current_user_school_id);
                    $stmt_check_username->execute();
                    $stmt_check_username->store_result();
                    if ($stmt_check_username->num_rows > 0) {
                        $message .= $_L['username_exists_error'];
                    }
                    $stmt_check_username->close();

                    $sql_check_email = "SELECT id FROM users WHERE email = ? AND id != ? AND school_id = ?";
                    $stmt_check_email = $conn->prepare($sql_check_email);
                    $stmt_check_email->bind_param("sii", $new_email, $user_id, $current_user_school_id);
                    $stmt_check_email->execute();
                    $stmt_check_email->store_result();
                    if ($stmt_check_email->num_rows > 0) {
                        if ($stmt_check_username->num_rows > 0) $message .= " "; // Add space if both
                        $message .= $_L['email_exists_error'];
                    }
                    $stmt_check_email->close();
                    $message .= "</div>";

                } else {
                    // Handle photo upload
                    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
                        $target_dir = "uploads/teachers/";
                        // Create directory if it doesn't exist
                        if (!is_dir($target_dir)) {
                            mkdir($target_dir, 0777, true);
                        }

                        $file_name = basename($_FILES["photo"]["name"]);
                        $imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                        $unique_filename = "teacher_" . uniqid() . "." . $imageFileType;
                        $target_file = $target_dir . $unique_filename;
                        $uploadOk = 1;

                        // Check file size (e.g., 5MB limit)
                        if ($_FILES["photo"]["size"] > 5000000) {
                            $message = "<div class='error'>Sorry, your file is too large.</div>";
                            $uploadOk = 0;
                        }

                        // Allow certain file formats
                        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
                            $message = "<div class='error'>" . $_L['invalid_file_type'] . "</div>";
                            $uploadOk = 0;
                        }

                        if ($uploadOk == 1) {
                            if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
                                $photo_path = $target_file;
                                // Delete old photo if it exists and is not the default
                                if (!empty($current_photo_db) && file_exists($current_photo_db) && $current_photo_db !== 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR') {
                                    unlink($current_photo_db);
                                }
                            } else {
                                $message = "<div class='error'>" . $_L['file_upload_error'] . "</div>";
                                error_log("Error moving uploaded file: " . $_FILES["photo"]["error"]);
                            }
                        }
                    }

                    // Update user details in the database
                    $sql_update_profile = "UPDATE users SET username = ?, email = ?, phone_number = ?, photo = ? WHERE id = ? AND school_id = ?";
                    if ($stmt_update = $conn->prepare($sql_update_profile)) {
                        $stmt_update->bind_param("ssssii", $new_username, $new_email, $new_phone_number, $photo_path, $user_id, $current_user_school_id);
                        if ($stmt_update->execute()) {
                            // Update session variables immediately
                            $_SESSION["username"] = $new_username;
                            $current_username = $new_username;
                            $current_email = $new_email;
                            $current_phone_number = $new_phone_number;
                            $current_photo = htmlspecialchars($photo_path); // Update current_photo for display
                            $current_photo_db = $photo_path; // Update current_photo_db for subsequent checks
                            $message = "<div class='success'>" . $_L['update_success_message'] . "</div>";
                        } else {
                            $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
                            error_log("Execute failed for profile update: " . $stmt_update->error);
                        }
                        $stmt_update->close();
                    } else {
                        $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
                        error_log("Prepare failed for profile update: " . $conn->error);
                    }
                }
                $stmt_check->close();
            } else {
                error_log("Prepare failed for duplicate check: " . $conn->error);
                $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
            }
        }
    }

    // Handle form submission for password update
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_password'])) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_new_password = $_POST['confirm_new_password'];

        if (empty($current_password) || empty($new_password) || empty($confirm_new_password)) {
            $message = "<div class='error'>" . $_L['fill_all_fields'] . "</div>";
        } elseif (!password_verify($current_password, $hashed_password_db)) {
            $message = "<div class='error'>" . $_L['old_password_incorrect_error'] . "</div>";
        } elseif ($new_password !== $confirm_new_password) {
            $message = "<div class='error'>" . $_L['password_mismatch_error'] . "</div>";
        } elseif (strlen($new_password) < 6) {
            $message = "<div class='error'>" . $_L['password_too_short_error'] . "</div>";
        } else {
            // Hash the new password
            $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);

            $sql_update_password = "UPDATE users SET password = ? WHERE id = ? AND school_id = ?";
            if ($stmt_update_pass = $conn->prepare($sql_update_password)) {
                $stmt_update_pass->bind_param("sii", $hashed_new_password, $user_id, $current_user_school_id);
                if ($stmt_update_pass->execute()) {
                    $message = "<div class='success'>" . $_L['password_update_success'] . "</div>";
                    // Update the hashed password in memory for subsequent checks without re-fetching
                    $hashed_password_db = $hashed_new_password;
                } else {
                    $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
                    error_log("Execute failed for password update: " . $stmt_update_pass->error);
                }
                $stmt_update_pass->close();
            } else {
                $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
                error_log("Prepare failed for password update: " . $conn->error);
            }
        }
    }

    $conn->close(); // Close the database connection after all operations
} else {
    error_log("Database connection \$conn not available in teacher_settings.php");
    $message = "<div class='error'>" . $_L['update_error_message'] . "</div>";
    $current_photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
}

// 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;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $role_name; ?> <?php echo $_L['settings_title']; ?> - <?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 -->
</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><a href="teacher_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li><a href="teacher_my_classes.php"><i class="fas fa-chalkboard"></i> <?php echo $_L['sidebar_my_classes']; ?></a></li>
                    <li><a href="teacher_my_students.php"><i class="fas fa-user-graduate"></i> <?php echo $_L['sidebar_my_students']; ?></a></li>
                    <li><a href="create_assignment.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li><a href="teacher_grades.php"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades']; ?></a></li>
                    <li><a href="teacher_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li><a href="teacher_calendar.php"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a></li>
                    <li><a href="teacher_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="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 $current_photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username_session; ?></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="dashboard-content">
                <h2><i class="fas fa-cog"></i> <?php echo $_L['profile_settings_heading']; ?></h2>

                <?php
                // Check if message is not empty before echoing, and add an ID for JS targeting
                if (!empty($message)) {
                    echo "<div id='messageContainer'>" . $message . "</div>";
                }
                ?>

                <div class="container" style="max-width: 700px; margin-top: 20px;">
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                        <h3><?php echo $_L['profile_settings_heading']; ?></h3>
                        <div class="profile-grid"> <!-- Added this div for two-column layout -->
                            <div class="form-group">
                                <label for="username"><?php echo $_L['username_label']; ?>:</label>
                                <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($current_username); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="email"><?php echo $_L['email_label']; ?>:</label>
                                <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($current_email); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="phone_number"><?php echo $_L['phone_label']; ?>:</label>
                                <input type="text" id="phone_number" name="phone_number" value="<?php echo htmlspecialchars($current_phone_number); ?>">
                            </div>
                            <div class="form-group">
                                <label for="photo"><?php echo $_L['photo_label']; ?>:</label>
                                <input type="file" id="photo" name="photo" accept="image/*">
                                <?php if (!empty($current_photo) && $current_photo !== 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR'): ?>
                                    <p style="margin-top: 10px;">Current Photo: <img src="<?php echo $current_photo; ?>" alt="Profile Photo" style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover; vertical-align: middle;"></p>
                                <?php endif; ?>
                            </div>
                        </div> <!-- End of profile-grid -->
                        <input type="submit" name="update_profile" value="<?php echo $_L['update_profile_button']; ?>">
                    </form>

                    <hr style="margin: 40px 0; border: 0; border-top: 1px solid var(--border-color);">

                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <h3><?php echo $_L['update_password_button']; ?></h3>
                        <div class="form-group">
                            <label for="current_password"><?php echo $_L['current_password_label']; ?>:</label>
                            <input type="password" id="current_password" name="current_password" required>
                        </div>
                        <div class="form-group">
                            <label for="new_password"><?php echo $_L['new_password_label']; ?>:</label>
                            <input type="password" id="new_password" name="new_password" required>
                        </div>
                        <div class="form-group">
                            <label for="confirm_new_password"><?php echo $_L['confirm_password_label']; ?>:</label>
                            <input type="password" id="confirm_new_password" name="confirm_new_password" required>
                        </div>
                        <input type="submit" name="update_password" value="<?php echo $_L['update_password_button']; ?>">
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
        // JavaScript for sidebar toggle (same as dashboard)
        document.getElementById('menuToggle').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('dashboardContainer').classList.toggle('sidebar-open');
        });

        // JavaScript for language change (same as dashboard)
        function changeLanguage(lang) {
            window.location.href = window.location.pathname + '?lang=' + lang;
        }

        // JavaScript to make messages disappear after 3 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const messageContainer = document.getElementById('messageContainer');
            if (messageContainer) {
                setTimeout(() => {
                    messageContainer.style.transition = 'opacity 0.5s ease-out';
                    messageContainer.style.opacity = '0';
                    setTimeout(() => {
                        messageContainer.style.display = 'none';
                    }, 500); // Wait for transition to complete before setting display to none
                }, 3000); // 3000 milliseconds = 3 seconds
            }
        });
    </script>

    <!-- Mobile Footer (visible only on mobile screens) -->
    <footer class="mobile-footer">
        <div class="footer-nav">
            <a href="teacher_dashboard.php" class="footer-item">
                <i class="fas fa-th-large"></i>
                <span>Dashboard</span>
            </a>
            <a href="teacher_my_classes.php" class="footer-item">
                <i class="fas fa-chalkboard"></i>
                <span>Classes</span>
            </a>
            <a href="teacher_my_students.php" class="footer-item">
                <i class="fas fa-user-graduate"></i>
                <span>Students</span>
            </a>
            <button class="footer-item" id="moreButton">
                <i class="fas fa-ellipsis-h"></i>
                <span>More</span>
            </button>
        </div>
    </footer>

    <!-- More Menu Modal -->
    <div id="more-menu-modal" class="more-menu-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>More Options</h3>
                <button class="close-modal" id="closeModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-nav">
                <a href="create_assignment.php" class="modal-nav-item">
                    <i class="fas fa-file-alt"></i>
                    <span>Assignments</span>
                </a>
                <a href="teacher_exams.php" class="modal-nav-item">
                    <i class="fas fa-award"></i>
                    <span>Grades</span>
                </a>
                <a href="teacher_messages.php" class="modal-nav-item">
                    <i class="fas fa-envelope"></i>
                    <span>Messages</span>
                </a>
                <a href="teacher_calendar.php" class="modal-nav-item">
                    <i class="far fa-calendar-alt"></i>
                    <span>Calendar</span>
                </a>
                <a href="teacher_profile.php" class="modal-nav-item">
                    <i class="fas fa-user-circle"></i>
                    <span>Profile</span>
                </a>
                <a href="teacher_settings.php" class="modal-nav-item active">
                    <i class="fas fa-cog"></i>
                    <span>Settings</span>
                </a>
                <a href="logout.php" class="modal-nav-item logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </div>
    </div>

    <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;
            }
        }

        
        /* Mobile Footer Styles */
        .mobile-footer {
            display: none;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-top: 1px solid #e2e8f0;
            z-index: 1000;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        }

        .footer-nav {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 8px 0;
        }

        .footer-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-size: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s;
            background: none;
            border: none;
            cursor: pointer;
            min-width: 60px;
        }

        .footer-item i {
            font-size: 18px;
            margin-bottom: 4px;
        }

        .footer-item.active {
            color: #3b82f6;
            background-color: #eff6ff;
        }

        .footer-item:hover {
            color: #3b82f6;
            background-color: #f3f4f6;
        }

        /* More Menu Modal Styles */
        #more-menu-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            transform: translateY(100%);
            transition: transform 0.3s ease;
            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;
        }

        .modal-content {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-radius: 20px 20px 0 0;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 20px 10px;
            border-bottom: 1px solid #e2e8f0;
        }

        .modal-header h3 {
            margin: 0;
            color: #1f2937;
            font-size: 18px;
            font-weight: 600;
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            color: #6b7280;
            cursor: pointer;
            padding: 5px;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .close-modal:hover {
            background-color: #f3f4f6;
        }

        .modal-nav {
            padding: 10px 0 30px;
        }

        .modal-nav-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            text-decoration: none;
            color: #374151;
            transition: background-color 0.2s;
        }

        .modal-nav-item:hover {
            background-color: #f9fafb;
        }

        .modal-nav-item.active {
            background-color: #eff6ff;
            color: #3b82f6;
        }

        .modal-nav-item i {
            width: 24px;
            font-size: 18px;
            margin-right: 15px;
            color: #6b7280;
        }

        .modal-nav-item.active i {
            color: #3b82f6;
        }

        .modal-nav-item span {
            font-size: 16px;
            font-weight: 500;
        }

        .modal-nav-item.logout {
            color: #dc2626;
        }

        .modal-nav-item.logout i {
            color: #dc2626;
        }

        /* Show mobile footer only on mobile screens */
        @media (max-width: 768px) {
            .mobile-footer {
                display: block;
            }
            
            /* Add bottom padding to main content to account for fixed footer */
            .main-content {
                padding-bottom: 80px;
            }
        }
    </style>

    <script>
        // Mobile footer modal functionality
        document.addEventListener('DOMContentLoaded', function() {
            const moreButton = document.getElementById('moreButton');
            const moreModal = document.getElementById('more-menu-modal');
            const closeModal = document.getElementById('closeModal');

            if (moreButton && moreModal) {
                moreButton.addEventListener('click', function() {
                    moreModal.classList.add('show');
                });
            }

            if (closeModal && moreModal) {
                closeModal.addEventListener('click', function() {
                    moreModal.classList.remove('show');
                });
            }

            // Close modal when clicking outside
            if (moreModal) {
                moreModal.addEventListener('click', function(e) {
                    if (e.target === moreModal) {
                        moreModal.classList.remove('show');
                    }
                });
            }
        });
    </script>
</body>
</html>/html>
