<?php

$message = "";

if(isset($_POST['import']))
{
    if(isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0)
    {
        $fileName = $_FILES['csv_file']['name'];
        $fileTmp  = $_FILES['csv_file']['tmp_name'];
        $fileSize = $_FILES['csv_file']['size'];

        // Check extension
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);

        if($ext == "csv")
        {
            if($fileSize > 0)
            {
                $handle = fopen($fileTmp, "r");

                $rowCount = 0;

                while(($data = fgetcsv($handle, 1000, ",")) !== FALSE)
                {
                    $rowCount++;

                    // Example:
                    // $name = $data[0];
                    // $email = $data[1];

                    // Insert into database here
                }

                fclose($handle);

                $message = "
                <div class='alert alert-success'>
                    CSV File Uploaded Successfully.<br>
                    Total Rows Imported: ".$rowCount."
                </div>";
            }
            else
            {
                $message = "
                <div class='alert alert-danger'>
                    CSV File is Empty.
                </div>";
            }
        }
        else
        {
            $message = "
            <div class='alert alert-danger'>
                Only CSV files are allowed.
            </div>";
        }
    }
    else
    {
        $message = "
        <div class='alert alert-danger'>
            Please select a CSV file.
        </div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>CSV Import</title>

    <!-- Bootstrap -->
    <link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>

<div class="container mt-5">

    <h2>Upload CSV File</h2>

    <!-- MESSAGE SHOW HERE -->
    <?php echo $message; ?>

    <form method="POST"
          enctype="multipart/form-data">

        <div class="form-group">
            <label>Select CSV File</label>

            <input type="file"
                   name="csv_file"
                   class="form-control"
                   accept=".csv"
                   required>
        </div>

        <button type="submit"
                name="import"
                class="btn btn-primary">
            Import CSV
        </button>

    </form>

</div>

</body>
</html>