<?php require_once ('header.php');

function convertCsvToJson($csvFilePath){
    if (($handle = fopen($csvFilePath, "r")) !== FALSE) {
        $csvs = [];
        while(! feof($handle)) {
           $csvs[] = fgetcsv($handle);
        }
        $datas = [];
        $column_names = [];
        foreach ($csvs[0] as $single_csv) {
            $column_names[] = $single_csv;
        }
        $l=2;
        foreach ($csvs as $key => $csv) {
            if ($key === 0) {
                continue;
            }
            if(count($csvs)>$l){
                foreach ($column_names as $column_key => $column_name) {
                    $datas[$key-1][$column_name] = $csv[$column_key];
                }
            }
            $l++;
        }
        $json = json_encode($datas);
        fclose($handle);
        return $json;
        }
}

if (isset($_POST["Import"]))
{
    try
    {
        $csvFilePath = $_FILES["file"]["tmp_name"];

        $result=convertCsvToJson($csvFilePath);
        $result = json_decode($result, TRUE);
        
        for($i=0;$i<count($result);$i++){
            $insert_status=1;$error_msg='';
            
            $pl3_awb_no=$result[$i]['AWB_NO'];
         	$statement = $pdo->prepare("SELECT * FROM `pickup_entry` WHERE 3pl_awb='$pl3_awb_no'");
			$statement->execute();
			$result = $statement->fetchAll(PDO::FETCH_ASSOC);
			$count = $statement->rowCount();
			if($count>0)
			{
			    $error_msg."Row Number ".$ri." 3PL AWB Number Already Exist...<br>";
			    $insert_status=0;
			}
			
			$courier_id=$result[$i]['COURIER_ID'];
			if($courier_id!=''){
             	$statement = $pdo->prepare("SELECT * FROM `courier_company` WHERE id='$courier_id'");
    			$statement->execute();
    			$result = $statement->fetchAll(PDO::FETCH_ASSOC);
    			$count = $statement->rowCount();
    			if($count>0)
    			{
    			    $error_msg."Row Number ".$ri." Invaloid Courier Company ID...<br>";
    			    $insert_status=0;
    			}
			}
			
			$shipper_id=$result[$i]['SHIPPER_ID'];
         	$statement = $pdo->prepare("SELECT * FROM `tbl_user` WHERE role='Modicare' and id='$shipper_id'");
			$statement->execute();
			$shipper_details = $statement->fetchAll(PDO::FETCH_ASSOC);
			$count = $statement->rowCount();
			if($count>0)
			{
			    $error_msg."Row Number ".$ri." Shipper ID Is Invalid...<br>";
			    $insert_status=0;
			}
        }

        
    }catch(Exception $e){
        echo $e;
    }    
} ?>

<style>
    td,th{
        border:1px solid gray;
    }
</style>
<?php require_once ('footer.php'); ?>