<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if file was uploaded without errors
    if (isset($_FILES["importFile"]) && $_FILES["importFile"]["error"] == 0) {
        $fileName = $_FILES["importFile"]["name"];
        $tempName = $_FILES["importFile"]["tmp_name"];
        
        // Define upload path and ensure directory exists
        $uploadDir = "../uploads";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $filePath = "$uploadDir/$fileName";
        
        // Move uploaded file to the upload directory
        if (!move_uploaded_file($tempName, $filePath)) {
            echo "Failed to move uploaded file.";
            exit();
        }

        // Process the uploaded file
        if (($handle = fopen($filePath, "r")) !== FALSE) {
            include_once './dbconn.php';

            // Prepare SQL statement
            $sql = "INSERT INTO web_app_staff_list (firstname, middlename, lastname, companyname, registration_link, phone, email_address, gender, dob) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = mysqli_prepare($conn, $sql);

            if ($stmt === false) {
                echo "Error preparing statement: " . mysqli_error($conn);
                exit();
            }

            mysqli_stmt_bind_param($stmt, "sssssssss", $firstname, $middlename, $lastname, $companyname, $registration_link, $phone, $email_address, $gender, $dob);
            
            // Flag to skip the first line
            $isFirstLine = true;

            // Read each row of the CSV file and insert data
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if ($isFirstLine) {
                    $isFirstLine = false;
                    continue;
                }

                // Assign CSV data
                $firstname = $data[1] ?? '';
                $middlename = $data[2] ?? '';
                $lastname = $data[3] ?? '';
                $companyname = $data[4] ?? '';
                $registration_link = $data[5] ?? '';
                $phone = $data[6] ?? '';
                $email_address = $data[7] ?? '';
                $gender = $data[8] ?? '';
                $dob = $data[9] ?? '';

                if (!mysqli_stmt_execute($stmt)) {
                    echo "Error inserting row: " . mysqli_stmt_error($stmt);
                    exit();
                }
            }

            mysqli_stmt_close($stmt);
            mysqli_close($conn);
            fclose($handle);

            // Redirect
            header("Location: stafflist.php?success");
            exit();
        } else {
            echo "Error opening file.";
        }
    } else {
        echo "Error uploading file. Error code: " . $_FILES["importFile"]["error"];
    }
}
?>
