<?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);

    // Get examId, classId, and subjectId from POST request
    $examId = isset($_POST['examId']) ? $_POST['examId'] : '';
    $classId = isset($_POST['classId']) ? $_POST['classId'] : '';
    $subjectId = isset($_POST['subjectId']) ? $_POST['subjectId'] : '';

    // Check if values are correctly set
    if (empty($examId) || empty($classId) || empty($subjectId)) {
        echo "<p>Error: Missing required parameters (examId, classId, subjectId).</p>";
        exit;
    }

    // Fetch subject details from the subjects table
    $subjectCodeQuery = "SELECT subject_code, subject_name, theory_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['theory_full_marks'];
        $subjectname = $subjectCodeRow['subject_name'];

        echo "Edit marks of subject: $subjectname [Subject code: $subjectCode]<br>";
        echo "Full Marks: $fullmarksint <br>";
    } else {
        echo "<p>Error: Subject not found for the provided subjectId.</p>";
        exit;
    }

    // Fetch students assigned to the selected subject for the specified class and exam
    $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
        ";

    // Debugging: Print query to ensure it's being constructed correctly
    // echo "Query: $query <br>";

    $stmt = $conn->prepare($query);
    // Bind the parameters
    $stmt->bind_param("iiiiiiiiii", $examId, $subjectId, $classId, 
        $subjectCode, $subjectCode, $subjectCode, $subjectCode, $subjectCode, $subjectCode, $subjectCode);
    $stmt->execute();
    $result = $stmt->get_result();

    // Check if any students were found
    if ($result->num_rows > 0) {
        // Output JavaScript to handle validation based on full marks
        echo "<script>
            const fullMarks = $fullmarksint;
            function validateMarks(input, studentName) {
                const enteredMarks = parseFloat(input.value);
                if (enteredMarks > fullMarks) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Entered marks for ' + studentName + ' exceed the full marks (' + fullMarks + '). Please enter a valid mark.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    input.value = ''; // Clear the input field if it exceeds full marks
                    input.focus(); // Focus back on the input field
                }
            }
        </script>";

        // Display the student list and mark entry fields with JavaScript validation
        while ($row = $result->fetch_assoc()) {
            echo "<div class='form-group d-flex align-items-center'>
                    <label class='mb-0 mr-7'>
                        <b>{$row['name']}: <span style='color:red'>[Symbol No: {$row['symbol_no']}]</span></b>
                    </label>
                    <input type='number' name='marks[{$row['student_id']}]' 
                           id='marks_{$row['student_id']}' 
                           class='form-control' style='width: auto;' 
                           value='{$row['marks']}' 
                           oninput='validateMarks(this, \"{$row['name']}\")' />
                  </div>";
        }
    } else {
        echo "<p>No students assigned to this subject in the selected class.</p>";
    }

} else {
    echo "<p>Invalid request method.</p>";
}
?>
