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

// Check if the form is submitted
if (isset($_POST['submit'])) {
    $examId = $conn->real_escape_string($_POST['exam_id1']);
    $classId = $conn->real_escape_string($_POST['class_id']);
    $studentId = $conn->real_escape_string($_POST['student_id']);
    $marksArray = $_POST['marks'];

    // Track success and failure
    $success = true;

    // Iterate over each subject and process marks
    foreach ($marksArray as $subjectId => $marks) {
        // Check if marks already exist for the student, class, subject, and exam
        $checkQuery = "SELECT id FROM marks WHERE student_id = ? AND class_id = ? AND subject_id = ? AND exam_type = ?";
        $stmt = $conn->prepare($checkQuery);
        $stmt->bind_param("iiii", $studentId, $classId, $subjectId, $examId);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // If marks exist, update them
            $updateQuery = "UPDATE marks SET marks = ? WHERE student_id = ? AND class_id = ? AND subject_id = ? AND exam_type = ?";
            $updateStmt = $conn->prepare($updateQuery);
            $updateStmt->bind_param("diiii", $marks, $studentId, $classId, $subjectId, $examId);
            if (!$updateStmt->execute()) {
                $success = false;
            }
            $updateStmt->close();
        } else {
            // If marks do not exist, insert new records
            $insertQuery = "INSERT INTO marks (student_id, class_id, subject_id, exam_type, marks) VALUES (?, ?, ?, ?, ?)";
            $insertStmt = $conn->prepare($insertQuery);
            $insertStmt->bind_param("iiiid", $studentId, $classId, $subjectId, $examId, $marks);
            if (!$insertStmt->execute()) {
                $success = false;
            }
            $insertStmt->close();
        }

        $stmt->close();
    }

    // Redirect back to the form with a success or error message
    if ($success) {
        header("Location: enter_mark_std.php?success=1");
    } else {
        header("Location: enter_mark_std.php?error=1");
    }

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