<?php
set_time_limit(0);
ini_set('memory_limit', '1024M');

$destdir  = "live-data-migration-csvs/";
$name     = "nominal_codes.csv";
$destfile = $destdir . $name;

$records_inserted = 0;
$records_skipped  = 0;
$created_by       = $_SESSION['user_id'];
$created_on       = date("Y-m-d H:i:s");

$fp = fopen($destfile, 'r');
$header = true;

while (!feof($fp)) {
    $buffer = fgetcsv($fp, 1000000, ',');

    if (!$buffer) continue;

    // Skip header row
    if ($header) {
        $header = false;
        continue;
    }

    $nominal_code             = addslashes(trim($buffer[0]));
    $nominal_code_description = addslashes(trim($buffer[1]));

    if ($nominal_code == "") continue;

    // Check if already exists
    $check = mysqli_query($conn, "SELECT id FROM nominal_codes WHERE nominal_code = '$nominal_code'");
    if (mysqli_num_rows($check) > 0) {
        $records_skipped++;
        continue;
    }

    $sql = "INSERT INTO nominal_codes (nominal_code, nominal_code_description, created_by, created_on, updated_by, updated_on)
            VALUES ('$nominal_code', '$nominal_code_description', '$created_by', '$created_on', '$created_by', '$created_on')";

    mysqli_query($conn, $sql);
    $records_inserted++;
}

fclose($fp);
?>

<?php if ($records_inserted): ?>
    <br><span style="font-family:calibri;color:green;"><?= $records_inserted ?> record(s) inserted.</span>
<?php endif; ?>

<?php if ($records_skipped): ?>
    <br><span style="font-family:calibri;color:orange;"><?= $records_skipped ?> record(s) skipped (already exist).</span>
<?php endif; ?>