<?php
require '../config.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if file was uploaded without errors
    if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
        $filename = $_FILES["file"]["name"];
        $filetype = $_FILES["file"]["type"];
        $filesize = $_FILES["file"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if ($ext != "csv") {
            die("Error: Please upload a valid CSV file.");
        }

        // Open the uploaded CSV file
        if (($handle = fopen($_FILES["file"]["tmp_name"], "r")) !== FALSE) {
            fgetcsv($handle); // Skip the header row

            // Prepare the SQL statement outside the loop
            $sql = "INSERT INTO usuarios (usuario, email, clave, estudiante, curso, paralelo, especialidad) VALUES (?, ?, ?, ?, ?, ?, ?)";
            if (!$stmt = $conn->prepare($sql)) {
                die("Error preparing statement: " . $conn->error);
            }

            // Bind parameters
            $stmt->bind_param("sssssss", $usuario, $email, $clave, $estudiante, $curso, $paralelo, $especialidad);

            // Loop through the CSV rows
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                // Check if the row has exactly 7 columns
                if (count($data) == 7) {
                    // Assign CSV data to variables
                    list($usuario, $email, $clave, $estudiante, $curso, $paralelo, $especialidad) = $data;

                    // Execute the prepared statement
                    if (!$stmt->execute()) {
                        echo "Error inserting row: " . $stmt->error . "<br>";
                    }
                } else {
                    echo "Skipping invalid row: " . implode(",", $data) . "<br>";
                }
            }

            fclose($handle);
            echo "Data has been uploaded successfully!";
        } else {
            echo "Error: Unable to open the file.";
        }
    } else {
        echo "Error: " . $_FILES["file"]["error"];
    }
} else {
    echo "Invalid request.";
}

$conn->close();
?>
