<?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',
            'page_title' => 'My Assigned Classes',
            'page_subtitle' => 'Subjects and streams currently assigned to you.',
            'label_term' => 'Term',
            'label_year' => 'Year',
            'label_students' => 'Students',
            'no_classes' => 'No classes assigned yet.',
            'more_menu' => 'More',
            'search_placeholder' => 'Search classes...',
            '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',
            'page_title' => 'Ebibiina Byange',
            'page_subtitle' => 'Ebibiina n\'amasomo agakuweereddwa.',
            'label_term' => 'Ekkambi',
            'label_year' => 'Omwaka',
            'label_students' => 'Abayizi',
            'no_classes' => 'Tewali bibiina bikuweereddwa.',
            'more_menu' => 'Ebirala',
            'search_placeholder' => 'Noonya...',
            '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',
            'page_title' => 'Madarasa Yangu',
            'page_subtitle' => 'Masomo na mikondo uliyopewa.',
            'label_term' => 'Muhula',
            'label_year' => 'Mwaka',
            'label_students' => 'Wanafunzi',
            'no_classes' => 'Hakuna madarasa uliyopewa bado.',
            'more_menu' => 'Zaidi',
            'search_placeholder' => 'Tafuta...',
            '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 = 'my_classes'; // For sidebar highlighting
$user_id = $_SESSION["id"] ?? 0; 
$username = htmlspecialchars($_SESSION["username"] ?? 'User'); 
$school_id = $_SESSION["school_id"] ?? 0; 

// Initial Data
$school_name = "Divine Reports";
$school_logo_path = "images/default_school_logo.png";
$photo = "images/default.png";
$assignedClassesSubjects = [];

if (isset($conn) && $conn instanceof mysqli) {
    
    // 1. Fetch Header Data
    $sql_user = "SELECT u.photo, 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_user)) {
        $stmt->bind_param("ii", $user_id, $school_id);
        if ($stmt->execute()) {
            $stmt->bind_result($photo_db, $school_name_db, $school_logo_db);
            if ($stmt->fetch()) {
                $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'https://ui-avatars.com/api/?name='.urlencode($username).'&background=0a66c2&color=fff&size=128';
                $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. Fetch Assigned Classes
    $sql_classes = "
        SELECT
            c.class_name,
            COALESCE(s.stream_name, '') as stream_name,
            sub.subject_name,
            cst.academic_year,
            cst.term,
            (SELECT COUNT(*) FROM users u WHERE u.class_id = c.class_id AND u.role = 3 AND u.status = 'active') as student_count
        FROM class_subject_teachers cst
        JOIN classes c ON cst.class_id = c.class_id
        LEFT JOIN streams s ON cst.stream_id = s.stream_id
        JOIN subjects sub ON cst.subject_id = sub.subject_id
        WHERE cst.teacher_user_id = ? AND cst.school_id = ?
        ORDER BY cst.academic_year DESC, cst.term DESC, c.class_name ASC
    ";

    if ($stmt = $conn->prepare($sql_classes)) {
        $stmt->bind_param("ii", $user_id, $school_id);
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $assignedClassesSubjects[] = $row;
            }
        }
        $stmt->close();
    }
    $conn->close();
}
?>

