<?php
die;
set_time_limit(0);
ini_set('memory_limit','1024M');
ini_set('post_max_size','32M');
ini_set('upload_max_filesize','32M');

include "config.php";

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

$table_name = "route_details";

$records_inserted = 0;
$records_updated  = 0;
$missing_parts    = array();

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

while (!feof($fp)) {

    $buffer = fgetcsv($fp, 1000000, ',');

    if ($buffer) {

        $Route_Number = addslashes(trim($buffer[0]));
        $Part_Number  = addslashes(trim($buffer[1]));

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

        /* ---------------------------------------
           GET PART ID FROM item_management
        --------------------------------------- */

        $part_id = utility::getTableFieldById(
                        "item_management",
                        "id",
                        "part_number",
                        $Part_Number
                   );

        /* ---------------------------------------
           IF PART NOT FOUND
        --------------------------------------- */

        if (!$part_id) {
            $missing_parts[] = $Part_Number;
            continue;
        }

        /* ---------------------------------------
           CHECK IF PART EXISTS IN route_details
        --------------------------------------- */

        $check_sql = "SELECT id 
                      FROM $table_name
                      WHERE item_id = '$part_id'";

        $check = mysqli_query($conn, $check_sql);

        if (mysqli_num_rows($check) > 0) {

            /* -------- UPDATE -------- */

            $update_sql = "UPDATE $table_name
                           SET route_no = '$Route_Number'
                           WHERE item_id = '$part_id'";

            mysqli_query($conn, $update_sql);
            $records_updated++;

        } else {

            /* -------- INSERT -------- */

            $insert_sql = "INSERT INTO $table_name
                           (`route_no`,`item_id`)
                           VALUES
                           ('$Route_Number','$part_id')";

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

fclose($fp);


/* ---------------- RESULTS ---------------- */

echo "<br><b>Inserted :</b> $records_inserted";
echo "<br><b>Updated :</b> $records_updated";

if (!empty($missing_parts)) {

    echo "<br><br><b>Parts Not Found In item_management:</b><br>";

    foreach ($missing_parts as $p) {
        echo $p."<br>";
    }
}
?>
