<?php
// DELETE handler
if (isset($_POST['teachers_delete_btn'])) {
    $assignment_id = $_POST['teachers_hidden_id'];
    $stmt = $connection->prepare("DELETE FROM subject_teacher WHERE id = ?");
    $stmt->bind_param("i", $assignment_id);

    if ($stmt->execute()) {
        $_SESSION['msg'] = "Subject Assignment Deleted Successfully";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Error! Could Not Delete Record";
        $_SESSION['type'] = "error";
    }

    $stmt->close();
    header("Location: assign_subject_to_staff");
    exit();
}

// SAVE handler
if (isset($_POST['save_btn'])) {
    $staff_id = (int) $_POST['teacher_id'];
    $subject = trim($_POST['subject']);
    $class = trim($_POST['class']);
    $term = trim($_POST['term']);

    // Allow both Subject and Class Teachers
    $stmt = $connection->prepare("SELECT s.name FROM staff s INNER JOIN role r ON s.role = r.id WHERE s.id = ? AND r.role_name IN ('Subject Teacher', 'Class Teacher')");
    $stmt->bind_param("i", $staff_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $staff_name = $row['name'];

        $check = $connection->prepare("SELECT id FROM subject_teacher WHERE staff_id = ? AND subject = ? AND class = ? AND term = ?");
        $check->bind_param("isss", $staff_id, $subject, $class, $term);
        $check->execute();
        $check_result = $check->get_result();

        if ($check_result->num_rows == 0) {
            $insert = $connection->prepare("INSERT INTO subject_teacher (staff_id, subject, class, term) VALUES (?, ?, ?, ?)");
            $insert->bind_param("isss", $staff_id, $subject, $class, $term);

            if ($insert->execute()) {
                $_SESSION['msg'] = "$staff_name assigned to subject '$subject' for $class - $term successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Error assigning subject.";
                $_SESSION['type'] = "error";
            }
            $insert->close();
        } else {
            $_SESSION['msg'] = "Subject '$subject' already assigned to $staff_name for $class - $term.";
            $_SESSION['type'] = "error";
        }
        $check->close();
    } else {
        $_SESSION['msg'] = "Selected staff is not eligible for subject assignment.";
        $_SESSION['type'] = "error";
    }

    $stmt->close();
    header("Location: assign_subject_to_staff");
    exit();
}
?>

<div class="page-title">
    <div>
        <h1><i class="fa fa-book"></i> Subject Teachers</h1>
        <p>Assign subjects to teachers</p>
    </div>
</div>

<div class="card">
    <form action="" method="POST">
        <div class="panel panel-primary ch">
            <div class="panel-heading">
                <h4 class="text-center">Assign Subjects to Teachers</h4>
            </div>
            <div class="panel-body">
                <div class="row">
                    <!-- Staff Dropdown -->
                    <div class='col-md-4'>
                        <div class="input-group">
                            <span class="input-group-addon">Staff</span>
                            <select class="form-control" name="teacher_id" required>
                                <option value="">-- Select Staff --</option>
                                <?php
                                $query = "SELECT staff.id, staff.name, role.role_name 
                                          FROM staff 
                                          INNER JOIN role ON staff.role = role.id 
                                          WHERE role.role_name IN ('Subject Teacher', 'Class Teacher') 
                                          ORDER BY staff.name ASC";
                                $result = mysqli_query($connection, $query);
                                while ($row = mysqli_fetch_assoc($result)) {
                                    echo "<option value='{$row['id']}'>{$row['name']} ({$row['role_name']})</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <!-- Class Dropdown -->
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Class:</span>
                            <select class='form-control' name='class' id='class-select' required>
								<option selected disabled>Select Class</option>
								<?php
								$query = "SELECT * FROM `classes`";
								$run_query = mysqli_query($connection, $query);
								if (mysqli_num_rows($run_query) > 0) {
									while ($result = mysqli_fetch_assoc($run_query)) {
										$attendance = $result['classes'];
										echo "<option value='{$attendance}'>{$attendance}</option>";
									}
								}
								?>
							</select>
                        </div>
                        <br />
                    </div>

                    <!-- Subject Dropdown -->
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Subject:</span>
                            <select class='form-control' name='subject' id='subject-select' required>
								<option selected>Select a Class First</option>
							</select>
                        </div>
                        <br />
                    </div>

                    <!-- Term -->
                    <div class='col-md-4'>
                        <div class="input-group">
                            <span class="input-group-addon">Term</span>
                            <select class="form-control" name="term" required>
                                <option value="">-- Select Term --</option>
                                <option>First Term</option>
                                <option>Second Term</option>
                                <option>Third Term</option>
                            </select>
                        </div>
                    </div>

                    <!-- Save Button -->
                    <div class='col-md-2'>
                        <button type="submit" name="save_btn" class="btn btn-primary btn-md">
                            <span class="glyphicon glyphicon-book"></span> SAVE
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- Assigned Subjects Table -->
    <?php
    $query = "SELECT st.id, s.name, st.subject, st.class, st.term 
              FROM subject_teacher st 
              INNER JOIN staff s ON st.staff_id = s.id 
              ORDER BY st.class ASC, st.subject ASC";
    $result = mysqli_query($connection, $query);

    if (mysqli_num_rows($result) > 0): ?>
        <div class='table-responsive'>
            <table class='table table-striped'>
                <thead>
                    <tr>
                        <th>S/N</th>
                        <th>NAME</th>
                        <th>SUBJECT</th>
                        <th>CLASS</th>
                        <th>TERM</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i = 0;
                    while ($row = mysqli_fetch_assoc($result)):
                        $i++; ?>
                        <tr>
                            <td><?= $i ?></td>
                            <td><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= htmlspecialchars($row['subject']) ?></td>
                            <td><?= htmlspecialchars($row['class']) ?></td>
                            <td><?= htmlspecialchars($row['term']) ?></td>
                            <td>
                                <form method='POST' action=''>
                                    <input type='hidden' name='teachers_hidden_id' value='<?= $row['id'] ?>' />
                                    <button type="submit" name="teachers_delete_btn" class="btn btn-xs btn-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
