<?php
/**
 * ===================================================================================
 * Manage Students Page (for Teachers) - Mobile Responsive
 * ===================================================================================
 *
 * File: manage_students.php
 * Location: /homework_portal/teacher/manage_students.php
 *
 * Purpose:
 * 1. Allows logged-in teachers to view and manage students in their assigned classes.
 * 2. Provides a responsive form to create new student accounts.
 * 3. Adapts for mobile, tablet, and desktop screens.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}
$teacher_id = $_SESSION['teacher_id'];
$teacher_full_name = e($_SESSION['teacher_full_name'] ?? 'Teacher');
$errors = [];
$success_message = '';

// --- Handle feedback messages ---
if(isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if(isset($_SESSION['error_message'])) {
    $errors[] = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

// --- Create student logic ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_student'])) {
    $full_name = trim($_POST['full_name'] ?? '');
    $index_number = trim($_POST['index_number'] ?? '');
    $class_id = (int)($_POST['class_id'] ?? 0);
    $parent_phone = trim($_POST['parent_phone'] ?? '');

    // Validation
    if (empty($full_name)) $errors[] = "Student's full name is required.";
    if (empty($index_number)) $errors[] = "Student's index number is required.";
    if (empty($class_id)) $errors[] = "You must select a class.";
    if (empty($parent_phone)) $errors[] = "Parent's phone number is required.";

    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT id FROM students WHERE index_number = ?");
        $stmt->execute([$index_number]);
        if ($stmt->fetch()) {
            $errors[] = "A student with this index number already exists.";
        }
    }

    if (empty($errors)) {
        $first_name = strtolower(explode(' ', $full_name)[0]);
        $password_hash = password_hash($index_number, PASSWORD_DEFAULT);
        $sql = "INSERT INTO students (full_name, username, password_hash, index_number, class_id, parent_phone) VALUES (?, ?, ?, ?, ?, ?)";
        try {
            $pdo->prepare($sql)->execute([$full_name, $first_name, $password_hash, $index_number, $class_id, $parent_phone]);
            $_SESSION['success_message'] = "Student '" . e($full_name) . "' created successfully!";
        } catch (PDOException $e) {
            $errors[] = "Database error: Could not create student account.";
        }
    }

    if(!empty($errors)) {
        $_SESSION['error_message'] = implode('<br>', $errors);
    }
    header("Location: manage_students.php");
    exit();
}

// --- Fetch data for display ---
try {
    // Fetch classes assigned to this teacher
    $classes_sql = "SELECT DISTINCT c.id, c.class_name FROM classes c JOIN teacher_subject_class tsc ON c.id = tsc.class_id WHERE tsc.teacher_id = ? ORDER BY c.class_name ASC";
    $class_stmt = $pdo->prepare($classes_sql);
    $class_stmt->execute([$teacher_id]);
    $assigned_classes = $class_stmt->fetchAll();

    // Fetch students in those classes
    $students_sql = "
        SELECT s.id, s.full_name, s.index_number, c.class_name, 
               (SELECT COUNT(pf.id) FROM student_private_files pf WHERE pf.student_id = s.id AND pf.is_read = 0) as unread_file_count
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.class_id IN (SELECT tsc.class_id FROM teacher_subject_class tsc WHERE tsc.teacher_id = ?) 
        ORDER BY c.class_name, s.full_name ASC
    ";
    $student_stmt = $pdo->prepare($students_sql);
    $student_stmt->execute([$teacher_id]);
    $students = $student_stmt->fetchAll();

    // Fetch counts for sidebar badges
    $unread_messages_count = $pdo->query("SELECT COUNT(id) FROM teacher_messages WHERE teacher_id = {$teacher_id} AND is_read = 0 AND sender_type = 'admin'")->fetchColumn();
    $new_submission_count = $pdo->query("SELECT COUNT(sub.id) FROM submissions sub JOIN assignments a ON sub.assignment_id = a.id LEFT JOIN teacher_seen_submissions tss ON sub.id = tss.submission_id AND tss.teacher_id = {$teacher_id} WHERE a.teacher_id = {$teacher_id} AND tss.submission_id IS NULL")->fetchColumn();

} catch (PDOException $e) {
    $assigned_classes = [];
    $students = [];
    $unread_messages_count = 0;
    $new_submission_count = 0;
    $errors[] = "Database error: Could not fetch school data.";
    error_log($e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Students - Teacher Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
        .sidebar-link { display: flex; align-items: center; padding: 0.75rem 1rem; border-radius: 0.5rem; transition: background-color 0.2s, color 0.2s; font-weight: 500;}
        .sidebar-link:hover, .sidebar-link.active { background-color: #e0f2fe; color: #0284c7; font-weight: 600; }
        .notification-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 22px; padding: 0 4px; border-radius: 9999px; background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; }
        
        /* Styles for Responsive Table */
        @media (max-width: 768px) {
            .responsive-table thead { display: none; }
            .responsive-table tr {
                display: block;
                margin-bottom: 1rem;
                border: 1px solid #ddd;
                border-radius: 0.5rem;
                padding: 1rem;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            }
            .responsive-table td {
                display: flex;
                justify-content: space-between;
                align-items: center;
                text-align: right;
                padding: 0.5rem 0;
                border-bottom: 1px solid #eee;
            }
            .responsive-table td:last-child {
                border-bottom: none;
                flex-direction: column;
                align-items: stretch;
                padding-top: 1rem;
            }
            .responsive-table td:last-child a {
                margin: 0.25rem 0;
                text-align: center;
                padding: 0.5rem;
                border-radius: 0.375rem;
                border: 1px solid #ddd;
            }
            .responsive-table td::before {
                content: attr(data-label);
                font-weight: 600;
                text-align: left;
                padding-right: 1rem;
            }
        }
    </style>
