<?php
include("includes/db.php");

if (isset($_POST['exam_type'])) {
    $examTypeId = $conn->real_escape_string($_POST['exam_type']);

    // Query to fetch subjects for the selected exam type
    $subjectQuery = "
        SELECT DISTINCT classes.class_name, classes.section, subjects.subject_code, subjects.subject_name
        FROM classes
        INNER JOIN marks ON classes.class_id = marks.class_id
        INNER JOIN subjects ON marks.subject_id = subjects.id
        WHERE marks.exam_type = '$examTypeId' AND classes.status = 'on'
        ORDER BY classes.class_id, subjects.subject_code 
    ";
    $subjectResult = $conn->query($subjectQuery);

    if ($subjectResult->num_rows > 0) {
        $currentClass = "";
        $currentSection = "";
        $output = '';

        while ($row = $subjectResult->fetch_assoc()) {
            $className = htmlspecialchars($row['class_name']);
            $section = htmlspecialchars($row['section']);
            $subjectCode = htmlspecialchars($row['subject_code']);
            $subjectName = htmlspecialchars($row['subject_name']);

            if ($currentClass != $className || $currentSection != $section) {
                // Close previous table if not the first
                if ($currentClass != "" && $currentSection != "") {
                    $output .= "</tbody></table>";
                }

                // New class-section encountered, display header and start new table
                $output .= "<h2>$className - $section</h2>";
                $output .= "
                    <table class='table table-striped table-bordered table-hover'>
                        <thead class='thead-dark'>
                            <tr>
                                <th>Subject Code</th>
                                <th>Subject Name</th>
                            </tr>
                        </thead>
                        <tbody>
                ";
                $currentClass = $className;
                $currentSection = $section;
            }

            // Display subjects for the current class-section
            $output .= "
                <tr>
                    <td>$subjectCode</td>
                    <td>$subjectName</td>
                </tr>
            ";
        }

        // Close the last table
        $output .= "</tbody></table>";

        echo $output;
    } else {
        echo "<p>No data found for this exam type.</p>";
    }
} else {
    echo "<p>Invalid request.</p>";
}
?>
