<?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' => [
            'calendar_title_prefix' => 'Calendar',
            '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',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'calendar_heading' => 'School Calendar',
            'event_title_placeholder' => 'Event Title',
            'event_start_placeholder' => 'Start Time',
            'event_end_placeholder' => 'End Time',
            'event_description_placeholder' => 'Description',
            'event_color_placeholder' => 'Event Color',
            'add_event_button' => 'Add Event',
            'event_added_success' => 'Event added successfully!',
            'event_add_error' => 'Error adding event. Please try again.',
            'event_delete_confirm' => 'Are you sure you want to delete this event?',
            'event_delete_success' => 'Event deleted successfully!',
            'event_delete_error' => 'Error deleting event. Please try again.',
        ],
        'lug' => [
            'calendar_title_prefix' => 'Kkalenda',
            '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',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'calendar_heading' => 'Kkalenda y’Essomero',
            'event_title_placeholder' => 'Erinnya ly’Omukolo',
            'event_start_placeholder' => 'Ekiseera Ekitandikira',
            'event_end_placeholder' => 'Ekiseera Ekiggwera',
            'event_description_placeholder' => 'Enyinyonnyola',
            'event_color_placeholder' => 'Langi y’Omukolo',
            'add_event_button' => 'Gattako Omukolo',
            'event_added_success' => 'Omukolo gugattiddwa bulungi!',
            'event_add_error' => 'Waliwo ensobi mu kugattako omukolo. Gerageza nate.',
            'event_delete_confirm' => 'Olukakasa okugyawo omukolo guno?',
            'event_delete_success' => 'Omukolo gugyiddwawo bulungi!',
            'event_delete_error' => 'Waliwo ensobi mu kugyawo omukolo. Gerageza nate.',
        ],
        'sw' => [
            'calendar_title_prefix' => 'Kalenda',
            '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',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'calendar_heading' => 'Kalenda ya Shule',
            'event_title_placeholder' => 'Kichwa cha Tukio',
            'event_start_placeholder' => 'Muda wa Kuanza',
            'event_end_placeholder' => 'Muda wa Kumaliza',
            'event_description_placeholder' => 'Maelezo',
            'event_color_placeholder' => 'Rangi ya Tukio',
            'add_event_button' => 'Ongeza Tukio',
            'event_added_success' => 'Tukio limeongezwa kikamilifu!',
            'event_add_error' => 'Kuna hitilafu kuongeza tukio. Tafadhali jaribu tena.',
            'event_delete_confirm' => 'Una uhakika unataka kufuta tukio hili?',
            'event_delete_success' => 'Tukio limefutwa kikamilifu!',
            'event_delete_error' => 'Kuna hitilafu kufuta tukio. Tafadhali jaribu tena.',
        ]
    ];
    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.
 * @param int $required_role_code The role code required to access this page.
 */
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_STUDENT:
                header("location: student_dashboard.php");
                break;
            case ROLE_PARENT:
                header("location: parent_dashboard.php"); // Assuming parent dashboard exists
                break;
            case ROLE_STAFF:
                header("location: staff_dashboard.php"); // Assuming staff dashboard exists
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

// !! CRITICAL: Call the check for Teacher role !!
check_role_access(ROLE_TEACHER);

// This variable is used by includes/sidebar.php (or similar) to highlight the active link in the navigation.
$currentPage = 'calendar';

// User is authorized, now fetch additional details for display.
$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];
$current_user_school_id = $_SESSION["school_id"];

// Initialize variables
$phone_number = $photo = $status = "";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";
$message = ''; // For displaying success/error messages

// Array to hold calendar events
$events = [];

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


