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

$examId = $_POST['examId'];
$classId = $_POST['classId'];
$subjectId = $_POST['subjectId'];

$response = '';

 $query = "
        SELECT s.student_id, s.name, s.symbol_no, 
               COALESCE(m.marks, 'N/A') AS marks
        FROM students s
        INNER JOIN studentsub st ON s.student_id = st.student_id AND s.class_id = st.class_id
        LEFT JOIN marks m ON s.student_id = m.student_id AND m.exam_type = ? AND m.subject_id = ?
        WHERE s.class_id = ? 
        AND (
            st.sub1 = ? OR st.sub2 = ? OR st.sub3 = ? OR st.sub4 = ? OR st.sub5 = ? OR st.sub6 = ? OR st.sub7 = ?
        ) ORDER by s.symbol_no
        ";

$result = $conn->query($query);

if ($result->num_rows > 0) {
    $response .= '<table class="table table-bordered table-striped">';
    $response .= '<thead><tr><th>Student ID</th><th>Name</th><th>Marks</th></tr></thead><tbody>';
    while ($row = $result->fetch_assoc()) {
        $studentId = htmlspecialchars($row['student_id']);
        $name = htmlspecialchars($row['name']);
        $marks = htmlspecialchars($row['marks'] ?? '');

        $response .= "<tr>
                        <td>{$studentId}</td>
                        <td>{$name}</td>
                        <td>
                            <input type='number' min='0' max='100' class='form-control' id='mark_{$studentId}' value='{$marks}'>
                        </td>
                      </tr>";
    }
    $response .= '</tbody></table>';
} else {
    $response .= "<p>No students found for selected class and subject.</p>";
}

echo $response;
?>
