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

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fileToUpload"]) && isset($_POST["class"])) {
    $class = $_POST['class']; // Assuming $_POST['class'] is a safe value

    // $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);

            $stmt = $conn->prepare("INSERT INTO students (regd_id, symbol_no, name, gender, dob, address, phone, email, parent_name, parent_phone, class, Class_id) 
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $stmt->bind_param("ssssssssssss", $regdId, $symno, $name, $gender, $dob, $address, $phone, $email, $parentName, $parentPhone, $class, $class);

            while (($data = fgetcsv($csvFile)) !== FALSE) {
                // Parse CSV data
                list($regdId, $symno, $name, $gender, $dob, $address, $phone, $email, $parentName, $parentPhone) = array_map('trim', $data);
                
                // Additional validation (adjust as per your needs)
                if (empty($regdId) || empty($symno) || empty($name) || empty($gender) || empty($dob) || empty($address) || empty($phone) || empty($email) || empty($parentName) || empty($parentPhone)) {
                    echo "Error: All fields must be filled.";
                    break;
                }

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

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