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

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

// Loop through each student and update or insert scores
foreach ($student_ids as $student_id) {
    $score = $scores[$student_id];

    // Check if the record already exists
    $check_query = "
        SELECT id FROM results 
        WHERE student_id = $student_id 
        AND subject_id = $subject_id 
        AND month = '$month'
    ";
    $check_result = $conn->query($check_query);

    if ($check_result->num_rows > 0) {
        // Update existing record
        $update_query = "
            UPDATE results 
            SET score_given = $score 
            WHERE student_id = $student_id 
            AND subject_id = $subject_id 
            AND month = '$month'
        ";
        $conn->query($update_query);
    } else {
        // Insert new record
        $insert_query = "
            INSERT INTO results (student_id, subject_id, month, score_given) 
            VALUES ($student_id, $subject_id, '$month', $score)
        ";
        $conn->query($insert_query);
    }
}

echo "Scores have been successfully saved!";
?>
