<?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'];

// Auth Check
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
    header("location: login.php"); exit; 
}
if ($_SESSION["role"] !== ROLE_TEACHER) {
    header("location: login.php"); exit; 
}

$user_id = $_SESSION["id"]; 
$school_id = $_SESSION["school_id"]; 
$username = htmlspecialchars($_SESSION["username"]); 
$role_name = "Teacher";

// --- AJAX HANDLER FOR SEARCH & PAGINATION ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'fetch_students') {
    header('Content-Type: application/json');
    
    $page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    
    $class_id = isset($_POST['class_id']) && $_POST['class_id'] != '' ? $_POST['class_id'] : null;
    $stream_id = isset($_POST['stream_id']) && $_POST['stream_id'] != '' ? $_POST['stream_id'] : null;
    $search = isset($_POST['search']) ? trim($_POST['search']) : '';

    // Base Query Logic: Students in classes assigned to this teacher
    $where_clauses = ["u.school_id = ? AND u.role = 3"];
    $params = [$school_id];
    $types = "i";

    $where_clauses[] = "u.class_id IN (SELECT DISTINCT class_id FROM class_subject_teachers WHERE teacher_user_id = ? AND school_id = ?)";
    $params[] = $user_id;
    $params[] = $school_id;
    $types .= "ii";

    if ($class_id) {
        $where_clauses[] = "u.class_id = ?";
        $params[] = $class_id;
        $types .= "i";
    }
    if ($stream_id) {
        $where_clauses[] = "u.stream_id = ?";
        $params[] = $stream_id;
        $types .= "i";
    }
    if (!empty($search)) {
        $where_clauses[] = "(u.username LIKE ? OR u.ADM LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $types .= "ss";
    }

    $where_sql = implode(" AND ", $where_clauses);

    // 1. Get Total Count
    $count_sql = "SELECT COUNT(*) as total FROM users u WHERE $where_sql";
    $stmt = $conn->prepare($count_sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total_records = $stmt->get_result()->fetch_assoc()['total'];
    $total_pages = ceil($total_records / $limit);
    $stmt->close();

    // 2. Get Data
    $sql = "SELECT u.id, u.username, u.photo, u.ADM, u.status, u.phone_number, u.email, 
                   c.class_name, s.stream_name 
            FROM users u 
            JOIN classes c ON u.class_id = c.class_id 
            LEFT JOIN streams s ON u.stream_id = s.stream_id 
            WHERE $where_sql 
            ORDER BY u.username ASC 
            LIMIT ? OFFSET ?";
    
    $params[] = $limit;
    $params[] = $offset;
    $types .= "ii";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $students = [];
    while($row = $result->fetch_assoc()) {
        if(empty($row['photo'])) {
            $row['photo'] = 'https://ui-avatars.com/api/?name='.urlencode($row['username']).'&background=f3f2ef&color=0a66c2&bold=true';
        }
        $students[] = $row;
    }

    echo json_encode([
        'students' => $students,
        'pagination' => [
            'current' => $page,
            'total_pages' => $total_pages,
            'total_records' => $total_records
        ]
    ]);
    exit;
}

// Initial Data Loading
$teacher_photo = "images/default.png";
$classes = [];
$streams = [];

