<?php
// Include database connection code
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fileToUpload"]) && isset($_POST["class"])) {
    $class = mysqli_real_escape_string($conn, $_POST['class']);

    // $targetDirectory = "uploads/"; // Specify the directory where you want to store uploaded files
    $targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Check if the file is a CSV file
    if ($fileType == "csv") {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
            $csvFile = fopen($targetFile, "r");

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

            while (($data = fgetcsv($csvFile)) !== FALSE) {
                // Parse CSV data
                $regdId = mysqli_real_escape_string($conn, $data[0]);
                $symno = mysqli_real_escape_string($conn, $data[1]);
                $name = mysqli_real_escape_string($conn, $data[2]);
                $gender = mysqli_real_escape_string($conn, $data[3]);
                $dob = mysqli_real_escape_string($conn, $data[4]);
                $address = mysqli_real_escape_string($conn, $data[5]);
                $phone = mysqli_real_escape_string($conn, $data[6]);
                $email = mysqli_real_escape_string($conn, $data[7]);
                $parentName = mysqli_real_escape_string($conn, $data[8]);
                $parentPhone = mysqli_real_escape_string($conn, $data[9]);
                $ent_group = mysqli_real_escape_string($conn, $data[10]);
                // $section = mysqli_real_escape_string($conn, $data[10]);
                // $classId = mysqli_real_escape_string($conn, $data[11]);

                // Insert data into the students table
                $query = "INSERT INTO students (regd_id,symbol_no, name, gender, dob, address, phone, email, parent_name, parent_phone, class, Class_id, section, std_group, status) 
                          VALUES ('$regdId','$symno', '$name','$gender','$dob', '$address', '$phone', '$email', '$parentName', '$parentPhone', '$class','$class','','$ent_group','Active' )";

                if ($conn->query($query) !== TRUE) {
                    echo "Error inserting data: " . $conn->error;
                    break;
                }
            }

            fclose($csvFile);
            echo "Data imported successfully!";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    } else {
        echo "Only CSV files are allowed.";
    }
}
?>
