<?php
// Include the database configuration file
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Debugging statements
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    $classId = $conn->real_escape_string($_POST["classId"]);
    $subjectId = $conn->real_escape_string($_POST["subjectId"]);

    // Debugging statements
    // Fetch subject code based on subjectId from the subjects table
    $subjectCodeQuery = "SELECT subject_code, internal_full_marks FROM subjects WHERE id = '$subjectId'";
    $subjectCodeResult = $conn->query($subjectCodeQuery);

    if ($subjectCodeResult->num_rows > 0) {
        $subjectCodeRow = $subjectCodeResult->fetch_assoc();
        $subjectCode = $subjectCodeRow['subject_code'];
        $fullmarksint = $subjectCodeRow['internal_full_marks'];

     echo "Subject code: $subjectCode <br>";
        echo "Full Marks: $fullmarksint <br>";
        // Fetch students assigned the selected subject based on class
        $query = "SELECT s.student_id, s.symbol_no, s.regd_id, s.name, im.internal_marks
                  FROM students s
                  LEFT JOIN int_marks im ON s.student_id = im.student_id
                  WHERE s.class_id = '$classId'
                    AND im.subject_id = '$subjectId'";

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

        // Generate marks entry fields for each student
        $output = '';
        while ($row = $result->fetch_assoc()) {
            $studentId = $row['student_id'];
            $internalMarks = $row['internal_marks'] ?? ''; // Handle NULL values

            $output .= '<div class="form-group ">';
            // Output student details
            $output .= '<b><span for="marks_' . $studentId . '"> ' . $row['name'] .'<span style="color:red">' ." [Symbol No ".$row['symbol_no']."]".'</span>'.':</span></b> <input type="number" id="marks_' . $studentId . '" name="marks[' . $studentId . ']" class="form-control"  placeholder="Internal Marks" value="' . $internalMarks . '" required>';
            // Include additional student details as needed
            $output .= '</div>';
        }

        // Return the marks entry fields
        echo $output;
    } else {
        echo "Subject code not found for Subject ID: $subjectId";
    }

    // Close the database connection
    $conn->close();
}
?>
