<?php
// Include necessary files and connect to the database
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["csv_file"])) {
    $classId = $_POST["class_id"];
    $subjectId = $_POST["subject_id"];
    $examtype = $_POST["exam_id"];

    // Check if the uploaded file is a CSV
    $fileType = pathinfo($_FILES["csv_file"]["name"], PATHINFO_EXTENSION);
    if ($fileType == "csv") {
        $file = $_FILES["csv_file"]["tmp_name"];

        // Open and read the CSV file
        $handle = fopen($file, "r");

        // Skip the header row
        fgetcsv($handle);

  

        // Prepare statement for inserting marks into the database
        $stmt = $conn->prepare("INSERT INTO int_marks (student_id, class_id, subject_id, exam_type, internal_marks) VALUES (?, ?, ?, ?, ?)");

        // Assuming CSV columns are: Student ID, Regd ID, Name, Sym No., Marks
        $stmt->bind_param("iiiss", $studentId, $classId, $subjectId,$examtype, $marks);

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            // Assuming the CSV columns are in this order: Student ID, Regd ID, Name, Sym No., Marks
            $studentId = $data[0];
            $regdId = $data[1];
            $name = $data[2];
            $symNo = $data[3];
            $marks = $data[4];

            // Insert marks into the database
            $stmt->execute();
        }

        fclose($handle);
        $stmt->close();

        // Display success alert using SweetAlert
        echo "<script>
                swal({
                    title: 'Success!',
                    text: 'Marks uploaded successfully!',
                    icon: 'success',
                    button: 'OK'
                }).then(function() {
                    window.location = 'bulk_marks_pr.php';
                });
             </script>";
    } else {
        echo "Please upload a CSV file.";
    }
} else {
    echo "Invalid request.";
}

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