<?php
// 1. Clean Environment
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
ini_set('display_errors', 0);

session_start(); 
require_once 'config.php'; 

// Role Constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 0);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 1);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 2); 
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 3); 
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 4); 
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 5); 

// Language Handling
$available_languages = ['en', 'lug', 'sw']; 
$default_language = 'en';
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'];

function load_language_data($lang) {
    $data = [
        'en' => [
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_my_classes' => 'My Classes',
            'sidebar_my_students' => 'Students',
            'sidebar_assignments' => 'Assignments',
            'sidebar_grades' => 'Grades',
            'sidebar_messages' => 'Messages',
            'sidebar_calendar' => 'Calendar',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'search_placeholder' => 'Search records...',
            'welcome_message_prefix' => 'Welcome back',
            'manage_records_text' => 'Here is your daily academic overview.',
            'view_my_classes_button' => 'View Classes',
            'stat_students_label' => 'Total Students',
            'stat_assignments_label' => 'Pending Grading',
            'stat_messages_label' => 'Unread Messages',
            'stat_lessons_label' => 'Next Lessons',
            'school_announcements_heading' => 'Notice Board',
            'view_all_button' => 'View All',
            'no_announcements' => 'No new announcements.',
            'day_mon' => 'Mon', 'day_tue' => 'Tue', 'day_wed' => 'Wed', 'day_thu' => 'Thu',
            'day_fri' => 'Fri', 'day_sat' => 'Sat', 'day_sun' => 'Sun',
            'more_menu' => 'More', 
            'my_profile' => 'My Profile',
            'school_name_not_found' => 'School Name Not Found',
            'select_language' => 'Select Language'
        ],
        'lug' => [
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_my_classes' => 'Ebibiina',
            'sidebar_my_students' => 'Bayizi',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_grades' => 'Akaadi',
            'sidebar_messages' => 'Obubaka',
            'sidebar_calendar' => 'Kkalenda',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'search_placeholder' => 'Noonya...',
            'welcome_message_prefix' => 'Olamusiddwa',
            'manage_records_text' => 'Kola ku bibiina byo.',
            'view_my_classes_button' => 'Ebibiina',
            'stat_students_label' => 'Abayizi',
            'stat_assignments_label' => 'Ebitongole',
            'stat_messages_label' => 'Obubaka',
            'stat_lessons_label' => 'Ensiriki',
            'school_announcements_heading' => 'Amanyisibwa',
            'view_all_button' => 'Laba Byonna',
            'no_announcements' => 'Tewali manyisibwa.',
            'day_mon' => 'Bal', 'day_tue' => 'Bbi', 'day_wed' => 'Ggo', 'day_thu' => 'Nna',
            'day_fri' => 'Muu', 'day_sat' => 'Lwa', 'day_sun' => 'San',
            'more_menu' => 'Ebirala', 
            'my_profile' => 'Purofayiro Yange',
            'school_name_not_found' => 'Erinnya ly\'Essomero Terinnaba Kulabika',
            'select_language' => 'Londa Olulimi'
        ],
        'sw' => [
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_my_classes' => 'Madarasa',
            'sidebar_my_students' => 'Wanafunzi',
            'sidebar_assignments' => 'Kazi',
            'sidebar_grades' => 'Alama',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_calendar' => 'Kalenda',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'search_placeholder' => 'Tafuta...',
            'welcome_message_prefix' => 'Karibu',
            'manage_records_text' => 'Dhibiti madarasa yako.',
            'view_my_classes_button' => 'Madarasa',
            'stat_students_label' => 'Wanafunzi',
            'stat_assignments_label' => 'Kazi',
            'stat_messages_label' => 'Ujumbe',
            'stat_lessons_label' => 'Masomo',
            'school_announcements_heading' => 'Matangazo',
            'view_all_button' => 'Tazama Yote',
            'no_announcements' => 'Hakuna matangazo.',
            'day_mon' => 'Jt', 'day_tue' => 'Jnn', 'day_wed' => 'Jtatu', 'day_thu' => 'Jne',
            'day_fri' => 'Ij', 'day_sat' => 'Jmo', 'day_sun' => 'Jpili',
            'more_menu' => 'Zaidi', 
            'my_profile' => 'Wasifu Wangu',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'select_language' => 'Chagua Lugha'
        ]
    ];
    return $data[$lang] ?? $data['en']; 
}
$_L = load_language_data($current_lang);