<!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="#0a66c2">
    <title><?php echo $_L['page_title']; ?> | <?php echo $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;
        }
        
        /* Sidebar Styling */
        .sidebar-desktop {
            background-color: #ffffff;
            border-right: 1px solid #e0dfdc;
        }
        
        .sidebar-link {
            display: flex;
            align-items: center;
            padding: 12px 24px;
            color: #666666;
            font-weight: 600;
            font-size: 0.95rem;
            border-left: 4px solid transparent;
            transition: all 0.2s ease;
        }
        .sidebar-link:hover { background-color: #f3f2ef; color: #191919; }
        .sidebar-link.active { border-left-color: #0a66c2; background-color: white; color: #0a66c2; }
        .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); }

        /* --- NEW CARD DESIGN (Grid Layout) --- */
        .class-card {
            background: white;
            border-radius: 12px;
            border: 1px solid #e0e0e0;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        .class-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.08);
            border-color: #0a66c2;
        }
        /* Color Accent Bar at top of card */
        .class-card::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 4px;
            background: #0a66c2;
        }

        /* 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: 80px; }
        }
    </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"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a>
            <a href="teacher_my_classes.php" class="sidebar-link active"><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"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></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">
             <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>

    <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">
        <h2 class="text-lg font-bold text-gray-800"><?php echo $_L['page_title']; ?></h2>
        <div class="flex items-center gap-4">
            <div class="text-right">
                <p class="text-sm font-semibold text-gray-900"><?php echo $username; ?></p>
                <p class="text-xs text-gray-500">Teacher</p>
            </div>
            <img src="<?php echo $photo; ?>" class="h-9 w-9 rounded-full border border-gray-200 object-cover">
        </div>
    </header>

    <main class="main-content pt-20 lg:pt-24 px-4 lg:px-8 pb-10 min-h-screen">
        
        <div class="mb-6">
            <h1 class="text-xl md:text-2xl font-bold text-gray-900 lg:hidden mb-1"><?php echo $_L['page_title']; ?></h1>
            <p class="text-sm text-gray-500"><?php echo $_L['page_subtitle']; ?></p>
        </div>

        <?php if (empty($assignedClassesSubjects)): ?>
            <div class="flex flex-col items-center justify-center bg-white rounded-lg p-12 border border-gray-200 shadow-sm text-center">
                <div class="bg-gray-50 p-4 rounded-full mb-4">
                    <i class="fas fa-folder-open text-4xl text-gray-300"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-700 mb-1"><?php echo $_L['no_classes']; ?></h3>
                <p class="text-gray-500 text-sm">Contact your admin to get started.</p>
            </div>
        <?php else: ?>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <?php foreach ($assignedClassesSubjects as $row): ?>
                <div class="class-card p-5 flex flex-col justify-between h-full">
                    
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <span class="inline-block px-2 py-1 bg-gray-100 text-gray-600 text-[10px] font-bold uppercase tracking-wide rounded mb-2">
                                <?php echo htmlspecialchars($row['academic_year']); ?> • Term <?php echo htmlspecialchars($row['term']); ?>
                            </span>
                            <h3 class="font-bold text-xl text-gray-900 leading-tight">
                                <?php echo htmlspecialchars($row['class_name']); ?>
                            </h3>
                            <?php if(!empty($row['stream_name'])): ?>
                                <p class="text-sm text-[#0a66c2] font-semibold mt-0.5"><?php echo htmlspecialchars($row['stream_name']); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="h-10 w-10 bg-blue-50 rounded-full flex items-center justify-center text-[#0a66c2] text-lg">
                            <i class="fas fa-chalkboard-teacher"></i>
                        </div>
                    </div>

                    <div class="space-y-3 mb-6">
                        <div class="flex items-center text-gray-600 text-sm">
                            <i class="fas fa-book w-5 text-gray-400"></i>
                            <span class="font-medium truncate" title="<?php echo htmlspecialchars($row['subject_name']); ?>">
                                <?php echo htmlspecialchars($row['subject_name']); ?>
                            </span>
                        </div>
                        <div class="flex items-center text-gray-600 text-sm">
                            <i class="fas fa-users w-5 text-gray-400"></i>
                            <span><?php echo $row['student_count'] ?? 0; ?> Students</span>
                        </div>
                    </div>

                    <div class="pt-4 border-t border-gray-100 mt-auto flex items-center justify-between text-xs text-gray-400">
                        <span><i class="fas fa-info-circle mr-1"></i> Assignment Info</span>
                        <span class="font-medium text-gray-500">Active</span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

        <?php endif; ?>
    </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 flex flex-col items-center justify-center w-full h-full text-gray-500 hover:text-[#0a66c2] 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 active flex flex-col items-center justify-center w-full h-full transition-colors">
            <i class="fas fa-chalkboard text-xl mb-1"></i>
            <span class="text-[10px] font-semibold"><?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 text-gray-500 hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-user-graduate text-xl mb-1"></i>
            <span class="text-[10px] font-semibold"><?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 text-gray-500 hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-ellipsis-h text-xl mb-1"></i>
            <span class="text-[10px] font-semibold"><?php echo $_L['more_menu']; ?></span>
        </button>
    </nav>

    <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>
        const moreMenu = document.getElementById('moreMenu');
        const moreMenuBackdrop = document.getElementById('moreMenuBackdrop');

        function toggleMoreMenu(show) {
            if (show) {
                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);
            }
        }
    </script>
</body>
</html>