<?php
/**
 * ===================================================================================
 * Assign Subjects to Teachers Page (Mobile Responsive)
 * ===================================================================================
 *
 * File: assign_subjects.php
 * Location: /homework_portal/admin/assign_subjects.php
 *
 * Purpose:
 * 1. Allows an Admin to assign a teacher to a specific subject in a specific class.
 * 2. Displays current assignments for a selected teacher.
 * 3. Handles adding and removing these assignments with a responsive UI.
 */

require_once '../config.php';
require_once 'admin_helpers.php'; // Correctly include the helper file

// Security Check for this specific page
check_permission('assign_subjects');

$errors = [];
$success_message = '';
$selected_teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;

// --- 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']);
}


// --- Handle Form Submission to ADD an assignment ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_subject'])) {
    $teacher_id_post = (int)$_POST['teacher_id'];
    $class_id = (int)$_POST['class_id'];
    $subject_id = (int)$_POST['subject_id'];

    if (empty($teacher_id_post) || empty($class_id) || empty($subject_id)) {
        $_SESSION['error_message'] = "Teacher, Class, and Subject must all be selected.";
    } else {
        // Check if this assignment already exists
        $check_stmt = $pdo->prepare("SELECT * FROM teacher_subject_class WHERE teacher_id = ? AND class_id = ? AND subject_id = ?");
        $check_stmt->execute([$teacher_id_post, $class_id, $subject_id]);
        if ($check_stmt->fetch()) {
            $_SESSION['error_message'] = "This teacher is already assigned to this subject in this class.";
        } else {
            try {
                $sql = "INSERT INTO teacher_subject_class (teacher_id, class_id, subject_id) VALUES (?, ?, ?)";
                $pdo->prepare($sql)->execute([$teacher_id_post, $class_id, $subject_id]);
                $_SESSION['success_message'] = "Assignment created successfully!";
            } catch (PDOException $e) {
                $_SESSION['error_message'] = "Database error: Could not create assignment.";
            }
        }
    }
    // Redirect to the same teacher's view
    header("Location: assign_subjects.php?teacher_id=" . $teacher_id_post);
    exit();
}

// --- Handle DELETE action ---
if (isset($_GET['action']) && $_GET['action'] === 'unassign') {
    $teacher_id_get = (int)$_GET['teacher_id'];
    $class_id_get = (int)$_GET['class_id'];
    $subject_id_get = (int)$_GET['subject_id'];
    
    try {
        $sql = "DELETE FROM teacher_subject_class WHERE teacher_id = ? AND class_id = ? AND subject_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$teacher_id_get, $class_id_get, $subject_id_get]);
        $_SESSION['success_message'] = "Assignment removed successfully!";
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Database error: Could not remove assignment.";
    }
    // Redirect back to the same teacher's view
    header("Location: assign_subjects.php?teacher_id=" . $teacher_id_get);
    exit();
}