// Auth Check
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php"); exit; 
    }
    if (isset($_SESSION["role"]) && $_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;
            default: header("location: login.php"); break;
        }
        exit; 
    }
}
check_role_access(ROLE_TEACHER);

$currentPage = 'dashboard';
$user_id = $_SESSION["id"] ?? 0; 
$username = htmlspecialchars($_SESSION["username"] ?? 'User'); 
$user_role_code = $_SESSION["role"] ?? 0; 
$current_user_school_id = $_SESSION["school_id"] ?? 0; 

$phone_number = $photo = $status = ""; 
$school_name = $_L['school_name_not_found']; 
$school_logo_path = "images/default_school_logo.png"; 

$totalStudentsInMyClasses = 0; 
$pendingAssignmentsToGrade = 0; 
$unreadMessages = 0; 
$upcomingLessons = 0; 
$announcements = []; 
$teacher_has_assignments = false;

if (isset($conn) && $conn instanceof mysqli) {
    // 1. User & School
    $sql = "SELECT u.phone_number, u.photo, u.status, s.school_name, s.logo 
            FROM users u 
            JOIN schools s ON u.school_id = s.school_id 
            WHERE u.id = ? AND u.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, $school_name_db, $school_logo_db); 
            if($stmt->fetch()) {
                $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
                // Brand Blue Background for Avatar
                $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://ui-avatars.com/api/?name='.urlencode($username).'&background=0a66c2&color=fff&size=128'; 
                $status = htmlspecialchars($status_db ?? 'N/A');
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        } 
        $stmt->close(); 
    }

    // 2. Check Assignments
    $sql_check = "SELECT COUNT(*) as assignment_count FROM class_teachers WHERE teacher_user_id = ?";
    if ($stmt_check = $conn->prepare($sql_check)) {
        $stmt_check->bind_param("i", $user_id);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();
        $assignment_count = $result_check->fetch_assoc()['assignment_count'];
        $stmt_check->close();
        $teacher_has_assignments = ($assignment_count > 0);
    }

    // 3. Stats
    if ($teacher_has_assignments) {
        $sql_students = "SELECT COUNT(DISTINCT u.id) FROM users u JOIN class_teachers ct ON u.class_id = ct.class_id JOIN classes c ON ct.class_id = c.class_id WHERE u.role = 3 AND u.status = 'active' AND ct.teacher_user_id = ? AND u.school_id = ? AND c.school_id = ?";
        if ($stmt = $conn->prepare($sql_students)) {
            $stmt->bind_param("iii", $user_id, $current_user_school_id, $current_user_school_id);
            if ($stmt->execute()) { $stmt->bind_result($totalStudentsInMyClasses); $stmt->fetch(); }
            $stmt->close();
        }

        $sql_assign = "SELECT COUNT(assignment_id) FROM assignments WHERE teacher_user_id = ? AND school_id = ? AND due_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)";
        if ($stmt = $conn->prepare($sql_assign)) {
            $stmt->bind_param("ii", $user_id, $current_user_school_id);
            if ($stmt->execute()) { $stmt->bind_result($pendingAssignmentsToGrade); $stmt->fetch(); }
            $stmt->close();
        }

        $sql_msg = "SELECT COUNT(id) FROM messages WHERE receiver_id = ? AND school_id = ? AND status = 'Unread'";
        if ($stmt = $conn->prepare($sql_msg)) {
            $stmt->bind_param("ii", $user_id, $current_user_school_id);
            if ($stmt->execute()) { $stmt->bind_result($unreadMessages); $stmt->fetch(); }
            $stmt->close();
        }

        $sql_less = "SELECT COUNT(DISTINCT ct.class_id) FROM class_teachers ct JOIN classes c ON ct.class_id = c.class_id WHERE ct.teacher_user_id = ? AND c.school_id = ?";
        if ($stmt = $conn->prepare($sql_less)) {
            $stmt->bind_param("ii", $user_id, $current_user_school_id);
            if ($stmt->execute()) { $stmt->bind_result($upcomingLessons); $stmt->fetch(); }
            $stmt->close();
        }
    }

    // 4. Announcements
    $sql_ann = "SELECT title, content, created_at FROM announcements WHERE school_id = ? ORDER BY created_at DESC LIMIT 4";
    if ($stmt = $conn->prepare($sql_ann)) {
        $stmt->bind_param("i", $current_user_school_id);
        if ($stmt->execute()) {
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) $announcements[] = $row;
        }
        $stmt->close();
    }
    $conn->close(); 
}

