<?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     = "Groups.csv";
$destfile = $destdir.$name;  

$batch_size = 3000;
$table_name = "group_mangmnt";
$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("Internal_Part_Number","Group_No1","Group_No2","Group_No3");
			foreach($variable_array as $key=>$val){		
				//${$val} = addslashes(trim(strtolower($buffer[$key])));
				${$val} = addslashes(trim($buffer[$key]));
			}
			if($Group_No3 =="Group_No3"){
				continue;
			}
			
			$part_id = utility::getTableFieldById(
                "item_management",
                "id",
                "part_number",
                $Internal_Part_Number
            );
if(empty($part_id)){
    $missing_parts[] = $Internal_Part_Number;
    continue; // skip this row
}
			if (substr($Group_No3, 0, 1) == 'M') {
				$group_type = 'mandatory';
			} elseif (substr($Group_No3, 0, 1) == 'V') {
				$group_type = 'optional';
			}
			$created_by					= $_SESSION['user_id'];
        	$created_on					= date("Y-m-d H:i:s");	
        	$updated_by					= $_SESSION['user_id'];
			$group_number = $Group_No3;

// check if group already exists
$check_sql = "SELECT id FROM group_mangmnt WHERE group_number='$group_number' LIMIT 1";
$check_res = mysqli_query($conn, $check_sql);

if(mysqli_num_rows($check_res) > 0){
    // group already exists
    $row = mysqli_fetch_assoc($check_res);
    $group_id = $row['id'];
}else{
    // insert new group
    $sql = "INSERT INTO group_mangmnt(`group_number`,`group_type`,`description`) 
            VALUES('$group_number','$group_type','$group_number')";
    mysqli_query($conn,$sql);
    $group_id = mysqli_insert_id($conn);

    $records_inserted++;
}


			
			$sql_mapp =  "INSERT INTO group_mangmnt_mapping(`group_id`,`part_id`) VALUE('$group_id','$part_id')";
			
			mysqli_query($conn,$sql_mapp);
	  }
  }
}
?>
<?php 
if(!empty($missing_parts)){
    echo "<br><b>Part numbers not found in item_management:</b><br>";
    echo implode("<br>", array_unique($missing_parts));
}
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>';
}?>