</head>
<body class="flex flex-col min-h-screen">
    <div class="relative min-h-screen md:flex">
        <!-- Mobile menu button -->
        <div class="md:hidden flex justify-between items-center bg-white p-4 shadow-md">
             <a href="dashboard.php">
                <h1 class="text-3xl font-bold text-red-600 font-sans">TTTEDDDEL</h1>
            </a>
            <button id="mobile-menu-button" class="text-gray-500 hover:text-blue-600 focus:outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path></svg>
            </button>
        </div>

        <!-- Sidebar Navigation -->
        <aside id="sidebar" class="w-64 bg-white shadow-md absolute inset-y-0 left-0 transform -translate-x-full md:relative md:translate-x-0 transition-transform duration-300 ease-in-out z-30">
            <div class="p-4 border-b text-center">
                <a href="dashboard.php">
                    <h1 class="text-4xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1>
                    <p class="text-xs font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p>
                    <p class="text-xs text-blue-800">by Ele Infocomm Technologies</p>
                </a>
            </div>
            <nav class="p-4 space-y-2">
                <a href="dashboard.php" class="sidebar-link"><span>Dashboard</span></a>
                <a href="inbox.php" class="sidebar-link flex justify-between items-center">
                    <span>Inbox</span>
                    <?php if ($unread_messages_count > 0): ?><span class="notification-badge"><?php echo $unread_messages_count; ?></span><?php endif; ?>
                </a>
                <a href="manage_students.php" class="sidebar-link active"><span>My Students</span></a>
                <a href="post_material.php" class="sidebar-link"><span>Post Material</span></a>
                <a href="my_materials.php" class="sidebar-link"><span>My Posted Materials</span></a>
                <a href="view_submissions.php" class="sidebar-link flex justify-between items-center">
                    <span>View Submissions</span>
                     <?php if ($new_submission_count > 0): ?><span class="notification-badge"><?php echo $new_submission_count; ?></span><?php endif; ?>
                </a>
            </nav>
        </aside>

        <!-- Main Content Area -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white shadow-sm border-b hidden md:flex"><div class="flex items-center justify-end p-4 w-full"><span class="text-gray-600 mr-4">Welcome, <?php echo $teacher_full_name; ?>!</span><a href="../logout.php" class="ml-2 py-2 px-4 bg-teal-600 text-white font-semibold rounded-lg shadow-md hover:bg-teal-700">Logout</a></div></header>
            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-4 md:p-6">
                <h2 class="text-3xl font-semibold text-gray-800">My Students</h2>

                <!-- Feedback Messages -->
                <?php if($success_message): ?><div class="p-4 my-4 text-sm text-green-700 bg-green-100 rounded-lg"><?php echo $success_message; ?></div><?php endif; ?>
                <?php if(!empty($errors)): ?><div class="p-4 my-4 text-sm text-red-700 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach($errors as $error) echo "<li>$error</li>"; ?></ul></div><?php endif; ?>
                
                <!-- Create Student Form -->
                <div class="mt-6 bg-white p-6 rounded-lg shadow">
                    <h3 class="text-xl font-semibold text-gray-800 mb-4">Create New Student Account</h3>
                    <form action="manage_students.php" method="POST" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 items-end">
                        <div>
                            <label for="full_name" class="block text-sm font-medium text-gray-700">Student's Full Name</label>
                            <input type="text" name="full_name" id="full_name" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                        </div>
                        <div>
                            <label for="index_number" class="block text-sm font-medium text-gray-700">Index Number (Password)</label>
                            <input type="text" name="index_number" id="index_number" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                        </div>
                        <div>
                            <label for="parent_phone" class="block text-sm font-medium text-gray-700">Parent's Phone</label>
                            <input type="tel" name="parent_phone" id="parent_phone" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                        </div>
                        <div>
                            <label for="class_id" class="block text-sm font-medium text-gray-700">Class</label>
                            <select name="class_id" id="class_id" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                                <option value="">Select a class</option>
                                <?php foreach($assigned_classes as $class): ?>
                                    <option value="<?php echo e($class['id']); ?>"><?php echo e($class['class_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="lg:col-span-3 text-center md:text-right">
                            <button type="submit" name="create_student" class="w-full md:w-auto px-6 py-2 bg-teal-600 text-white font-semibold rounded-lg shadow hover:bg-teal-700">Create Student</button>
                        </div>
                    </form>
                </div>

                <!-- Student List -->
                <div class="mt-8 bg-white shadow-lg rounded-lg overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 responsive-table">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Index Number</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php if(empty($students)): ?>
                                    <tr><td colspan="4" class="text-center p-6 text-gray-500">No students found in your assigned classes.</td></tr>
                                <?php else: ?>
                                    <?php foreach($students as $student): ?>
                                    <tr>
                                        <td data-label="Name" class="px-6 py-4 text-sm font-medium text-gray-900"><?php echo e($student['full_name']); ?></td>
                                        <td data-label="Class" class="px-6 py-4 text-sm text-gray-500"><?php echo e($student['class_name']); ?></td>
                                        <td data-label="Index #" class="px-6 py-4 text-sm text-gray-500"><?php echo e($student['index_number']); ?></td>
                                        <td data-label="Actions" class="px-6 py-4 whitespace-nowrap text-sm font-medium text-center space-x-4">
                                            <a href="view_student_files.php?id=<?php echo $student['id']; ?>" class="relative inline-flex items-center text-blue-600 hover:text-blue-900">
                                                <span>View Files</span>
                                                <?php if ($student['unread_file_count'] > 0): ?>
                                                    <span class="absolute -top-2 -right-3 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-red-100 transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full"><?php echo $student['unread_file_count']; ?></span>
                                                <?php endif; ?>
                                            </a>
                                            <a href="upload_private_file.php?id=<?php echo $student['id']; ?>" class="text-green-600 hover:text-green-900">Upload File</a>
                                            <a href="edit_student.php?id=<?php echo $student['id']; ?>" class="text-indigo-600 hover:text-indigo-900">Edit</a>
                                            <a href="student_actions.php?action=delete&id=<?php echo $student['id']; ?>" onclick="return confirm('Are you sure you want to delete this student?');" class="text-red-600 hover:text-red-900">Delete</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    </div>
    <footer class="text-center py-6 bg-gray-100 border-t mt-auto">
        <p class="text-xs text-gray-500">Built By Ele InfoComm Technologies- Kenya | <a href="http://web.e-ict.co.ke" target="_blank" class="hover:underline">web.e-ict.co.ke</a> | <a href="mailto:info@e-ict.co.ke" class="hover:underline">info@e-ict.co.ke</a> | +254202000121 | +254 722 215810 | 2025 All right reserved.</p>
    </footer>

    <script>
        const btn = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');

        btn.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
        });
    </script>
</body>
</html>