$role_name = "Teacher";

// Calendar
$current_day = date('d'); 
$current_month_num = date('m'); 
$current_year = date('Y'); 
$num_days_in_month = cal_days_in_month(CAL_GREGORIAN, $current_month_num, $current_year); 
$first_day_of_month_timestamp = mktime(0, 0, 0, $current_month_num, 1, $current_year); 
$first_day_of_week = date('N', mktime(0, 0, 0, $current_month_num, 1, $current_year)); 
$current_month_name = date('F', mktime(0, 0, 0, $current_month_num, 1, $current_year)); 
?>

<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#ffffff">
    <title><?php echo $_L['sidebar_dashboard']; ?> | <?php echo htmlspecialchars($school_name); ?></title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        body { 
            font-family: 'Inter', sans-serif;
            background-color: #f3f2ef; /* LinkedIn Canvas */
            color: #191919;
        }
        
        /* Premium Scrollbar */
        ::-webkit-scrollbar { width: 5px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #b0b0b0; border-radius: 20px; }

        /* Animation */
        #mobile-search-bar { transition: transform 0.3s cubic-bezier(0.2, 0.8, 0.2, 1); transform-origin: top; }

        /* Card Styling */
        .card {
            background: white;
            border-radius: 8px; /* Standard Corporate Radius */
            border: 1px solid #e0dfdc; /* Subtle border */
            transition: box-shadow 0.2s ease;
        }
        .card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        /* --- SIDEBAR RE-DESIGN --- */
        .sidebar-desktop {
            background-color: #ffffff;
            border-right: 1px solid #e0dfdc;
        }
        
        /* The "Left Border" Active State */
        .sidebar-link {
            display: flex;
            align-items: center;
            padding: 12px 24px;
            color: #5E5E5E; /* Neutral Gray */
            font-weight: 500;
            font-size: 0.95rem;
            border-left: 4px solid transparent; /* Hidden border by default */
            transition: all 0.2s ease;
        }
        .sidebar-link:hover {
            background-color: #f3f2ef; /* Light hover gray */
            color: #191919;
        }
        .sidebar-link.active {
            border-left-color: #0a66c2; /* Brand Blue */
            background-color: white; /* Keep white, let border do the work */
            color: #0a66c2;
            font-weight: 600;
        }
        .sidebar-link i { width: 24px; margin-right: 12px; font-size: 1.1rem; }

        /* Mobile Nav */
        .nav-item { color: #666666; }
        .nav-item.active { color: #0a66c2; }
        .nav-item.active i { transform: translateY(-2px); transition: transform 0.2s; }

        /* Dropdowns */
        #language-dropdown, #desktop-lang-menu { transition: all 0.15s ease; }
        .hidden { display: none; }

        /* Utilities */
        @media (min-width: 1024px) {
            .mobile-only { display: none !important; }
            .sidebar-desktop { display: flex !important; }
            .main-content { margin-left: 260px; }
        }
        @media (max-width: 1023px) {
            .desktop-only { display: none !important; }
            .sidebar-desktop { display: none !important; }
            .main-content { margin-left: 0; padding-bottom: 90px; }
        }
    </style>
</head>
<body class="antialiased">

    <aside class="sidebar-desktop fixed h-full z-50 flex-col w-[260px]">
        <div class="h-16 flex items-center px-6 border-b border-gray-200 bg-white">
            <img src="<?php echo $school_logo_path; ?>" alt="Logo" class="h-8 w-8 object-contain mr-2">
            <div>
                <h1 class="font-bold text-[#0a66c2] text-sm tracking-tight">DIVINE REPORTS</h1>
            </div>
        </div>
        
        <nav class="flex-1 overflow-y-auto py-4">
            <a href="teacher_dashboard.php" class="sidebar-link active"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a>
            <a href="teacher_my_classes.php" class="sidebar-link"><i class="fas fa-chalkboard"></i> <?php echo $_L['sidebar_my_classes']; ?></a>
            <a href="teacher_my_students.php" class="sidebar-link"><i class="fas fa-user-graduate"></i> <?php echo $_L['sidebar_my_students']; ?></a>
            <a href="create_assignment.php" class="sidebar-link"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a>
            <a href="teacher_exams.php" class="sidebar-link"><i class="fas fa-award"></i> <?php echo $_L['sidebar_grades']; ?></a>
            <a href="teacher_messages.php" class="sidebar-link relative">
                <i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?>
                <?php if($unreadMessages > 0): ?>
                    <span class="absolute right-4 top-1/2 -translate-y-1/2 w-2 h-2 bg-red-500 rounded-full"></span>
                <?php endif; ?>
            </a>
            <a href="teacher_calendar.php" class="sidebar-link"><i class="far fa-calendar-alt"></i> <?php echo $_L['sidebar_calendar']; ?></a>
        </nav>

        <div class="p-4 border-t border-gray-200">
            <a href="logout.php" class="flex items-center px-4 py-2 text-gray-500 hover:text-red-600 transition-colors text-sm font-semibold">
                <i class="fas fa-sign-out-alt mr-3"></i> <?php echo $_L['sidebar_logout']; ?>
            </a>
        </div>
    </aside>

    <header class="mobile-only fixed top-0 w-full bg-white z-40 px-4 py-3 border-b border-gray-200 flex justify-between items-center shadow-sm">
        <div class="flex items-center gap-2">
            <img src="<?php echo $school_logo_path; ?>" class="h-8 w-8 object-contain rounded">
            <h1 class="font-bold text-[#0a66c2] text-sm truncate max-w-[150px]"><?php echo htmlspecialchars($school_name); ?></h1>
        </div>
        <div class="flex items-center gap-3">
             <button onclick="toggleMobileSearch()" class="text-gray-500 hover:text-[#0a66c2] p-2 rounded-full transition-colors">
                <i class="fas fa-search text-lg"></i>
             </button>
             <button onclick="toggleMobileLanguageMenu(true)" class="text-xl p-1 rounded hover:bg-gray-100 transition-colors">
                <?php echo ($current_lang === 'lug') ? '🇺🇬' : (($current_lang === 'sw') ? '🇹🇿' : '🇺🇸'); ?>
             </button>
             <div class="h-8 w-8 rounded-full bg-gray-200 overflow-hidden border border-gray-300">
                <img src="<?php echo $photo; ?>" alt="User" class="h-full w-full object-cover">
            </div>
        </div>
    </header>

    <div id="mobile-search-bar" class="mobile-only fixed top-14 left-0 w-full bg-white border-b border-gray-200 p-4 z-30 transform -translate-y-[150%] shadow-lg">
        <div class="relative">
            <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-[#0a66c2]"></i>
            <input type="text" id="mobile-search-input" onkeyup="handleSearch(this.value, 'mobile')" placeholder="<?php echo $_L['search_placeholder']; ?>" class="w-full bg-gray-100 border-none rounded-full pl-10 pr-10 py-2 text-sm focus:ring-2 focus:ring-[#0a66c2]">
            <button onclick="toggleMobileSearch()" class="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 p-1">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div id="mobile-search-results" class="hidden mt-3 bg-white rounded-lg border border-gray-100 shadow-sm max-h-60 overflow-y-auto"></div>
    </div>

    <header class="desktop-only fixed top-0 right-0 left-[260px] bg-white h-16 z-40 px-8 flex justify-between items-center border-b border-gray-200">
        <div class="flex items-center w-[400px] relative">
            <div class="relative w-full group">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-500"></i>
                <input type="text" id="desktop-search-input" onkeyup="handleSearch(this.value, 'desktop')" placeholder="<?php echo $_L['search_placeholder']; ?>" class="w-full bg-[#eef3f8] border-none rounded-md py-2 pl-10 pr-4 text-sm focus:bg-white focus:ring-2 focus:ring-[#0a66c2] transition-all">
            </div>
            <div id="desktop-search-results" class="absolute top-12 left-0 w-full bg-white rounded-lg shadow-xl border border-gray-100 hidden p-2 z-50 transition-all"></div>
        </div>

        <div class="flex items-center gap-6">
            <div class="relative">
                <button onclick="toggleDesktopLanguageMenu()" class="flex items-center gap-2 text-gray-600 hover:text-[#0a66c2] transition-colors font-medium text-sm">
                    <span class="text-lg"><?php echo ($current_lang === 'lug') ? '🇺🇬' : (($current_lang === 'sw') ? '🇹🇿' : '🇺🇸'); ?></span>
                    <span class="uppercase"><?php echo $current_lang; ?></span>
                    <i class="fas fa-chevron-down text-xs ml-1"></i>
                </button>
                <div id="desktop-lang-menu" class="absolute right-0 top-8 w-40 bg-white rounded-lg shadow-xl border border-gray-100 hidden z-[60] overflow-hidden">
                    <ul class="py-1">
                        <li><a href="?lang=en" class="flex items-center px-4 py-2.5 text-sm hover:bg-gray-50 text-gray-700 transition-colors"><span class="mr-3 text-lg">🇺🇸</span> English</a></li>
                        <li><a href="?lang=lug" class="flex items-center px-4 py-2.5 text-sm hover:bg-gray-50 text-gray-700 transition-colors"><span class="mr-3 text-lg">🇺🇬</span> Luganda</a></li>
                        <li><a href="?lang=sw" class="flex items-center px-4 py-2.5 text-sm hover:bg-gray-50 text-gray-700 transition-colors"><span class="mr-3 text-lg">🇹🇿</span> Kiswahili</a></li>
                    </ul>
                </div>
            </div>
            
            <div class="flex items-center gap-3 pl-6 border-l border-gray-200">
                <div class="text-right">
                    <p class="text-sm font-semibold text-gray-900"><?php echo $username; ?></p>
                    <p class="text-xs text-gray-500 uppercase"><?php echo $role_name; ?></p>
                </div>
                <img src="<?php echo $photo; ?>" class="h-9 w-9 rounded-full border border-gray-200 object-cover">
            </div>
        </div>
    </header>

    <main class="main-content pt-20 lg:pt-24 px-4 lg:px-8 pb-10 min-h-screen">
        
        <div class="card p-5 mb-6 flex flex-col md:flex-row items-center justify-between border-l-4 border-l-[#0a66c2]">
            <div class="flex items-center gap-4 mb-4 md:mb-0 w-full md:w-auto">
                <img src="<?php echo $photo; ?>" alt="User" class="h-12 w-12 rounded-full border border-gray-200 object-cover">
                <div>
                    <h2 class="text-lg font-bold text-gray-900"><?php echo $_L['welcome_message_prefix']; ?>, <span class="text-[#0a66c2]"><?php echo $username; ?></span></h2>
                    <p class="text-gray-500 text-xs"><?php echo $_L['manage_records_text']; ?></p>
                </div>
            </div>
            <a href="teacher_my_classes.php" class="w-full md:w-auto text-center bg-[#0a66c2] hover:bg-[#004182] text-white px-5 py-2 rounded-full text-sm font-semibold transition shadow-sm">
                <?php echo $_L['view_my_classes_button']; ?>
            </a>
        </div>

        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="card p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="h-10 w-10 flex items-center justify-center bg-[#e7f3ff] rounded text-[#0a66c2]"><i class="fas fa-users text-lg"></i></div>
                    <span class="text-[10px] font-bold text-green-700 bg-green-50 px-2 py-0.5 rounded border border-green-100">Active</span>
                </div>
                <h3 class="text-2xl font-bold text-gray-900"><?php echo $totalStudentsInMyClasses; ?></h3>
                <p class="text-xs text-gray-500 font-medium mt-1"><?php echo $_L['stat_students_label']; ?></p>
            </div>

            <div class="card p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="h-10 w-10 flex items-center justify-center bg-amber-50 rounded text-amber-600"><i class="fas fa-file-alt text-lg"></i></div>
                </div>
                <h3 class="text-2xl font-bold text-gray-900"><?php echo $pendingAssignmentsToGrade; ?></h3>
                <p class="text-xs text-gray-500 font-medium mt-1"><?php echo $_L['stat_assignments_label']; ?></p>
            </div>

            <div class="card p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="h-10 w-10 flex items-center justify-center bg-purple-50 rounded text-purple-600"><i class="fas fa-envelope text-lg"></i></div>
                </div>
                <h3 class="text-2xl font-bold text-gray-900"><?php echo $unreadMessages; ?></h3>
                <p class="text-xs text-gray-500 font-medium mt-1"><?php echo $_L['stat_messages_label']; ?></p>
            </div>

            <div class="card p-4">
                <div class="flex justify-between items-start mb-2">
                    <div class="h-10 w-10 flex items-center justify-center bg-teal-50 rounded text-teal-600"><i class="fas fa-calendar-check text-lg"></i></div>
                </div>
                <h3 class="text-2xl font-bold text-gray-900"><?php echo $upcomingLessons; ?></h3>
                <p class="text-xs text-gray-500 font-medium mt-1"><?php echo $_L['stat_lessons_label']; ?></p>
            </div>
        </div>

        <div class="grid lg:grid-cols-3 gap-6">
            <div class="lg:col-span-2 card p-6">
                <div class="flex justify-between items-center mb-4 border-b border-gray-100 pb-3">
                    <h3 class="font-bold text-gray-900"><?php echo $_L['school_announcements_heading']; ?></h3>
                    <a href="#" class="text-xs font-bold text-gray-500 hover:text-[#0a66c2] uppercase tracking-wide"><?php echo $_L['view_all_button']; ?></a>
                </div>
                
                <div class="space-y-3">
                    <?php if (empty($announcements)): ?>
                        <div class="text-center py-8">
                            <i class="fas fa-inbox text-3xl text-gray-300 mb-2"></i>
                            <p class="text-sm text-gray-400"><?php echo $_L['no_announcements']; ?></p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($announcements as $announcement): ?>
                            <div class="flex gap-3 p-3 rounded hover:bg-gray-50 transition-colors cursor-pointer border-b border-gray-50 last:border-0">
                                <div class="flex-shrink-0 w-12 h-12 bg-[#f3f2ef] rounded flex flex-col items-center justify-center text-[#0a66c2] border border-gray-200">
                                    <span class="text-[9px] font-bold uppercase"><?php echo date('M', strtotime($announcement['created_at'])); ?></span>
                                    <span class="text-lg font-bold leading-none"><?php echo date('d', strtotime($announcement['created_at'])); ?></span>
                                </div>
                                <div>
                                    <h4 class="text-sm font-semibold text-gray-900 hover:text-[#0a66c2] transition-colors mb-0.5"><?php echo htmlspecialchars($announcement['title']); ?></h4>
                                    <p class="text-xs text-gray-500 line-clamp-2"><?php echo nl2br(htmlspecialchars($announcement['content'])); ?></p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card p-6 h-fit">
                <div class="flex justify-between items-center mb-4 border-b border-gray-100 pb-3">
                    <h3 class="font-bold text-gray-900"><?php echo $current_month_name . ' ' . $current_year; ?></h3>
                </div>
                <div class="grid grid-cols-7 gap-1 text-center mb-2">
                    <?php foreach([$_L['day_mon'], $_L['day_tue'], $_L['day_wed'], $_L['day_thu'], $_L['day_fri'], $_L['day_sat'], $_L['day_sun']] as $day): ?>
                        <div class="text-[10px] font-bold text-gray-400 uppercase"><?php echo $day; ?></div>
                    <?php endforeach; ?>
                </div>
                <div class="grid grid-cols-7 gap-1 text-center">
                    <?php
                    for ($i = 1; $i < $first_day_of_week; $i++) echo '<div></div>';
                    for ($day = 1; $day <= $num_days_in_month; $day++) {
                        $isToday = ($day == $current_day && $current_month_num == date('m') && $current_year == date('Y'));
                        $class = $isToday ? 'bg-[#0a66c2] text-white font-bold shadow-sm' : 'text-gray-600 hover:bg-gray-100 font-medium';
                        echo "<div class='aspect-square flex items-center justify-center text-xs rounded cursor-pointer transition-all $class'>$day</div>";
                    }
                    ?>
                </div>
            </div>
        </div>
    </main>

    <nav class="mobile-only fixed bottom-0 left-0 w-full bg-white border-t border-gray-200 z-50 flex justify-around items-center h-[70px] pb-safe shadow-[0_-4px_10px_rgba(0,0,0,0.05)]">
        <a href="teacher_dashboard.php" class="nav-item active flex flex-col items-center justify-center w-full h-full transition-colors">
            <i class="fas fa-th-large text-xl mb-1"></i>
            <span class="text-[10px] font-semibold"><?php echo $_L['sidebar_dashboard']; ?></span>
        </a>
        <a href="teacher_my_classes.php" class="nav-item flex flex-col items-center justify-center w-full h-full hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-chalkboard text-xl mb-1"></i>
            <span class="text-[10px] font-medium"><?php echo $_L['sidebar_my_classes']; ?></span>
        </a>
        <a href="teacher_my_students.php" class="nav-item flex flex-col items-center justify-center w-full h-full hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-user-graduate text-xl mb-1"></i>
            <span class="text-[10px] font-medium"><?php echo $_L['sidebar_my_students']; ?></span>
        </a>
        <button onclick="toggleMoreMenu(true)" class="nav-item flex flex-col items-center justify-center w-full h-full hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-ellipsis-h text-xl mb-1"></i>
            <span class="text-[10px] font-medium"><?php echo $_L['more_menu']; ?></span>
        </button>
    </nav>

    <div id="mobileLanguageMenuBackdrop" onclick="toggleMobileLanguageMenu(false)" class="fixed inset-0 bg-black/40 z-[70] hidden transition-opacity opacity-0"></div>
    <div id="mobileLanguageMenu" class="mobile-only fixed bottom-0 left-0 w-full bg-white rounded-t-xl z-[80] transform translate-y-full transition-transform duration-300 ease-out shadow-2xl pb-safe">
        <div class="w-10 h-1 bg-gray-300 rounded-full mx-auto my-3"></div>
        <div class="px-6 pb-4 border-b border-gray-100">
            <h3 class="font-bold text-lg text-gray-800 text-center"><?php echo $_L['select_language']; ?></h3>
        </div>
        <div class="p-4 space-y-2">
            <a href="?lang=en" class="flex items-center px-4 py-3 rounded-lg border border-gray-200 hover:bg-gray-50 transition-all <?php echo ($current_lang === 'en') ? 'border-[#0a66c2] bg-[#e7f3ff] text-[#0a66c2]' : ''; ?>">
                <span class="text-2xl mr-3">🇺🇸</span>
                <span class="font-semibold text-gray-700">English</span>
            </a>
            <a href="?lang=lug" class="flex items-center px-4 py-3 rounded-lg border border-gray-200 hover:bg-gray-50 transition-all <?php echo ($current_lang === 'lug') ? 'border-[#0a66c2] bg-[#e7f3ff] text-[#0a66c2]' : ''; ?>">
                <span class="text-2xl mr-3">🇺🇬</span>
                <span class="font-semibold text-gray-700">Luganda</span>
            </a>
            <a href="?lang=sw" class="flex items-center px-4 py-3 rounded-lg border border-gray-200 hover:bg-gray-50 transition-all <?php echo ($current_lang === 'sw') ? 'border-[#0a66c2] bg-[#e7f3ff] text-[#0a66c2]' : ''; ?>">
                <span class="text-2xl mr-3">🇹🇿</span>
                <span class="font-semibold text-gray-700">Kiswahili</span>
            </a>
        </div>
    </div>

    <div id="moreMenuBackdrop" onclick="toggleMoreMenu(false)" class="fixed inset-0 bg-black/40 z-[60] hidden transition-opacity opacity-0"></div>
    <div id="moreMenu" class="mobile-only fixed bottom-0 left-0 w-full bg-white rounded-t-xl z-[70] transform translate-y-full transition-transform duration-300 ease-out shadow-2xl pb-safe">
        <div class="w-10 h-1 bg-gray-300 rounded-full mx-auto my-3"></div>
        <div class="grid grid-cols-3 gap-3 p-5">
            <a href="create_assignment.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-amber-600 mb-1 text-xl"><i class="fas fa-file-alt"></i></div><span class="text-[10px] font-bold text-gray-600"><?php echo $_L['sidebar_assignments']; ?></span></a>
            <a href="teacher_exams.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-blue-600 mb-1 text-xl"><i class="fas fa-award"></i></div><span class="text-[10px] font-bold text-gray-600"><?php echo $_L['sidebar_grades']; ?></span></a>
            <a href="teacher_messages.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-purple-600 mb-1 text-xl"><i class="fas fa-envelope"></i></div><span class="text-[10px] font-bold text-gray-600"><?php echo $_L['sidebar_messages']; ?></span></a>
            <a href="teacher_calendar.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-teal-600 mb-1 text-xl"><i class="far fa-calendar-alt"></i></div><span class="text-[10px] font-bold text-gray-600"><?php echo $_L['sidebar_calendar']; ?></span></a>
            <a href="teacher_settings.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-gray-600 mb-1 text-xl"><i class="fas fa-cog"></i></div><span class="text-[10px] font-bold text-gray-600"><?php echo $_L['sidebar_settings']; ?></span></a>
        </div>
        <div class="p-5 pt-0"><a href="logout.php" class="flex items-center justify-center w-full py-3 bg-gray-100 text-gray-700 rounded-lg font-bold"><i class="fas fa-sign-out-alt mr-2"></i> <?php echo $_L['sidebar_logout']; ?></a></div>
    </div>

    <script>
        function toggleDesktopLanguageMenu() {
            document.getElementById('desktop-lang-menu').classList.toggle('hidden');
        }

        const mobileLangBackdrop = document.getElementById('mobileLanguageMenuBackdrop');
        const mobileLangMenu = document.getElementById('mobileLanguageMenu');

        function toggleMobileLanguageMenu(show) {
            if (show) {
                mobileLangBackdrop.classList.remove('hidden');
                setTimeout(() => {
                    mobileLangBackdrop.classList.remove('opacity-0');
                    mobileLangMenu.classList.remove('translate-y-full');
                }, 10);
            } else {
                mobileLangBackdrop.classList.add('opacity-0');
                mobileLangMenu.classList.add('translate-y-full');
                setTimeout(() => {
                    mobileLangBackdrop.classList.add('hidden');
                }, 300);
            }
        }

        function handleSearch(query, mode) {
            let container = mode === 'desktop' ? document.getElementById('desktop-search-results') : document.getElementById('mobile-search-results');
            if(query.length > 2) {
                container.classList.remove('hidden');
                container.innerHTML = `<div class="p-3 text-sm text-gray-500 bg-white border-b">Searching for "${query}"...</div>`;
            } else { container.classList.add('hidden'); }
        }

        const moreMenu = document.getElementById('moreMenu');
        const moreMenuBackdrop = document.getElementById('moreMenuBackdrop');
        const mobileSearchBar = document.getElementById('mobile-search-bar');

        function toggleMoreMenu(show) {
            if (show) {
                if (!mobileSearchBar.classList.contains('-translate-y-[150%]')) toggleMobileSearch();
                moreMenuBackdrop.classList.remove('hidden');
                setTimeout(() => {
                    moreMenuBackdrop.classList.remove('opacity-0');
                    moreMenu.classList.remove('translate-y-full');
                }, 10);
            } else {
                moreMenuBackdrop.classList.add('opacity-0');
                moreMenu.classList.add('translate-y-full');
                setTimeout(() => {
                    moreMenuBackdrop.classList.add('hidden');
                }, 300);
            }
        }

        function toggleMobileSearch() {
            if (mobileSearchBar.classList.contains('-translate-y-[150%]')) {
                mobileSearchBar.classList.remove('-translate-y-[150%]');
                mobileSearchBar.classList.add('translate-y-0');
            } else {
                mobileSearchBar.classList.add('-translate-y-[150%]');
                mobileSearchBar.classList.remove('translate-y-0');
            }
        }

        document.addEventListener('click', function(event) {
            const menu = document.getElementById('desktop-lang-menu');
            const trigger = event.target.closest('button');
            if (!trigger && menu && !menu.classList.contains('hidden')) {
                menu.classList.add('hidden');
            }
        });
    </script>
</body>
</html>