<?php
include './login/connect.php';

$class_id = $_POST['class_id'];
$month = $_POST['month'];
$subject_id = $_POST['subject_id'];

// SQL Query to fetch students and their scores
$query = "
    SELECT students.id AS student_id, students.name, results.score_given
    FROM students
    LEFT JOIN results 
    ON students.id = results.student_id 
    AND results.month = '$month' 
    AND results.subject_id = $subject_id
    WHERE students.class_id = $class_id
";
$result = $conn->query($query);

if (!$result) {
    die("Error: " . $conn->error);
}

// Generate the form with fetched data
echo '<form id="score-form">';
echo '<table>';
echo '<thead><tr><th>Student Name</th><th>Score</th></tr></thead><tbody>';

while ($row = $result->fetch_assoc()) {
    echo "<tr>
        <td>{$row['name']}</td>
        <td>
            <input type='hidden' name='student_ids[]' value='{$row['student_id']}'>
            <input type='number' name='scores[{$row['student_id']}]' value='{$row['score_given']}' min='0' max='100' required>
        </td>
    </tr>";
}

echo '</tbody></table>';
echo '<button type="submit">Save Scores</button>';
echo '</form>';
?>
