<?php
include 'includes/conn.php';
include 'includes/functions.php';
requireRole('admin');

$selected_teacher_id = $_POST['teacher_id'] ?? '';
$success_message = $error_message = "";

// Handle form submission
if (isset($_POST['assign_subjects'])) {
    $subject_ids = $_POST['subject_ids'] ?? [];

    if ($selected_teacher_id && !empty($subject_ids)) {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("DELETE FROM teacher_subjects WHERE teacher_id = ?")->execute([$selected_teacher_id]);
            $insert_stmt = $pdo->prepare("INSERT INTO teacher_subjects (teacher_id, classroom_id, subject_id) VALUES (?, ?, ?)");
            foreach ($subject_ids as $combo) {
                list($classroom_id, $subject_id) = explode('-', $combo);
                $insert_stmt->execute([$selected_teacher_id, $classroom_id, $subject_id]);
            }
            $pdo->commit();
            $success_message = "✅ Subjects successfully assigned to this teacher!";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "❌ Error assigning subjects: " . $e->getMessage();
        }
    } else {
        $error_message = "⚠️ Please select a teacher and at least one subject.";
    }
}

// Fetch teachers
$teachers = $pdo->query("SELECT id, first_name, last_name FROM users WHERE role = 'teacher' ORDER BY first_name ASC")->fetchAll();

// Fetch classrooms and subjects
$classrooms = $pdo->query("SELECT * FROM classrooms ORDER BY name ASC")->fetchAll();
$class_subjects = [];
foreach ($classrooms as $class) {
    $stmt = $pdo->prepare("
        SELECT s.id AS subject_id, s.name AS subject_name
        FROM class_subjects cs
        JOIN subjects s ON cs.subject_id = s.id
        WHERE cs.classroom_id = ?
        ORDER BY s.name ASC
    ");
    $stmt->execute([$class['id']]);
    $class_subjects[$class['id']] = $stmt->fetchAll();
}

// Fetch current assignments
$current_subjects = [];
if ($selected_teacher_id) {
    $stmt = $pdo->prepare("SELECT CONCAT(classroom_id,'-',subject_id) AS combo FROM teacher_subjects WHERE teacher_id = ?");
    $stmt->execute([$selected_teacher_id]);
    $current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Selected teacher's name
$selected_teacher_name = '';
if ($selected_teacher_id) {
    $stmt = $pdo->prepare("SELECT first_name,last_name FROM users WHERE id = ?");
    $stmt->execute([$selected_teacher_id]);
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $selected_teacher_name = $row['first_name'].' '.$row['last_name'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Assign Subjects to Teacher</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="major.css" rel="stylesheet">
<script src="https://kit.fontawesome.com/a2e0e6ad04.js" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
    <div class="container">
        <a class="navbar-brand" href="admin.php">
            <i class="fas fa-chalkboard-teacher"></i> Admin Portal
        </a>
        <div class="navbar-nav ms-auto">
            <span class="navbar-text me-3">
                Welcome, <?= htmlspecialchars($_SESSION['first_name']) ?>
            </span>
            <button id="themeToggle" class="toggle-btn">
                <i class="fas fa-moon"></i> Dark Mode
            </button>
            <script src="dark.js"></script>
            <a class="nav-link" href="admin.php">Dashboard</a>
            <a class="nav-link" href="logout.php">Logout</a>
        </div>
    </div>
</nav>
<div class="container py-5">
    <div class="card shadow-lg">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"><i class="fas fa-book me-2"></i>Assign Subjects to Teacher</h4>
        </div>
        <div class="card-body">
            <?php if ($success_message): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success_message) ?></div>
            <?php elseif ($error_message): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
            <?php endif; ?>

            <!-- Teacher Search -->
            <form method="POST" class="mb-4">
                <label for="teacher_search" class="form-label fw-bold">Select Teacher</label>
                <div class="position-relative">
                    <input type="text" id="teacher_search" class="form-control" placeholder="Type to search..."
                           value="<?= htmlspecialchars($selected_teacher_name) ?>" autocomplete="off">
                    <ul id="teacher_dropdown" class="list-group position-absolute w-100"
                        style="z-index:1000; display:none; max-height:200px; overflow-y:auto;"></ul>
                    <input type="hidden" name="teacher_id" id="teacher_id" value="<?= htmlspecialchars($selected_teacher_id) ?>">
                </div>
            </form>

            <!-- Subject Assignment -->
            <?php if ($selected_teacher_id): ?>
            <form method="POST">
                <input type="hidden" name="teacher_id" value="<?= htmlspecialchars($selected_teacher_id) ?>">
                <?php foreach ($classrooms as $class): ?>
                    <?php if (!empty($class_subjects[$class['id']])): ?>
                        <div class="mb-4">
                            <h5 class="fw-bold text-success"><i class="fas fa-chalkboard me-2"></i><?= htmlspecialchars($class['name']) ?></h5>
                            <div class="row">
                                <?php foreach ($class_subjects[$class['id']] as $subject):
                                    $combo = $class['id'].'-'.$subject['subject_id'];
                                    $checked = in_array($combo,$current_subjects) ? 'checked' : '';
                                ?>
                                    <div class="col-md-4 mb-3">
                                        <div class="form-check border rounded p-2 shadow-sm">
                                            <input class="form-check-input" type="checkbox" name="subject_ids[]" 
                                                   value="<?= $combo ?>" id="sub<?= $combo ?>" <?= $checked ?>>
                                            <label class="form-check-label fw-semibold" for="sub<?= $combo ?>">
                                                <?= htmlspecialchars($subject['subject_name']) ?> 
                                                <small class="text-muted">(<?= htmlspecialchars($class['name']) ?>)</small>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <hr>
                    <?php endif; ?>
                <?php endforeach; ?>
                <div class="text-end mt-4">
                    <button type="submit" name="assign_subjects" class="btn btn-success px-4">
                        <i class="fas fa-save me-2"></i>Save Changes
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
const teachers = [
    <?php foreach($teachers as $t): ?>
    {id: <?= $t['id'] ?>, name: "<?= addslashes($t['first_name'].' '.$t['last_name']) ?>"},
    <?php endforeach; ?>
];

const searchInput = document.getElementById('teacher_search');
const dropdown = document.getElementById('teacher_dropdown');
const hiddenInput = document.getElementById('teacher_id');

// Filter and display dropdown
searchInput.addEventListener('input', function(){
    const query = this.value.toLowerCase();
    dropdown.innerHTML = '';
    if(query===''){ dropdown.style.display='none'; hiddenInput.value=''; return; }
    const filtered = teachers.filter(t=>t.name.toLowerCase().includes(query));
    if(filtered.length===0){ dropdown.style.display='none'; hiddenInput.value=''; return; }

    filtered.forEach(t=>{
        const li = document.createElement('li');
        li.className='list-group-item list-group-item-action';
        li.textContent = t.name;
        li.style.cursor='pointer';
        li.addEventListener('click', function(){
            searchInput.value = t.name;
            hiddenInput.value = t.id;
            dropdown.style.display='none';
            searchInput.form.submit(); // auto-submit to reload assigned subjects
        });
        dropdown.appendChild(li);
    });
    dropdown.style.display='block';
});

// Close dropdown on outside click
document.addEventListener('click', function(e){
    if(!searchInput.contains(e.target) && !dropdown.contains(e.target)){
        dropdown.style.display='none';
    }
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
