<?php
// admin/allocation/subject_teacher.php
require_once '../../includes/auth_check.php';
checkAccess('admin');
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign'])) {
    $teacher_id = $_POST['teacher_id'];
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];

    $stmt = $pdo->prepare("INSERT INTO subject_teacher (teacher_id, subject_id, class_id) VALUES (?, ?, ?)");
    $stmt->execute([$teacher_id, $subject_id, $class_id]);
    $msg = "Teacher assigned successfully!";
}

// Fetch data for dropdowns
$teachers = $pdo->query("SELECT id, fullname FROM users WHERE role = 'teacher'")->fetchAll();
$subjects = $pdo->query("SELECT * FROM subjects")->fetchAll();
$classes = $pdo->query("SELECT * FROM classes")->fetchAll();
?>

<!DOCTYPE html>
<html>
<head><title>Assign Subjects to Teachers</title></head>
<body>
    <?php include '../../includes/header.php'; ?>
    <h2>Subject-Teacher Allocation</h2>
    
    <form method="POST">
        <select name="teacher_id" required>
            <option value="">Select Teacher</option>
            <?php foreach($teachers as $t): ?>
                <option value="<?php echo $t['id']; ?>"><?php echo $t['fullname']; ?></option>
            <?php endforeach; ?>
        </select>

        <select name="subject_id" required>
            <option value="">Select Subject</option>
            <?php foreach($subjects as $s): ?>
                <option value="<?php echo $s['id']; ?>"><?php echo $s['subject_name']; ?></option>
            <?php endforeach; ?>
        </select>

        <select name="class_id" required>
            <option value="">Select Class</option>
            <?php foreach($classes as $c): ?>
                <option value="<?php echo $c['id']; ?>"><?php echo $c['class_name']; ?></option>
            <?php endforeach; ?>
        </select>

        <button type="submit" name="assign">Assign Teacher</button>
    </form>
</body>
</html>