if (isset($conn) && $conn instanceof mysqli) {

    // --- Handle Adding Event (AJAX request) ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_event'])) {
        $title = trim($_POST['title']);
        $start = trim($_POST['start']);
        $end = trim($_POST['end']);
        $description = trim($_POST['description']);
        $color = trim($_POST['color']);

        // Basic validation
        if (!empty($title) && !empty($start) && !empty($end)) {
            // Convert to MySQL datetime format if necessary (FullCalendar typically sends ISO 8601)
            $start_mysql = date('Y-m-d H:i:s', strtotime($start));
            $end_mysql = date('Y-m-d H:i:s', strtotime($end));

            // Assuming 'events' table exists with columns: id, title, start_datetime, end_datetime, description, color, user_id, school_id, created_by_role
            $sql_insert_event = "INSERT INTO events (title, start_datetime, end_datetime, description, color, user_id, school_id, created_by_role) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt_insert = $conn->prepare($sql_insert_event)) {
                $stmt_insert->bind_param("sssssiii", $title, $start_mysql, $end_mysql, $description, $color, $user_id, $current_user_school_id, $user_role_code);
                if ($stmt_insert->execute()) {
                    echo json_encode(['success' => true, 'message' => $_L['event_added_success'], 'event_id' => $conn->insert_id]);
                } else {
                    echo json_encode(['success' => false, 'error' => $stmt_insert->error, 'message' => $_L['event_add_error']]);
                    error_log("Execute failed for inserting event: " . $stmt_insert->error);
                }
                $stmt_insert->close();
            } else {
                echo json_encode(['success' => false, 'error' => $conn->error, 'message' => $_L['event_add_error']]);
                error_log("Prepare failed for inserting event: " . $conn->error);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing required event fields.', 'message' => $_L['event_add_error']]);
        }
        exit; // Exit after handling AJAX request
    }

    // --- Handle Event Deletion (AJAX request) ---
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_event'])) {
        $event_id_to_delete = filter_var($_POST['event_id'], FILTER_VALIDATE_INT);

        if ($event_id_to_delete) {
            // Ensure the user can only delete events they created or events specific to their school that they are allowed to delete (e.g., if only admins can delete certain events).
            // For now, allowing a teacher to delete only events they created or school-wide events if they have the privilege.
            // Simplified: Teacher can delete their own events.
            $sql_delete_event = "DELETE FROM events WHERE id = ? AND user_id = ? AND school_id = ?";
            if ($stmt_delete = $conn->prepare($sql_delete_event)) {
                $stmt_delete->bind_param("iii", $event_id_to_delete, $user_id, $current_user_school_id);
                if ($stmt_delete->execute()) {
                    if ($stmt_delete->affected_rows > 0) {
                        echo json_encode(['success' => true, 'message' => $_L['event_delete_success']]);
                    } else {
                        echo json_encode(['success' => false, 'error' => 'Event not found or unauthorized to delete.', 'message' => $_L['event_delete_error']]);
                    }
                } else {
                    echo json_encode(['success' => false, 'error' => $stmt_delete->error, 'message' => $_L['event_delete_error']]);
                    error_log("Execute failed for deleting event: " . $stmt_delete->error);
                }
                $stmt_delete->close();
            } else {
                echo json_encode(['success' => false, 'error' => $conn->error, 'message' => $_L['event_delete_error']]);
                error_log("Prepare failed for deleting event: " . $conn->error);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid event ID for deletion.', 'message' => $_L['event_delete_error']]);
        }
        exit;
    }

    // --- Fetch user details ---
    $sql = "SELECT phone_number, photo, status FROM users WHERE id = ? AND school_id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ii", $user_id, $current_user_school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db, $status_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
            $status = htmlspecialchars($status_db ?? 'N/A');
        } else {
            error_log("Execute failed for user details query in teacher_calendar: " . $stmt->error);
        }
        $stmt->close();
    } else {
        error_log("Prepare failed for user details query in teacher_calendar: " . $conn->error);
    }

    // --- Fetch School Name and Logo ---
    $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 in teacher_calendar: " . $stmt_school->error);
        }
        $stmt_school->close();
    } else {
        error_log("Prepare failed for school data query: " . $conn->error);
    }

    // --- Fetch Events for FullCalendar ---
    // Fetch events that are school-wide or created by this specific teacher
    $sql_events = "SELECT id, title, start_datetime AS start, end_datetime AS end, description, color FROM events WHERE school_id = ? AND (user_id = ? OR created_by_role <= ?)"; // Adjust 'created_by_role' condition as needed for shared events (e.g., only Admin events are school-wide)
    if ($stmt_events = $conn->prepare($sql_events)) {
        // Assuming events created by ROLE_ADMIN (2) or ROLE_SUPER_ADMIN (1) are visible school-wide
        $admin_role_threshold = ROLE_ADMIN; // Events created by Admins or Super Admins are visible to teachers
        $stmt_events->bind_param("iii", $current_user_school_id, $user_id, $admin_role_threshold);
        if ($stmt_events->execute()) {
            $result_events = $stmt_events->get_result();
            while ($row = $result_events->fetch_assoc()) {
                // Ensure 'id' is explicitly set for FullCalendar event object
                $row['id'] = (string) $row['id']; // FullCalendar often prefers string IDs
                $events[] = $row;
            }
        } else {
            error_log("Execute failed for fetching events: " . $stmt_events->error);
        }
        $stmt_events->close();
    } else {
        error_log("Prepare failed for fetching events: " . $conn->error);
    }


    $conn->close(); // Close the database connection
} else {
    error_log("Database connection \$conn not available in teacher_calendar.php");
    $photo = 'https://via.placeholder.com/80/cccccc/FFFFFF?text=TR';
}
?>

