<?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;  

$batch_size = 3000;
$table_name = "route_details";

$records_inserted = 0;
$records_updated  = 0;  

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

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

while (!feof($fp)) {

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

    if ($flag && $buffer) { 

        $variable_array = array(
            "Part_Number","Route_Number"
        );

        foreach ($variable_array as $key=>$val){        
            ${$val} = addslashes(trim($buffer[$key]));
        }

        // Skip header or empty
        if ($Part_Number == "Part_Number" || empty($Part_Number)) {
            continue;
        }

        // ================= GET PART ID =================
        $part_id = utility::getTableFieldById(
            "item_management",
            "id",
            "part_number",
            $Part_Number
        );

        // If part not found → skip
        if (empty($part_id)) {
            continue;
        }

        // ================= CHECK EXIST IN route_details =================
        $check_query = mysqli_query($conn, "
            SELECT id 
            FROM route_details 
            WHERE item_id = '$part_id'
            LIMIT 1
        ");

        if (mysqli_num_rows($check_query) > 0) {

            // ===== UPDATE =====
            $row = mysqli_fetch_assoc($check_query);
            $route_id = $row['id'];

            mysqli_query($conn, "
                UPDATE route_details 
                SET route_no = '$Route_Number',
                    updated_by = '$updated_by',
                    updated_on = '$created_on'
                WHERE id = '$route_id'
            ");

            $records_updated++;

        } else {

            // ===== INSERT =====
            mysqli_query($conn, "
                INSERT INTO route_details 
                (item_id, route_no, created_by, created_on) 
                VALUES 
                ('$part_id', '$Route_Number', '$created_by', '$created_on')
            ");

            $records_inserted++;
        }
    }
}

fclose($fp);
?>

<?php 
if($records_inserted){    
  echo '<br><span style="font-family:calibri;color:green;">'.($records_inserted).' records has been inserted...</span>';
}
?>

<?php 
if($records_updated){    
  echo '<br><span style="font-family:calibri;color:blue;">'.($records_updated).' records has been updated...</span>';
}
?>