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

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

$batch_size = 3000;
$table_name = "item_management";
$records_inserted = 0;
$records_updated = 0;  
                                   
$flag = true;
$fp = fopen($destfile, 'r');
while (!feof ($fp)){
  $buffer = fgetcsv($fp, 1000000, ',');  
  if($flag) { 
	  if($buffer){
		$variable_array = array("PartNumber","Description","Type","Colour","GRADE","GRAIN","Length","Width","Thickness");

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

if ($PartNumber == "PartNumber") {
    continue;
}



$Type_id = utility::getTableFieldById(
    "raw_materials",  
    "id",                
    "type",       
    $Type 
);

$keycode_id = utility::getTableFieldById(
    "keycode",  
    "id",              
    "code",       
    $GRAIN 
);


$checkSql = "SELECT id FROM $table_name WHERE part_number = '$PartNumber' LIMIT 1";
$checkResult = mysqli_query($conn, $checkSql);

if (mysqli_num_rows($checkResult) > 0) {

    $row = mysqli_fetch_assoc($checkResult);
    $part_id = $row['id'];

    $records_updated++;

    $updateSql = "UPDATE $table_name SET 
                    product_description = '$Description',
                    type = '$Type_id',
                    grade = '$grade',
                    grain = '$keycode_id',
                    color = '$Colour',
                    length_mm = '$Length',
                    width_mm = '$Width',
                    thickness = '$Thickness'
                  WHERE id = '$part_id'";

    mysqli_query($conn, $updateSql);

} else {

    $records_inserted++;

    $insertSql = "INSERT INTO $table_name 
    (`part_number`,`product_description`,`type`,`grade`,`grain`,`color`,`length_mm`,`width_mm`,`thickness`,`usual_source`) 
    VALUES 
    ('$PartNumber','$Description','$Type_id','$grade','$keycode_id','$Colour','$Length','$Width','$Thickness','Bought In')";

    mysqli_query($conn, $insertSql);
    $partt_id = mysqli_insert_id($conn);


    $sql_product_name = "INSERT INTO product_name 
            (`pro_id`,`group_number`,`group_code`,`group_name`,`qty`) 
            VALUES ('$partt_id','$PartNumber','Bought In','$PartNumber','1')";
    mysqli_query($conn, $sql_product_name);
    $partt_idd = mysqli_insert_id($conn);

    $sql_update = "UPDATE item_management 
                   SET part_number_id = '$partt_idd' 
                   WHERE id = '$partt_id'";
    mysqli_query($conn, $sql_update);
}


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