<?php
include "../include/config.php";

if (isset($_POST['bulk'])) {
    $studentIds = $_POST['studentid'];
    $courses = $_POST['course'];
    $caArray = $_POST['ca'];
        $caArray1 = $_POST['ca1'];
    $caArray2 = $_POST['ca2'];
    $email2 = $_POST['email'];

    $examArray = $_POST['exam'];
    $terms = $_POST['term'];
    $years = $_POST['year'];
    $intake = $_POST['intake'];
    $existingRecordsCount = 0;
    $newlyInsertedRecordsCount = 0;

    for ($i = 0; $i < count($studentIds); $i++) {
        $studentId = $studentIds[$i];
        $course = $courses[$i];
        $ca = trim($caArray[$i]);
         $ca1 = trim($caArray1[$i]); 
         $ca2 = trim($caArray2[$i]);
        $exam = trim($examArray[$i]);
        $term = $terms[$i];
        $year = $years[$i];
        $intakes = $intake[$i];
        $email = trim($email2[$i]);


        // Check if record exists
        $stmt = $conn->prepare("SELECT * FROM `results` WHERE `studentid` = ? AND `course` = ? AND `term` = ? AND `year` = ?");
        $stmt->bind_param("ssss", $studentId, $course, $term, $year);
        $stmt->execute();
        $result1 = $stmt->get_result();

        if ($result1->num_rows == 0) {
            // Insert new record
            $save = $conn->prepare("INSERT INTO `results` (`studentid`, `course`, `term`, `year`, `intake`, `ca`, `ca1`, `ca2`, `exam`,`email`) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?)");
            $save->bind_param("ssssssssss", $studentId, $course, $term, $year, $intakes, $ca,$ca1,$ca2, $exam,$email);

            if ($save->execute()) {
                $newlyInsertedRecordsCount++;
            } else {
                header("Location: push.php?error=Not saved. Existing Records Count: {$existingRecordsCount}, Newly Count: {$newlyInsertedRecordsCount}");
                exit;
            }
        } else {
            $existingRecordsCount++;
        }
    }

    // Redirect with success message
    header("Location: push.php?success=Your Course has been successfully Pushed. Existing Count: {$existingRecordsCount}, Newly Count: {$newlyInsertedRecordsCount}");
    exit;
}
?>
