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

$selected_student_id = $_POST['student_id'] ?? '';
$success_message = $error_message = "";

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

    if ($selected_student_id && !empty($subject_ids)) {
        $pdo->beginTransaction();
        try {
            $pdo->prepare("DELETE FROM student_subjects WHERE student_id = ?")->execute([$selected_student_id]);
            $insert_stmt = $pdo->prepare("INSERT INTO student_subjects (student_id, subject_id) VALUES (?, ?)");
            foreach ($subject_ids as $subject_id) {
                $insert_stmt->execute([$selected_student_id, $subject_id]);
            }
            $pdo->commit();
            $success_message = "✅ Subjects successfully assigned to student!";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "❌ Error: " . $e->getMessage();
        }
    } else {
        $error_message = "⚠️ Please select a student and at least one subject.";
    }
}

// Fetch students and subjects
$students = $pdo->query("SELECT id, first_name, last_name, current_class FROM users WHERE role = 'student' ORDER BY first_name ASC")->fetchAll();
$subjects = $pdo->query("SELECT * FROM subjects ORDER BY name ASC")->fetchAll();

// Fetch current subjects if student selected
$current_subjects = [];
if ($selected_student_id) {
    $stmt = $pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id = ?");
    $stmt->execute([$selected_student_id]);
    $current_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Get selected student's full name for display
$selected_student_name = '';
if ($selected_student_id) {
    $stmt = $pdo->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
    $stmt->execute([$selected_student_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) $selected_student_name = $row['first_name'].' '.$row['last_name'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign Subjects to Student</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">
</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, <?php echo $_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-success text-white">
            <h4 class="mb-0">Assign Subjects to Student</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; ?>

            <!-- Student Search -->
            <form method="POST" class="mb-4">
                <div class="mb-3">
                    <label for="student_search" class="form-label fw-bold">Select Student</label>
                    <div class="position-relative">
                        <input type="text" id="student_search" class="form-control" placeholder="Type to search..."
                               value="<?= htmlspecialchars($selected_student_name) ?>" autocomplete="off">
                        <ul id="student_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="student_id" id="student_id" value="<?= htmlspecialchars($selected_student_id) ?>">
                    </div>
                </div>
            </form>

            <!-- Subject Assignment -->
            <?php if ($selected_student_id): ?>
            <form method="POST">
                <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id) ?>">
                <div class="row">
                    <?php foreach ($subjects as $subject): ?>
                        <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="<?= $subject['id'] ?>"
                                       id="s<?= $subject['id'] ?>"
                                       <?= in_array($subject['id'], $current_subjects) ? 'checked' : '' ?>>
                                <label class="form-check-label fw-semibold" for="s<?= $subject['id'] ?>">
                                    <?= htmlspecialchars($subject['name']) ?>
                                </label>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="text-end mt-4">
                    <button type="submit" name="assign_subjects" class="btn btn-primary px-4">
                        <i class="fas fa-save me-2"></i>Save Assignments
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

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

const searchInput = document.getElementById('student_search');
const dropdown = document.getElementById('student_dropdown');
const hiddenInput = document.getElementById('student_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 = students.filter(s => s.name.toLowerCase().includes(query));
    if(filtered.length === 0){
        dropdown.style.display = 'none';
        hiddenInput.value = '';
        return;
    }

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

    dropdown.style.display = 'block';
});

// Close dropdown if click outside
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>
