<?php
session_start();
include '../admin/includes/database.php';
include '../admin/includes/functions.php';
$conn = new Functions();

if(isset($_SESSION['teacher'])) {

    $username = $_SESSION['teacher'];
    $sql = "SELECT * FROM teachers WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);

    $result = $conn->fetchSingle();
    $teacher_name = $result->name;

    if (!empty($_POST['className'])) {
        $className = $_POST['className'];

        // Get class ID first
        $sql = "SELECT id FROM classes WHERE name = :class_name";
        $conn->query($sql);
        $conn->bind(':class_name', $className);
        $class_id = $conn->fetchColumn();

        if ($class_id) {
            $sql = "SELECT * FROM subjects 
                WHERE class_id = :class_id 
                AND teacher_name =:teacher_name
                ORDER BY subject_name";
            $conn->query($sql);
            $conn->bind(':class_id', $class_id);
            $conn->bind(":teacher_name", $teacher_name);
            if($conn->rowCount() > 0){
                $subjects = $conn->fetchMultiple();

                echo '<option value="">Select Subject</option>';
                foreach ($subjects as $subject) {
                    echo '<option value="' . $subject->subject_name . '">' . $subject->subject_name . '</option>';
                }
            }else{
                echo '<option value="">No subjects found</option>';
            }
        } else {
            echo '<option value="">No subjects found</option>';
        }
    } else {
        echo '<option value="">Select class first</option>';
    }

}