// --- Fetch data for display ---
try {
    $teachers = $pdo->query("SELECT id, full_name FROM teachers ORDER BY full_name ASC")->fetchAll();
    $classes = $pdo->query("SELECT id, class_name FROM classes ORDER BY class_name ASC")->fetchAll();
    $subjects = $pdo->query("SELECT id, subject_name FROM subjects ORDER BY subject_name ASC")->fetchAll();
    $unread_count = $pdo->query("SELECT COUNT(id) FROM teacher_messages WHERE sender_type = 'teacher' AND is_read = 0")->fetchColumn();

    $assignments = [];
    if ($selected_teacher_id > 0) {
        $assignment_sql = "
            SELECT t.full_name, c.class_name, s.subject_name, tsc.teacher_id, tsc.class_id, tsc.subject_id
            FROM teacher_subject_class tsc
            JOIN teachers t ON tsc.teacher_id = t.id
            JOIN classes c ON tsc.class_id = c.id
            JOIN subjects s ON tsc.subject_id = s.id
            WHERE tsc.teacher_id = ?
            ORDER BY c.class_name, s.subject_name
        ";
        $stmt = $pdo->prepare($assignment_sql);
        $stmt->execute([$selected_teacher_id]);
        $assignments = $stmt->fetchAll();
    }
} catch (PDOException $e) {
    $errors[] = "Could not fetch data from the database.";
    $teachers = $classes = $subjects = $assignments = [];
    $unread_count = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Subjects - Admin 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; }
        .sidebar-link:hover, .sidebar-link.active { background-color: #e0f2fe; color: #0284c7; }
        .notification-badge { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; 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;
                justify-content: center; /* Center action buttons */
                padding-top: 1rem;
            }
            .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_count > 0): ?><span class="notification-badge"><?php echo $unread_count; ?></span><?php endif; ?>
                </a>
                <?php if (has_permission('manage_admins')): ?><a href="manage_admins.php" class="sidebar-link"><span>Manage Admins</span></a><?php endif; ?>
                <?php if (has_permission('manage_teachers')): ?><a href="manage_teachers.php" class="sidebar-link"><span>Manage Teachers</span></a><?php endif; ?>
                <?php if (has_permission('manage_classes')): ?><a href="manage_classes.php" class="sidebar-link"><span>Manage Classes</span></a><?php endif; ?>
                <?php if (has_permission('manage_subjects')): ?><a href="manage_subjects.php" class="sidebar-link"><span>Manage Subjects</span></a><?php endif; ?>
                <?php if (has_permission('assign_subjects')): ?><a href="assign_subjects.php" class="sidebar-link active"><span>Assign Subjects</span></a><?php endif; ?>
                <?php if (has_permission('send_message')): ?><a href="send_message.php" class="sidebar-link"><span>Send Message</span></a><?php endif; ?>
            </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 e($_SESSION['admin_username'] ?? 'Admin'); ?>!</span><a href="account_settings.php" class="p-2 text-gray-500 hover:text-blue-600" title="Account Settings"><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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg></a><a href="logout.php" class="ml-2 py-2 px-4 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-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">Assign Subjects to Teachers</h2>

                <?php if (!empty($errors)): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach ($errors as $error) echo "<li>" . $error . "</li>"; ?></ul></div><?php endif; ?>
                <?php if ($success_message): ?><div class="p-4 my-4 text-sm text-green-800 bg-green-100 rounded-lg"><?php echo $success_message; ?></div><?php endif; ?>

                <!-- Teacher Selection Form -->
                <div class="mt-6 bg-white p-6 rounded-lg shadow">
                     <form action="assign_subjects.php" method="GET" class="flex flex-col md:flex-row items-start md:items-center space-y-2 md:space-y-0 md:space-x-4">
                        <label for="teacher_id_select" class="block text-lg font-medium text-gray-700 flex-shrink-0">Select a Teacher:</label>
                        <select name="teacher_id" id="teacher_id_select" onchange="this.form.submit()" class="block w-full md:w-1/2 p-2 border border-gray-300 rounded-md shadow-sm">
                            <option value="">-- View Assignments For... --</option>
                            <?php foreach($teachers as $teacher): ?>
                                <option value="<?php echo e($teacher['id']); ?>" <?php if($selected_teacher_id == $teacher['id']) echo 'selected'; ?>><?php echo e($teacher['full_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                     </form>
                </div>

                <?php if($selected_teacher_id > 0): ?>
                <!-- Assignment Form and List (shown only when a teacher is selected) -->
                <div class="mt-8 grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <!-- Add New Assignment Form -->
                    <div class="lg:col-span-1 bg-white p-6 rounded-lg shadow">
                        <h3 class="text-xl font-semibold text-gray-800 mb-4">Assign New Subject</h3>
                        <form action="assign_subjects.php?teacher_id=<?php echo $selected_teacher_id; ?>" method="POST" class="space-y-4">
                            <input type="hidden" name="teacher_id" value="<?php echo $selected_teacher_id; ?>">
                            <div>
                                <label for="class_id" class="block text-sm font-medium text-gray-700">To 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($classes as $class): ?><option value="<?php echo e($class['id']); ?>"><?php echo e($class['class_name']); ?></option><?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label for="subject_id" class="block text-sm font-medium text-gray-700">The Subject:</label>
                                <select name="subject_id" id="subject_id" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                                    <option value="">Select a Subject</option>
                                    <?php foreach($subjects as $subject): ?><option value="<?php echo e($subject['id']); ?>"><?php echo e($subject['subject_name']); ?></option><?php endforeach; ?>
                                </select>
                            </div>
                            <div class="text-right">
                                <button type="submit" name="assign_subject" class="w-full md:w-auto px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow hover:bg-blue-700">Assign</button>
                            </div>
                        </form>
                    </div>

                    <!-- Current Assignments List -->
                    <div class="lg:col-span-2 bg-white shadow-lg rounded-lg overflow-hidden">
                        <div class="p-4 border-b"><h3 class="text-xl font-semibold text-gray-800">Current Assignments</h3></div>
                        <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">Class</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Subject</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($assignments)): ?>
                                        <tr><td colspan="3" class="text-center p-6 text-gray-500">This teacher has no assignments yet.</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($assignments as $assignment): ?>
                                        <tr>
                                            <td data-label="Class" class="px-6 py-4 text-sm font-medium text-gray-900"><?php echo e($assignment['class_name']); ?></td>
                                            <td data-label="Subject" class="px-6 py-4 text-sm text-gray-500"><?php echo e($assignment['subject_name']); ?></td>
                                            <td data-label="Actions" class="px-6 py-4 text-sm font-medium text-center">
                                                <a href="assign_subjects.php?action=unassign&teacher_id=<?php echo e($assignment['teacher_id']); ?>&class_id=<?php echo e($assignment['class_id']); ?>&subject_id=<?php echo e($assignment['subject_id']); ?>" onclick="return confirm('Are you sure you want to unassign this subject?');" class="text-red-600 hover:text-red-900">Unassign</a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    <footer class="text-center py-6 bg-gray-100 border-t mt-auto">
        <p class="text-sm 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>