if (isset($conn) && $conn instanceof mysqli) {
    // Teacher Info
    $stmt = $conn->prepare("SELECT photo FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if($row = $res->fetch_assoc()) $teacher_photo = $row['photo'] ?: 'https://ui-avatars.com/api/?name='.urlencode($username).'&background=0a66c2&color=fff';
    $stmt->close();

    // Filters: Classes
    $c_sql = "SELECT DISTINCT c.class_id, c.class_name FROM classes c 
              JOIN class_subject_teachers cst ON c.class_id = cst.class_id 
              WHERE cst.teacher_user_id = ? ORDER BY c.class_name";
    $stmt = $conn->prepare($c_sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) $classes[] = $row;
    $stmt->close();

    // Filters: Streams
    $s_sql = "SELECT DISTINCT s.stream_id, s.stream_name FROM streams s 
              JOIN class_subject_teachers cst ON s.stream_id = cst.stream_id 
              WHERE cst.teacher_user_id = ? ORDER BY s.stream_name";
    $stmt = $conn->prepare($s_sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) $streams[] = $row;
    $stmt->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>My Students | Divine Reports</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; color: #191919; }
        
        /* Sidebar (Fixed & Full Height) */
        .sidebar-desktop { background-color: white; border-right: 1px solid #e0dfdc; }
        .sidebar-link { display: flex; align-items: center; padding: 12px 24px; color: #666; font-weight: 600; border-left: 4px solid transparent; transition: all 0.2s; }
        .sidebar-link:hover { background-color: #f3f2ef; color: #191919; }
        .sidebar-link.active { border-left-color: #0a66c2; background-color: white; color: #0a66c2; }
        
        /* Mobile Nav */
        .mobile-only { display: block; }
        @media (min-width: 1024px) { 
            .mobile-only { display: none !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; } 
        }

        /* Custom Select/Dropdowns */
        .custom-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
            background-position: right 0.5rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
            padding-right: 2.5rem;
        }

        /* Cards */
        .student-card {
            background: white; border-radius: 12px; border: 1px solid #e0dfdc;
            transition: all 0.2s ease; position: relative; overflow: hidden;
        }
        .student-card:hover { transform: translateY(-3px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-color: #0a66c2; }
        
        .status-active { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .status-inactive { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

        .loader { border: 3px solid #f3f3f3; border-radius: 50%; border-top: 3px solid #0a66c2; width: 24px; height: 24px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body class="antialiased">

    <aside class="sidebar-desktop fixed top-0 left-0 h-full z-50 flex-col w-[260px] hidden lg:flex">
        <div class="h-16 flex items-center px-6 border-b border-gray-200 bg-white">
            <img src="images/default_school_logo.png" class="h-8 w-8 object-contain mr-2">
            <h1 class="font-bold text-[#0a66c2] text-sm">DIVINE REPORTS</h1>
        </div>
        <nav class="flex-1 overflow-y-auto py-4">
            <a href="teacher_dashboard.php" class="sidebar-link"><i class="fas fa-th-large w-6"></i> Dashboard</a>
            <a href="teacher_my_classes.php" class="sidebar-link"><i class="fas fa-chalkboard w-6"></i> My Classes</a>
            <a href="teacher_my_students.php" class="sidebar-link active"><i class="fas fa-user-graduate w-6"></i> Students</a>
            <a href="create_assignment.php" class="sidebar-link"><i class="fas fa-file-alt w-6"></i> Assignments</a>
            <a href="teacher_exams.php" class="sidebar-link"><i class="fas fa-award w-6"></i> Grades</a>
            <a href="teacher_messages.php" class="sidebar-link"><i class="fas fa-envelope w-6"></i> Messages</a>
            <a href="teacher_calendar.php" class="sidebar-link"><i class="far fa-calendar-alt w-6"></i> 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 font-semibold"><i class="fas fa-sign-out-alt mr-3"></i> 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="images/default_school_logo.png" class="h-8 w-8 object-contain rounded">
            <h1 class="font-bold text-[#0a66c2] text-sm">Divine Reports</h1>
        </div>
        <img src="<?php echo $teacher_photo; ?>" class="h-8 w-8 rounded-full border border-gray-300 object-cover">
    </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">My Students</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 $teacher_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="bg-white p-4 rounded-xl shadow-sm border border-gray-200 mb-6 flex flex-col md:flex-row gap-4 items-center justify-between">
            <div class="relative w-full md:w-1/3">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                <input type="text" id="searchInput" placeholder="Search by name..." 
                       class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-full text-sm focus:ring-2 focus:ring-[#0a66c2] outline-none transition-all">
            </div>

            <div class="flex gap-2 w-full md:w-auto overflow-x-auto pb-1 md:pb-0">
                <select id="classFilter" class="custom-select border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-1 focus:ring-[#0a66c2] outline-none min-w-[140px]">
                    <option value="">All Classes</option>
                    <?php foreach($classes as $c): ?>
                        <option value="<?php echo $c['class_id']; ?>"><?php echo $c['class_name']; ?></option>
                    <?php endforeach; ?>
                </select>
                <select id="streamFilter" class="custom-select border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-1 focus:ring-[#0a66c2] outline-none min-w-[140px]">
                    <option value="">All Streams</option>
                    <?php foreach($streams as $s): ?>
                        <option value="<?php echo $s['stream_id']; ?>"><?php echo $s['stream_name']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div id="studentsGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5"></div>

        <div id="paginationControls" class="mt-8 flex justify-center items-center gap-2"></div>

        <div id="loadingIndicator" class="hidden flex justify-center py-10">
            <div class="loader"></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="text-gray-500 hover:text-[#0a66c2] 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-medium">Home</span>
        </a>
        <a href="teacher_my_classes.php" class="text-gray-500 hover:text-[#0a66c2] 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-medium">Classes</span>
        </a>
        <a href="teacher_my_students.php" class="text-[#0a66c2] flex flex-col items-center justify-center w-full h-full font-bold transition-colors">
            <i class="fas fa-user-graduate text-xl mb-1"></i><span class="text-[10px]">Students</span>
        </a>
        <button onclick="toggleMoreMenu(true)" class="text-gray-500 hover:text-[#0a66c2] flex flex-col items-center justify-center w-full h-full transition-colors">
            <i class="fas fa-ellipsis-h text-xl mb-1"></i><span class="text-[10px] font-medium">More</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="px-6 pb-2 border-b border-gray-100 flex justify-between items-center">
            <h3 class="font-bold text-lg text-gray-800">Menu</h3>
            <button onclick="toggleMoreMenu(false)" class="p-2 text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
        </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">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">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">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">Calendar</span></a>
            <a href="teacher_profile.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-indigo-600 mb-1 text-xl"><i class="fas fa-user-circle"></i></div><span class="text-[10px] font-bold text-gray-600">Profile</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">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> Logout</a></div>
    </div>

    <script>
        let currentPage = 1;
        let searchTimeout = null;

        document.addEventListener('DOMContentLoaded', () => { fetchStudents(1); });

        // Live Search Debounce
        document.getElementById('searchInput').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => { currentPage = 1; fetchStudents(1); }, 400);
        });

        document.getElementById('classFilter').addEventListener('change', () => { currentPage = 1; fetchStudents(1); });
        document.getElementById('streamFilter').addEventListener('change', () => { currentPage = 1; fetchStudents(1); });

        function fetchStudents(page) {
            document.getElementById('loadingIndicator').classList.remove('hidden');
            const formData = new FormData();
            formData.append('action', 'fetch_students');
            formData.append('page', page);
            formData.append('search', document.getElementById('searchInput').value);
            formData.append('class_id', document.getElementById('classFilter').value);
            formData.append('stream_id', document.getElementById('streamFilter').value);

            fetch('teacher_my_students.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                renderCards(data.students);
                renderPagination(data.pagination);
                document.getElementById('loadingIndicator').classList.add('hidden');
            })
            .catch(err => console.error(err));
        }

        function renderCards(students) {
            const grid = document.getElementById('studentsGrid');
            grid.innerHTML = '';
            if (students.length === 0) {
                grid.innerHTML = `<div class="col-span-full text-center py-10 text-gray-500"><i class="fas fa-user-slash text-4xl mb-3 text-gray-300"></i><p>No students found.</p></div>`;
                return;
            }
            students.forEach(s => {
                const statusClass = s.status === 'active' ? 'status-active' : 'status-inactive';
                const card = `
                    <div class="student-card p-5 flex flex-col items-center text-center">
                        <div class="relative mb-3">
                            <img src="${s.photo}" class="w-20 h-20 rounded-full object-cover border-4 border-[#f3f2ef]">
                            <span class="absolute bottom-0 right-0 w-5 h-5 bg-white rounded-full flex items-center justify-center">
                                <span class="w-3 h-3 rounded-full ${s.status === 'active' ? 'bg-green-500' : 'bg-red-500'}"></span>
                            </span>
                        </div>
                        <h3 class="font-bold text-gray-900 text-lg leading-tight mb-1">${s.username}</h3>
                        <p class="text-xs text-gray-500 font-mono bg-gray-100 px-2 py-1 rounded mb-3">ADM: ${s.ADM}</p>
                        <div class="w-full border-t border-gray-100 my-2 pt-2 flex justify-between items-center text-sm">
                            <div class="text-left">
                                <p class="text-[#0a66c2] font-bold">${s.class_name}</p>
                                <p class="text-xs text-gray-400">${s.stream_name}</p>
                            </div>
                            <div class="${statusClass} text-[10px] uppercase font-bold px-2 py-1 rounded-full">${s.status}</div>
                        </div>
                        <div class="flex gap-2 mt-3 w-full">
                            <a href="tel:${s.phone_number}" class="flex-1 py-1.5 border border-gray-200 rounded text-gray-500 hover:bg-gray-50 hover:text-[#0a66c2] transition"><i class="fas fa-phone"></i></a>
                            <a href="mailto:${s.email}" class="flex-1 py-1.5 border border-gray-200 rounded text-gray-500 hover:bg-gray-50 hover:text-[#0a66c2] transition"><i class="fas fa-envelope"></i></a>
                            <a href="teacher_student_profile.php?id=${s.id}" class="flex-1 py-1.5 bg-[#0a66c2] text-white rounded hover:bg-[#004182] transition"><i class="fas fa-arrow-right"></i></a>
                        </div>
                    </div>`;
                grid.innerHTML += card;
            });
        }

        function renderPagination(pg) {
            const container = document.getElementById('paginationControls');
            container.innerHTML = '';
            if (pg.total_pages <= 1) return;
            if (pg.current > 1) container.innerHTML += `<button onclick="currentPage--; fetchStudents(currentPage)" class="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50 text-gray-600"><i class="fas fa-chevron-left"></i></button>`;
            container.innerHTML += `<span class="px-4 py-1 text-sm text-gray-600">Page <b>${pg.current}</b> of ${pg.total_pages}</span>`;
            if (pg.current < pg.total_pages) container.innerHTML += `<button onclick="currentPage++; fetchStudents(currentPage)" class="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50 text-gray-600"><i class="fas fa-chevron-right"></i></button>`;
        }

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