<?php
// header.php already starts session
require_once(__DIR__ . "/../header.php");
require_once(__DIR__ . "/../../public/connection.php");



// Ensure teacher is logged in
if (!isset($_SESSION['staff'])) {
    header("Location: ../../login.php");
    exit;
}

$teacher_id = $_SESSION['staff'];

// Fetch subjects assigned to this teacher
$sub_q = $connection->prepare("SELECT DISTINCT subject, class FROM subject_teacher WHERE staff_id=? ORDER BY subject");
$sub_q->bind_param("i", $teacher_id);
$sub_q->execute();
$res = $sub_q->get_result();
$subjects_classes = [];
while($row = $res->fetch_assoc()){
    $subjects_classes[$row['subject']][] = $row['class'];
}

// Handle form submission
$success = '';
if(isset($_POST['issue_btn'])){
    $subject = $_POST['subject'];
    $class = $_POST['class'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $due_date = $_POST['due_date'];

    $file_path = null;
    if(isset($_FILES['file']) && $_FILES['file']['error']===0){
        $filename = time().'_'.basename($_FILES['file']['name']);
        $target = $_SERVER['DOCUMENT_ROOT'].'/uploads/assignments/'.$filename;
        if(move_uploaded_file($_FILES['file']['tmp_name'],$target)){
            $file_path = '/uploads/assignments/'.$filename;
        }
    }

    $stmt = $connection->prepare("INSERT INTO assignments (teacher_id, class, subject, title, description, due_date, file_path) VALUES (?,?,?,?,?,?,?)");
    $stmt->bind_param("issssss",$teacher_id, $class, $subject, $title, $description, $due_date, $file_path);
    if($stmt->execute()){
        $success = "Assignment issued successfully!";
    }
}
?>
<link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../../assets/css/style.css">
<link rel="stylesheet" href="../../assets/css/custom.css">
<script src="../../assets/js/jquery.min.js"></script>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>

<div class="container mt-4">
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h4>Issue Assignment</h4>
        </div>
        <div class="card-body">
            <?php if($success): ?>
                <div class="alert alert-success"><?= $success ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label>Subject</label>
                        <select name="subject" id="subject" class="form-control" required>
                            <option value="">Select Subject</option>
                            <?php foreach($subjects_classes as $sub => $classes): ?>
                                <option value="<?= $sub ?>"><?= $sub ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label>Class</label>
                        <select name="class" id="class" class="form-control" required>
                            <option value="">Select Class</option>
                        </select>
                    </div>
                </div>

                <div class="mb-3">
                    <label>Title</label>
                    <input type="text" name="title" class="form-control" required>
                </div>

                <div class="mb-3">
                    <label>Description</label>
                    <textarea name="description" class="form-control" rows="4"></textarea>
                </div>

                <div class="mb-3">
                    <label>Due Date</label>
                    <input type="datetime-local" name="due_date" class="form-control" required>
                </div>

                <div class="mb-3">
                    <label>Attachment (optional)</label>
                    <input type="file" name="file" class="form-control">
                </div>

                <button type="submit" name="issue_btn" class="btn btn-success">Issue Assignment</button>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    // Object mapping subjects to classes
    const subjectClasses = <?= json_encode($subjects_classes) ?>;

    $('#subject').on('change', function(){
        const subject = $(this).val();
        const classDropdown = $('#class');
        classDropdown.empty().append('<option value="">Select Class</option>');
        if(subject && subjectClasses[subject]){
            subjectClasses[subject].forEach(cls => {
                classDropdown.append('<option value="'+cls+'">'+cls+'</option>');
            });
        }
    });
});
</script>