<!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['calendar_title_prefix']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- FullCalendar CSS -->
    <link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.13/main.min.css' rel='stylesheet' />
    <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;
            }
        }

        
        /* Additional styles for calendar if not already in style.css */
        .calendar-section {
            display: grid;
            grid-template-columns: 1fr; /* Default to single column */
            gap: 20px;
        }

        .calendar-controls, .calendar-display {
            background-color: var(--card-bg);
            padding: 25px;
            border-radius: 10px;
            box-shadow: var(--shadow-light);
        }

        .calendar-controls h3 {
            margin-top: 0;
            color: var(--text-dark);
            margin-bottom: 20px;
            font-size: 1.4em;
        }

        .calendar-controls .form-group {
            margin-bottom: 15px;
        }

        .calendar-controls input[type="text"],
        .calendar-controls input[type="datetime-local"],
        .calendar-controls textarea,
        .calendar-controls select {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            font-size: 1em;
            box-sizing: border-box; /* Ensure padding is included in width */
        }

        .calendar-controls input[type="color"] {
            width: 80px;
            height: 40px;
            vertical-align: middle;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            cursor: pointer;
        }

        .calendar-controls .btn-primary {
            width: 100%;
            margin-top: 15px;
        }

        /* FullCalendar overrides/enhancements */
        #calendar {
            max-width: 100%; /* Make it responsive */
            margin: 0 auto;
        }

        .fc .fc-toolbar-title {
            font-size: 1.8em;
            color: var(--primary-green);
            font-weight: 600;
        }

        .fc .fc-button-primary {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
            color: white;
            padding: 8px 12px;
            border-radius: 5px;
            font-size: 0.9em;
            transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .fc .fc-button-primary:hover {
            background-color: #218838;
            border-color: #218838;
        }

        .fc .fc-button-primary:not(:disabled).fc-button-active {
            background-color: #1a712f;
            border-color: #1a712f;
        }

        .fc .fc-daygrid-day-number {
            font-weight: 500;
        }

        .fc .fc-day-today {
            background-color: #e6f7ff !important; /* Light blue for today */
        }

        .fc-event {
            border: none !important;
            border-radius: 4px !important;
            font-size: 0.85em !important;
            padding: 2px 5px !important;
            margin-bottom: 1px !important;
            cursor: pointer;
        }

        .fc-event-title-wrap {
            white-space: normal; /* Allow event titles to wrap */
        }

        /* Ensure responsive grid for calendar controls and display */
        @media (min-width: 992px) {
            .calendar-section {
                grid-template-columns: 1fr 2fr; /* Event form on left, calendar on right */
            }
        }

        @media (max-width: 768px) {
            .calendar-controls input[type="color"] {
                width: 100%; /* Make color picker full width on small screens */
            }
        }
    </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><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 class="active"><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><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>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?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="far fa-calendar-alt"></i> <?php echo $_L['calendar_heading']; ?></h2>

                <?php echo $message; // Display success/error messages ?>

                <div class="calendar-section">
                    <div class="calendar-controls">
                        <h3><?php echo $_L['add_event_button']; ?></h3>
                        <form id="addEventForm">
                            <div class="form-group">
                                <label for="eventTitle"><?php echo $_L['event_title_placeholder']; ?></label>
                                <input type="text" id="eventTitle" placeholder="<?php echo $_L['event_title_placeholder']; ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="eventStart"><?php echo $_L['event_start_placeholder']; ?></label>
                                <input type="datetime-local" id="eventStart" required>
                            </div>
                            <div class="form-group">
                                <label for="eventEnd"><?php echo $_L['event_end_placeholder']; ?></label>
                                <input type="datetime-local" id="eventEnd" required>
                            </div>
                            <div class="form-group">
                                <label for="eventDescription"><?php echo $_L['event_description_placeholder']; ?></label>
                                <textarea id="eventDescription" rows="3" placeholder="<?php echo $_L['event_description_placeholder']; ?>"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="eventColor"><?php echo $_L['event_color_placeholder']; ?></label>
                                <input type="color" id="eventColor" value="#0275d8"> <!-- Default color -->
                            </div>
                            <button type="submit" class="btn btn-primary"><?php echo $_L['add_event_button']; ?></button>
                        </form>
                    </div>

                    <div class="calendar-display">
                        <div id='calendar'></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- FullCalendar JavaScript -->
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.13/index.global.min.js'></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Sidebar Toggle Logic
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');

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

            document.addEventListener('click', function(event) {
                if (window.innerWidth <= 768) {
                    if (!sidebar.contains(event.target) && !menuToggle.contains(event.target) && sidebar.classList.contains('active')) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                }
            });

            // Language Selector Logic
            window.changeLanguage = function(lang) {
                window.location.href = `teacher_calendar.php?lang=${lang}`;
            };

            // FullCalendar Initialization
            const calendarEl = document.getElementById('calendar');
            const calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'dayGridMonth', // Default view (month view)
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay' // Month, Week, Day views
                },
                editable: true, // Allow events to be dragged and resized
                selectable: true, // Allow selecting dates for event creation
                dayMaxEvents: true, // Allow "more" link when too many events
                events: <?php echo json_encode($events); ?>, // Load events from PHP
                eventColor: '#0275d8', // Default event color, can be overridden by individual event colors

                // Event Click Handler (for showing/editing event details or deleting)
                eventClick: function(info) {
                    if (confirm('<?php echo $_L['event_delete_confirm']; ?>\n' + info.event.title)) {
                        const formData = new FormData();
                        formData.append('delete_event', 'true');
                        formData.append('event_id', info.event.id);

                        fetch('teacher_calendar.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                info.event.remove(); // Remove event from calendar UI
                                alert(data.message); // Show success message
                            } else {
                                alert('<?php echo $_L['event_delete_error']; ?>: ' + data.error);
                            }
                        })
                        .catch(error => {
                            console.error('Error deleting event:', error);
                            alert('<?php echo $_L['event_delete_error']; ?>');
                        });
                    }
                },

                // Date Selection Handler (for adding new event)
                select: function(info) {
                    // Pre-fill start and end dates in the form
                    document.getElementById('eventStart').value = new Date(info.startStr).toISOString().slice(0, 16);
                    document.getElementById('eventEnd').value = new Date(info.endStr || info.startStr).toISOString().slice(0, 16);
                    // Optionally scroll to the form or make it prominent
                },

                // Event Drop/Drag Handler (for updating event dates)
                eventDrop: function(info) {
                    // Send an AJAX request to update the event's start and end dates
                    const formData = new FormData();
                    formData.append('update_event_dates', 'true'); // Or a dedicated update API
                    formData.append('event_id', info.event.id);
                    formData.append('new_start', info.event.start.toISOString());
                    formData.append('new_end', info.event.end ? info.event.end.toISOString() : ''); // End might be null for all-day

                    fetch('teacher_calendar.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Event updated successfully on server
                            console.log('Event dates updated:', data.message);
                        } else {
                            // If update fails on server, revert the change in UI
                            info.revert();
                            console.error('Failed to update event dates:', data.error);
                            alert('Error updating event dates: ' + data.error);
                        }
                    })
                    .catch(error => {
                        info.revert(); // Revert on network error
                        console.error('Network error updating event dates:', error);
                        alert('Network error updating event dates.');
                    });
                },

                // Event Resize Handler (for updating event duration)
                eventResize: function(info) {
                    // Similar to eventDrop, send AJAX to update start/end
                    const formData = new FormData();
                    formData.append('update_event_dates', 'true');
                    formData.append('event_id', info.event.id);
                    formData.append('new_start', info.event.start.toISOString());
                    formData.append('new_end', info.event.end ? info.event.end.toISOString() : '');

                    fetch('teacher_calendar.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            console.log('Event duration updated:', data.message);
                        } else {
                            info.revert();
                            console.error('Failed to update event duration:', data.error);
                            alert('Error updating event duration: ' + data.error);
                        }
                    })
                    .catch(error => {
                        info.revert();
                        console.error('Network error updating event duration:', error);
                        alert('Network error updating event duration.');
                    });
                }
            });

            calendar.render(); // Render the calendar when the page loads

            // Handle Add Event Form Submission
            const addEventForm = document.getElementById('addEventForm');
            addEventForm.addEventListener('submit', function(event) {
                event.preventDefault(); // Prevent default form submission

                const title = document.getElementById('eventTitle').value;
                const start = document.getElementById('eventStart').value;
                const end = document.getElementById('eventEnd').value;
                const description = document.getElementById('eventDescription').value;
                const color = document.getElementById('eventColor').value;

                const formData = new FormData();
                formData.append('add_event', 'true');
                formData.append('title', title);
                formData.append('start', start);
                formData.append('end', end);
                formData.append('description', description);
                formData.append('color', color);

                fetch('teacher_calendar.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Add the new event to the calendar UI
                        calendar.addEvent({
                            id: data.event_id, // Use the ID returned from the server
                            title: title,
                            start: start,
                            end: end,
                            description: description,
                            color: color
                        });
                        alert(data.message); // Show success message
                        addEventForm.reset(); // Clear the form
                    } else {
                        alert('<?php echo $_L['event_add_error']; ?>: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error adding event:', error);
                    alert('<?php echo $_L['event_add_error']; ?>');
                });
            });
        });
    </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 active">
                    <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">
                    <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>
        /* 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>
