<?php require_once ('header.php');
function generateNextNumber($currentNumber) {
    preg_match('/(\d+)$/', $currentNumber, $matches);
    $currentNumericPart = $matches[1];

    $nextNumericPart = str_pad($currentNumericPart + 1, strlen($currentNumericPart), '0', STR_PAD_LEFT);

    $nextNumber = preg_replace('/\d+$/', $nextNumericPart, $currentNumber);

    return $nextNumber;
}
function generateUniqueId($prefix = 'ak-exp') {
    // Get the current time in microseconds and ensure uniqueness by combining it with a random number
    $uniqueId = uniqid($prefix, true);
    
    // Replace dots with nothing or another character to ensure a clean ID
    $uniqueId = str_replace('.', '', $uniqueId);

    // Optionally, you can add a random string at the end to further ensure uniqueness
    $randomString = substr(md5(mt_rand()), 0, 8);
    $uniqueId .= $randomString;

    return $uniqueId;
}
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[] = filter_var($single_csv, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);
        }

        $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] = filter_var($csv[$column_key], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);
                }
            }
            $l++;
        }
        fclose($handle);

        $json = json_encode($datas);
        
     
        return $json;
    }
}




if(isset($_POST["Import"])){
    try
    {
        $m_id='';$dummy_a=0;$dummy_c=0;$dummy_box=1;
 $success_count=0;
        $pdo->beginTransaction();
        $csvFilePath = $_FILES["file"]["tmp_name"];
        
        
$csvContent = file_get_contents($csvFilePath);

$encoding = mb_detect_encoding($csvContent, mb_list_encodings(), true);
if ($encoding != 'UTF-8') {
    $csvContent = mb_convert_encoding($csvContent, 'UTF-8', $encoding);
}
		 //   bulkupload id
$uid = generateUniqueId();

$cleanContent =  $csvContent;
        
        
        
        $new_client_id=$_POST['new_client'];
        $branch_id=1;
        $date=date('Y-m-d');
        $result=convertCsvToJson($csvFilePath);
 
        $result = json_decode($result, TRUE);
        
    $table="";
    $table.= "<section class='content-header'>
    <div class='box-body' style='margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;'>
				<div class='box-body table-responsive'><table id='error_table'  class='table table-bordered table-striped'><tr style='
    background: #c83600;
    color: white;'>
    <th>S.NO</th><th>ERROR MESSAGE</th>
    <th>COURIER_ID</th>
    <th>WAY_BILL</th>
    <th>EXPIRY_DATE</th>
    <th>REFERENCE_NO</th>
    <th>MASTER_ID</th>
    <th>CONSIGNEE_NAME</th>
    <th>CITY</th>
    <th>STATE</th>
    <th>COUNTRY</th>
    <th>ADDRESS</th>
    <th>PINCODE</th>
    <th>PHONE</th>
    <th>MOBILE</th>
    <th>WEIGHT</th>
    <th>SHIPMENT_LENGTH</th>
    <th>SHIPMENT_BREADTH</th>
    <th>SHIPMENT_HEIGHT</th>
    <th>PACKAGING_TYPE</th>
    <th>PAYMENT_MODE</th>
    <th>PACKAGE_AMOUNT</th>
    <th>COD_AMOUNT</th>
    <th>PRODUCT_TO_BE_SHIPPED</th>
    <th>VENDOR_PICKUP_LOCATION</th>
    <th>RETURN_ADDRESS</th>
    <th>RETURN_PINCODE</th>
    <th>SHIPPING_MODE</th>
    <th>FRAGILE_SHIPMENT</th>
    <th>ALTERNATE_PHONE</th>
    <th>SHIPMENT_TYPE</th>
    <th>MPS_CHILDRES</th>
    <th>MPS_AMOUNT</th>
    <th>SELLER_NAME</th>
    <th>SELLER_PINCODE</th>
    <th>SELLER_ADDRESS</th>
    <th>SELLER_CST_NO</th>
    <th>SELLER_TIN</th>
    <th>INVOICE_NO</th>
    <th>INVOICE_DATE</th>
    <th>QUANTITY</th>
    <th>COMMODITY_VALUE</th>
    <th>TAX_VALUE</th>
    <th>CATEGORY_OF_GOODS</th>
    <th>SELLER_GST_TIN</th>
    <th>HSN_CODE</th>
    <th>RETURN_REASON</th>
    <th>EWBN</th>
    <th>TAXABLE_AMOUNT</th>
    <th>DOCUMENT_NUMBER<th>
    <th>DOCUMENT_TYPE<th>
    <th>DOCUMENT_DATE<th>
    <th>SELLER_GST_AMOUNT<th>
    <th>GST_CESS_AMOUNT<th>
    <th>INTEGRATED_GST_AMOUNT<th>
    <th>CONSIGNEE_GST_AMOUNT<th>
    
    </tr><tbody id='tbodyid'>";
    
        $last_booking_id=0;$error_count=0;
        for($i=0;$i<count($result);$i++){
            $insert_status=1; $error_msg='';$is_volumetrix=0;$client_id = 0; $pickup_id=0;
            //COURIER_ID,<th>WAY_BILL<th>            REFERENCE_NO,CONSIGNEE_NAME,CITY,STATE,COUNTRY,ADDRESS,PINCODE,PHONE,MOBILE,WEIGHT,SHIPMENT_LENGTH,SHIPMENT_BREADTH,SHIPMENT_HEIGHT,PACKAGING_TYPE,PAYMENT_MODE,PACKAGE_AMOUNT,COD_AMOUNT,PRODUCT_TO_BE_SHIPPED,VENDOR_PICKUP_LOCATION,RETURN_ADDRESS,RETURN_PINCODE,SHIPPING_MODE,FRAGILE_SHIPMENT,ALTERNATE_PHONE,SHIPMENT_TYPE,MASTER_ID,MPS_CHILDRES,MPS_AMOUNT,SELLER_NAME,SELLER_ADDRESS,SELLER_CST_NO,SELLER_TIN,INVOICE_NO,INVOICE_DATE,QUANTITY,COMMODITY_VALUE,TAX_VALUE,CATEGORY_OF_GOODS,SELLER_GST_TIN,HSN_CODE,RETURN_REASON,EWBN
            
            // Values - Here
            // $COURIER_ID = $result[$i]['COURIER_ID'] ?? 1;
            $WAY_BILL = $result[$i]['WAY_BILL'] ?? '';
            $EXPIRY_DATE=$result[$i]['EXPIRY_DATE']?? '';
            $REFERENCE_NO = $result[$i]['REFERENCE_NO']?? '';
            $CONSIGNEE_NAME = $result[$i]['CONSIGNEE_NAME']?? '';
            $CITY = $result[$i]['CITY']?? '';
            $STATE = $result[$i]['STATE']?? '';
            $COUNTRY = $result[$i]['COUNTRY']?? '';
            $ADDRESS = $result[$i]['ADDRESS']?? '';
            $PINCODE = $result[$i]['PINCODE']?? '';
            $PHONE = $result[$i]['PHONE']?? '';
            $MOBILE = $result[$i]['MOBILE']?? '';
            $WEIGHT = $result[$i]['WEIGHT'] ?? 0;
            $SHIPMENT_LENGTH = $result[$i]['SHIPMENT_LENGTH'] ?? 1;
            $SHIPMENT_BREADTH = $result[$i]['SHIPMENT_BREADTH'] ?? 1;
            $SHIPMENT_HEIGHT = $result[$i]['SHIPMENT_HEIGHT'] ?? 1;
            $PACKAGING_TYPE = $result[$i]['PACKAGING_TYPE']?? '';
            $PAYMENT_MODE = $result[$i]['PAYMENT_MODE']?? '';
            $PACKAGE_AMOUNT = $result[$i]['PACKAGE_AMOUNT'] ?? 0;
            $COD_AMOUNT = $result[$i]['COD_AMOUNT'] ?? 0;
            $PRODUCT_TO_BE_SHIPPED = $result[$i]['PRODUCT_TO_BE_SHIPPED']?? '';
            $VENDOR_PICKUP_LOCATION = $result[$i]['VENDOR_PICKUP_LOCATION']?? '';
            $RETURN_ADDRESS = $result[$i]['RETURN_ADDRESS']?? '';
            $RETURN_PINCODE = $result[$i]['RETURN_PINCODE']?? '';
            $SHIPPING_MODE = $result[$i]['SHIPPING_MODE']?? '';
            $FRAGILE_SHIPMENT = $result[$i]['FRAGILE_SHIPMENT']?? '';
            $ALTERNATE_PHONE = $result[$i]['ALTERNATE_PHONE']?? '';
            $SHIPMENT_TYPE = $result[$i]['SHIPMENT_TYPE']?? '';
            $MASTER_ID = $result[$i]['MASTER_ID']?? '';
            $MPS_CHILDRES = $result[$i]['MPS_CHILDRES']?? '';
            $MPS_AMOUNT = $result[$i]['MPS_AMOUNT']?? '';
            $SELLER_NAME = $result[$i]['SELLER_NAME']?? '';
            $SELLER_PINCODE = $result[$i]['SELLER_PINCODE']?? '';
            $SELLER_ADDRESS = $result[$i]['SELLER_ADDRESS']?? '';
            $SELLER_CST_NO = $result[$i]['SELLER_CST_NO']?? '';
            $SELLER_TIN = $result[$i]['SELLER_TIN']?? '';
            $INVOICE_NO = $result[$i]['INVOICE_NO']?? '';
            $INVOICE_DATE = $result[$i]['INVOICE_DATE']?? '';
            $QUANTITY = $result[$i]['QUANTITY']?? '';
            $COMMODITY_VALUE = $result[$i]['COMMODITY_VALUE']?? '';
            $TAX_VALUE = $result[$i]['TAX_VALUE']?? '';
            $CATEGORY_OF_GOODS = $result[$i]['CATEGORY_OF_GOODS']?? '';
            $SELLER_GST_TIN = $result[$i]['SELLER_GST_TIN']?? '';
            $HSN_CODE = $result[$i]['HSN_CODE']?? '';
            $RETURN_REASON = $result[$i]['RETURN_REASON']?? '';
            $EWBN = $result[$i]['EWBN']?? '';
            $TAXABLE_AMOUNT = $result[$i]['TAXABLE_AMOUNT']?? '';
            $DOCUMENT_NUMBER = $result[$i]['DOCUMENT_NUMBER']?? '';
            $DOCUMENT_TYPE = $result[$i]['DOCUMENT_TYPE']?? '';
            $DOCUMENT_DATE = $result[$i]['DOCUMENT_DATE']?? '';
            $SELLER_GST_AMOUNT = $result[$i]['SELLER_GST_AMOUNT']?? '';
            $GST_CESS_AMOUNT = $result[$i]['GST_CESS_AMOUNT']?? '';
            $INTEGRATED_GST_AMOUNT = $result[$i]['INTEGRATED_GST_AMOUNT']?? '';
            $CONSIGNEE_GST_AMOUNT = $result[$i]['CONSIGNEE_GST_AMOUNT']?? '';
            
            /*reassigned*/
            $DOCUMENT_NUMBER = $INVOICE_NO;
            
            $SELLER_CITY="";
            $SELLER_STATE="";
            //$SELLER_PINCODE="";
            $SELLER_COUNTRY="";
            $SELLER_PHONE="";
            $SELLER_MOBILE="";
            
            
            $VENDOR_PICKUP_LOCATION_CITY="";
            $VENDOR_PICKUP_LOCATION_STATE="";
            $VENDOR_PICKUP_LOCATION_PINCODE="";
            $VENDOR_PICKUP_LOCATION_COUNTRY="";
            $VENDOR_PICKUP_LOCATION_PHONE="";
            $VENDOR_PICKUP_LOCATION_ADDRESS=""; 
           
            


            if($PACKAGE_AMOUNT >= 50000){  
                if($EWBN ==''){
                    $error_msg.="Row Number ".($i+1)." WAY BILL required...<br>";
                    $insert_status=0;   
                }
                if($EXPIRY_DATE ==''){
                    $error_msg.="Row Number ".($i+1)." EXPIRY DATE required...<br>";
                    $insert_status=0;   
                }
            }else{
                if($EWBN !='' ){
                    if($EXPIRY_DATE == ''){
                        $error_msg.="Row Number ".($i+1)." EXPIRY DATE required...<br>";
                        $insert_status=0;
                    }
                }
            }
    

        
        if($SHIPPING_MODE==""){
            $error_msg.="Row Number ".($i+1)." shipping mode Can't Be Empty...should be Express or Surface<br>";
			    $insert_status=0;
        }else if($SHIPPING_MODE=="EXPRESS"){
            $SHIPPING_MODE="Express";
        }else if($SHIPPING_MODE=="SURFACE"){
            $SHIPPING_MODE="Surface";
        }  
           error_log('stephen'.$EWBN);
    
	    if($EWBN != ''){
         	$statement = $pdo->prepare("SELECT * FROM `ewaybills` WHERE ewbNo='$EWBN'");
	    	$statement->execute();
	    	$counts = $statement->rowCount();
	    	$user_result = $statement->fetchAll(PDO::FETCH_ASSOC);
	    	if($counts == 0)
	    	{
	    	    $error_msg.="Row Number ".($i+1)." Invalid EWBN Exists.....<br>";
	    	    $insert_status=0;  
	    	}
	    }  
        
        
        if($SHIPPING_MODE!="Express" && $SHIPPING_MODE!="Surface"){
            $error_msg.="Row Number ".($i+1)." shipping mode Can't Be Empty...should be Express or Surface<br>";
			    $insert_status=0;
        } 
        
        
        if($PINCODE==""){
            $error_msg.="Row Number ".($i+1)." Consignee Pincode Can't Be Empty...<br>";
			    $insert_status=0;
        } 
        if($SELLER_PINCODE==""){
            $error_msg.="Row Number ".($i+1)." Seller Pincode Can't Be Empty...<br>";
			    $insert_status=0;
        }
        if($RETURN_ADDRESS==""){
            $error_msg.="Row Number ".($i+1)." Return Address Can't Be Empty...<br>";
			    $insert_status=0;
        }
        if($RETURN_PINCODE==""){
            $error_msg.="Row Number ".($i+1)." Return Pincode Can't Be Empty...<br>";
			    $insert_status=0;
        }
			if($SELLER_NAME!=''){
             	$statement = $pdo->prepare("SELECT * FROM `tbl_client_new` WHERE name='$SELLER_NAME'");
    			$statement->execute();
    			$counts = $statement->rowCount();
    			$user_result = $statement->fetchAll(PDO::FETCH_ASSOC);
    			if($counts)
    			{
    			    error_log("Seller LOOp Inside");
    			    $client_id=$user_result[0]['id'];
    			    $SELLER_CITY=$user_result[0]['city'];
                    $SELLER_STATE=$user_result[0]['state'];
                    $SELLER_PINCODE=$user_result[0]['pincode'];
                    $SELLER_COUNTRY="INDIA";
                    $SELLER_PHONE=$user_result[0]['phone_no'];
                    $SELLER_MOBILE=$user_result[0]['phone_no'];
                    if($SELLER_ADDRESS==""){
                        $SELLER_ADDRESS=$user_result[0]['address'];
                    }
                    
    			}
			}else if($SELLER_NAME==""){
			     $error_msg.="Row Number ".($i+1)." Seller Name Not Existing in Our Panel...<br>";
    			 $insert_status=0;
			}
			
			if($VENDOR_PICKUP_LOCATION!=''){
             	$statement = $pdo->prepare("SELECT * FROM `tbl_pickup_points` WHERE name='$VENDOR_PICKUP_LOCATION'");
    			$statement->execute();
    			$counts = $statement->rowCount();
    			$user_result = $statement->fetchAll(PDO::FETCH_ASSOC);
    			if($counts)
    			{
    			    $pickup_id=$user_result[0]['client_new_id'];
    			    $VENDOR_PICKUP_LOCATION_CITY=$user_result[0]['city'];
                    $VENDOR_PICKUP_LOCATION_STATE=$user_result[0]['state'];
                    $VENDOR_PICKUP_LOCATION_PINCODE=$user_result[0]['pincode'];
                    $VENDOR_PICKUP_LOCATION_COUNTRY=$user_result[0]['country'];
                    $VENDOR_PICKUP_LOCATION_PHONE=$user_result[0]['mobile_no'];
                    $VENDOR_PICKUP_LOCATION_ADDRESS=$user_result[0]['address'];
    			}else{
    			    $error_msg.="Row Number ".($i+1)." VENDOR PICKUP LOCATION Not Existing in Our Panel...<br>";
    			    $insert_status=0;
    			}
			}else if($VENDOR_PICKUP_LOCATION==""){
			     $error_msg.="Row Number ".($i+1)." VENDOR PICKUP LOCATION required...<br>";
    			 $insert_status=0;
			}
			
			if($WAY_BILL!=''){
             	$statement = $pdo->prepare("SELECT * FROM `pickup_entry` WHERE cscs_awb='$WAY_BILL'");
    			$statement->execute();
    			$counts = $statement->rowCount();
    			$user_result = $statement->fetchAll(PDO::FETCH_ASSOC);
    			if($counts)
    			{
    			    $error_msg.="Row Number ".($i+1)." AWB Is Already Exists.....<br>";
    			    $insert_status=0;
    			}
			}
       
            
        
        if($m_id!="" && $m_id==$MASTER_ID){ // Child
            $is_volumetrix=1;
        }else if($m_id!="" && $m_id!=$MASTER_ID){
            $is_volumetrix=0;
        }else{
            $is_volumetrix=0;
        }
        $m_id=$MASTER_ID;
			
			if($insert_status==1){
			    // Insert Here
			    
			    $collectable_amount = 0;
			    $ref_no = 0;
			    $order_type = 0;
			 //   taxable_amount,document_number,document_type,document_date,seller_gst_amount,gst_cess_amount,integrated_gst_amount,consignee_gst_amount

	if($is_volumetrix==0){
	    
	    $C_WEIGHT=round($SHIPMENT_HEIGHT*$SHIPMENT_HEIGHT*$SHIPMENT_BREADTH/5000,2);
	    
	    $FC_WEIGHT=$WEIGHT;
	    if($WEIGHT<$C_WEIGHT){
	        $FC_WEIGHT=$C_WEIGHT;
	    }
	    $date_added=date('Y-m-d');
	    
	    $statement = $pdo->prepare("SELECT o_ids,id FROM pickup_entry where date_added='".$date_added."' and o_ids!='' order by id desc limit 1");
    	$statement->execute();
    	$result_or = $statement->fetchAll(PDO::FETCH_ASSOC);
    	if($result_or){
    	    $serias_no=generateNextNumber($result_or[0]['o_ids']);
    	}else{
    	    $serias_no='001';
    	    $serias_no = "CCS/DEL/".date('dm').'/'.$serias_no;
    	}
        
        $order_id = $serias_no;
    $o_ids=$order_id;
    if($REFERENCE_NO!=""){
        $order_id=$REFERENCE_NO;
    }
    
    
 
	    
	$statement = $pdo->prepare("INSERT INTO `pickup_entry`(new_client_id,
	`client_id`,`courier_id`, `branch_id`, `cscs_awb`, `3pl_awb`, `ref_no`, `status`, `status_code`, `order_type`, `collectable_amount`,
	`business_mode`, `business_type`, `shipper_name`, `shipper_address`, `shipper_city`, `shipper_state`, `shipper_pincode`, `shipper_phone`, `shipper_mobile`, `shipper_country`,
	`consignee_name`, `consignee_address`, `consignee_city`, `consignee_state`, `consignee_pincode`, `consignee_phone`, `product_description`, `quantity`, `boxes`, `invoice_value`,
	`taxable_value`, `hsn_code`, `discount`, `gst_amount`, `mrp`, `ewaybill`, `rto_name`, `rto_address`, `rto_city`, `rto_state`, 
	`rto_pincode`, `rto_phone`, `a_weight`, `c_weight`, `gst_rate`, `buyer_gst`, `seller_gst`, `manifest_id`, `delete_status`, `date_added`, 
	`created_at`,`customer_id`, `pickup_name`, `pickup_address`, `pickup_pincode`, `pickup_city`, `pickup_state`, `pickup_phone`, `pickup_points_id`, `packaging_type`,
	`package_amount`, `cod_amount`, `product_to_be_shipped`, `fragile_shipment`, `shipment_type`, `master_id`, `mps_childres`, `mps_amount`, `seller_cst_no`, `seller_tin`,
	`invoice_no`, `invoice_date`, `commodity_value`, `tax_value`, `return_reason`,taxable_amount,document_number,document_type,document_date,seller_gst_amount,gst_cess_amount,integrated_gst_amount,consignee_gst_amount,order_id,pickup_points,o_ids,ewaybill_validity_date) VALUES (
		?,?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
		?,?,?,?,?,?,?,?)");

		$result1=$statement->execute(array(
		    $new_client_id,$client_id,0,$branch_id,$WAY_BILL,$WAY_BILL,$REFERENCE_NO,'pending',1,$PAYMENT_MODE,($PACKAGE_AMOUNT+$COD_AMOUNT),
		    $SHIPPING_MODE,'b2b',$SELLER_NAME,$SELLER_ADDRESS,$SELLER_CITY,$SELLER_STATE,$SELLER_PINCODE,$SELLER_PHONE,$SELLER_MOBILE,$SELLER_COUNTRY,
		    $CONSIGNEE_NAME,$ADDRESS,$CITY,$STATE,$PINCODE,$PHONE,$CATEGORY_OF_GOODS,$QUANTITY,$QUANTITY,($PACKAGE_AMOUNT+$COD_AMOUNT),
		    ($PACKAGE_AMOUNT+$COD_AMOUNT),$HSN_CODE,'','','',$EWBN,'',$RETURN_ADDRESS,'','',
		    $RETURN_PINCODE,'',$WEIGHT,$FC_WEIGHT,0,'',$SELLER_GST_TIN,'','0',$date,
		    $date,0,$VENDOR_PICKUP_LOCATION,$VENDOR_PICKUP_LOCATION_ADDRESS,$VENDOR_PICKUP_LOCATION_PINCODE,$VENDOR_PICKUP_LOCATION_CITY,$VENDOR_PICKUP_LOCATION_STATE,$VENDOR_PICKUP_LOCATION_PHONE,0,$PACKAGING_TYPE,
		    $PACKAGE_AMOUNT,$COD_AMOUNT,$PRODUCT_TO_BE_SHIPPED,$FRAGILE_SHIPMENT,$SHIPMENT_TYPE,'','','','','',
		    $INVOICE_NO,$INVOICE_DATE,$COMMODITY_VALUE,$TAX_VALUE,$RETURN_REASON,$TAXABLE_AMOUNT,$DOCUMENT_NUMBER,$DOCUMENT_TYPE,$DOCUMENT_DATE,$SELLER_GST_AMOUNT,$GST_CESS_AMOUNT,$INTEGRATED_GST_AMOUNT,$CONSIGNEE_GST_AMOUNT
		    ,$order_id,0,$o_ids,$EXPIRY_DATE));
	    $last_booking_id = $pdo->lastInsertId();;
	   
	    $statement = $pdo->prepare("INSERT INTO tbl_tracking (pickup_entry_id,user_id,location,status,status_code,description,remark,created_at) VALUES (?,?,?,?,?,?,?,?)");
		$result2=$statement->execute(array($last_booking_id,$client_id,'NA','pending','1','Shipment Softdata Created Successfully','Material Safe...',$date));
		
		
		$statement = $pdo->prepare("INSERT INTO `tbl_volumetrix_weight`(`pickup_id`, `length`, `width`, `height`, `no_of_box`, `actual_weight`, `charged_weight`, `fin_charges_weight`) VALUES (?,?,?,?,?,?,?,?)");
		$results = $statement->execute(array($last_booking_id,$SHIPMENT_LENGTH, $SHIPMENT_BREADTH, $SHIPMENT_HEIGHT ,1, $WEIGHT, $C_WEIGHT, $FC_WEIGHT));
		$dummy_a=$WEIGHT;
		$dummy_c=$C_WEIGHT;
		$dummy_box=1;
	}else{
	    
	    $C_WEIGHT=round($SHIPMENT_HEIGHT*$SHIPMENT_HEIGHT*$SHIPMENT_BREADTH/5000,2);
	    
	    $FC_WEIGHT=$WEIGHT;
	    if($WEIGHT<$C_WEIGHT){
	        $FC_WEIGHT=$C_WEIGHT;
	    }
	    
	    $statement = $pdo->prepare("INSERT INTO `tbl_volumetrix_weight`(`pickup_id`, `length`, `width`, `height`, `no_of_box`, `actual_weight`, `charged_weight`, `fin_charges_weight`) VALUES (?,?,?,?,?,?,?,?)");
		$results = $statement->execute(array($last_booking_id,$SHIPMENT_LENGTH, $SHIPMENT_BREADTH, $SHIPMENT_HEIGHT ,1, $WEIGHT, $C_WEIGHT, $FC_WEIGHT));
		
		$dummy_a +=$WEIGHT;
		$dummy_c +=$C_WEIGHT;
		$dummy_box +=1;
		
		$statement = $pdo->prepare("update pickup_entry set a_weight=?,c_weight=?,boxes=? where id=?");
		$result2=$statement->execute(array($dummy_a,$dummy_c,$dummy_box,$last_booking_id));
		
	} 
			}else{
			    $last_booking_id=0;$error_count++;
			    // Error Here
			    $table.='<tr><td>'.$error_count.'</td>
                            <td style="min-width: 300px;"><b style="color:red;">'.$error_msg.'</b></td>
                            <td>'.$result[$i]['COURIER_ID'].'</td>
                            <td>'.$result[$i]['WAY_BILL'].'</td>
                            <td>'.$result[$i]['EXPIRY_DATE'].'</td>
                            <td>'.$result[$i]['REFERENCE_NO'].'</td>
                            <td>'.$result[$i]['MASTER_ID'].'</td>
                            <td>'.$result[$i]['CONSIGNEE_NAME'].'</td>
                            <td>'.$result[$i]['CITY'].'</td>
                            <td>'.$result[$i]['STATE'].'</td>
                            <td>'.$result[$i]['COUNTRY'].'</td>
                            <td>'.$result[$i]['ADDRESS'].'</td>
                            <td>'.$result[$i]['PINCODE'].'</td>
                            <td>'.$result[$i]['PHONE'].'</td>
                            <td>'.$result[$i]['MOBILE'].'</td>
                            <td>'.$result[$i]['WEIGHT'].'</td>
                            <td>'.$result[$i]['SHIPMENT_LENGTH'].'</td>
                            <td>'.$result[$i]['SHIPMENT_BREADTH'].'</td>
                            <td>'.$result[$i]['SHIPMENT_HEIGHT'].'</td>
                            <td>'.$result[$i]['PACKAGING_TYPE'].'</td>
                            <td>'.$result[$i]['PAYMENT_MODE'].'</td>
                            <td>'.$result[$i]['PACKAGE_AMOUNT'].'</td>
                            <td>'.$result[$i]['COD_AMOUNT'].'</td>
                            <td>'.$result[$i]['PRODUCT_TO_BE_SHIPPED'].'</td>
                            <td>'.$result[$i]['VENDOR_PICKUP_LOCATION'].'</td>
                            <td>'.$result[$i]['RETURN_ADDRESS'].'</td>
                            <td>'.$result[$i]['RETURN_PINCODE'].'</td>
                            <td>'.$result[$i]['SHIPPING_MODE'].'</td>
                            <td>'.$result[$i]['FRAGILE_SHIPMENT'].'</td>
                            <td>'.$result[$i]['ALTERNATE_PHONE'].'</td>
                            <td>'.$result[$i]['SHIPMENT_TYPE'].'</td>
                            <td>'.$result[$i]['MPS_CHILDRES'].'</td>
                            <td>'.$result[$i]['MPS_AMOUNT'].'</td>
                            <td>'.$result[$i]['SELLER_NAME'].'</td>
                            <td>'.$result[$i]['SELLER_PINCODE'].'</td>
                            <td>'.$result[$i]['SELLER_ADDRESS'].'</td>
                            <td>'.$result[$i]['SELLER_CST_NO'].'</td>
                            <td>'.$result[$i]['SELLER_TIN'].'</td>
                            <td>'.$result[$i]['INVOICE_NO'].'</td>
                            <td>'.$result[$i]['INVOICE_DATE'].'</td>
                            <td>'.$result[$i]['QUANTITY'].'</td>
                            <td>'.$result[$i]['COMMODITY_VALUE'].'</td>
                            <td>'.$result[$i]['TAX_VALUE'].'</td>
                            <td>'.$result[$i]['CATEGORY_OF_GOODS'].'</td>
                            <td>'.$result[$i]['SELLER_GST_TIN'].'</td>
                            <td>'.$result[$i]['HSN_CODE'].'</td>
                            <td>'.$result[$i]['RETURN_REASON'].'</td>
                            <td>'.$result[$i]['EWBN'].'</td></tr>';
			}
        }
    $table.= "</tbody></table>
    <br><br><center><span id='export' class='btn btn-danger btn-sm'><i class='fa fa-download'></i> Download Failed Data</span></center></div></div></section>";
   
  	 $pdo->commit();  
    }catch(Exception $e){
        $pdo->rollBack();
        echo $e;
    }    
} 
?>
<section class="content">
    <div class="row">
		<div class="col-md-5" style="text-align: left;">
			<h4><i class="fa fa-upload"></i> Bulk Upload Report Status</h4>
		</div>
		<div class="col-md-7" style="text-align: right;">
		    <a href="shipment-create.php" class="btn btn-success btn-sm"><i class="fa fa-plus"></i> Create New Booking</a>
		    <a href="booking-list.php" class="btn btn-danger btn-sm"><i class="fa fa-arrow-left"></i> Back to Booking List</a>
		</div>
	</div>
	    <?php if($error_count){ ?>

                <?=$table?>
                
                
            <?php }else{ ?> 
<section class='content-header'>
    <div class='box-body' style='margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;'> 
            <center><b>All Data Bulk Upload Completed
            <br></b>
            <img src="img/success.gif" style="width: 250px;"><br>   
                
            <a href="shipment-create.php" class="btn btn-success btn-sm"><i class="fa fa-plus"></i> Create New Booking</a>
		    <a href="booking-list.php" class="btn btn-danger btn-sm"><i class="fa fa-arrow-left"></i> Back to Booking List</a></center>
    </div>
</section>
            <?php } ?>
	
</section>
<style>
    td,th{
        border:1px solid gray;
        padding:2px 5px;
    }
</style>


<?php require_once ('footer.php'); ?>


<script type="text/javascript">
$(document).ready(function () {
$('#export').click(function() {
  var titles = [];
  var data = [];

  /*
   * Get the table headers, this will be CSV headers
   * The count of headers will be CSV string separator
   */
  $('#error_table th').each(function() {
    titles.push($(this).text());
  });

  /*
   * Get the actual data, this will contain all the data, in 1 array
   */
  $('#error_table td').each(function() {
    data.push($(this).text());
  });
  
  /*
   * Convert our data to CSV string
   */
  var CSVString = prepCSVRow(titles, titles.length, '');
  CSVString = prepCSVRow(data, titles.length, CSVString);

  /*
   * Make CSV downloadable
   */
  var downloadLink = document.createElement("a");
  var blob = new Blob(["\ufeff", CSVString]);
  var url = URL.createObjectURL(blob);
  downloadLink.href = url;
  downloadLink.download = "data.csv";

  /*
   * Actually download CSV
   */
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
});

   /*
* Convert data array to CSV string
* @param arr {Array} - the actual data
* @param columnCount {Number} - the amount to split the data into columns
* @param initial {String} - initial string to append to CSV string
* return {String} - ready CSV string
*/
function prepCSVRow(arr, columnCount, initial) {
  var row = ''; // this will hold data
  var delimeter = ','; // data slice separator, in excel it's `;`, in usual CSv it's `,`
  var newLine = '\r\n'; // newline separator for CSV row

  /*
   * Convert [1,2,3,4] into [[1,2], [3,4]] while count is 2
   * @param _arr {Array} - the actual array to split
   * @param _count {Number} - the amount to split
   * return {Array} - splitted array
   */
  function splitArray(_arr, _count) {
    var splitted = [];
    var result = [];
    _arr.forEach(function(item, idx) {
      if ((idx + 1) % _count === 0) {
        splitted.push(item);
        result.push(splitted);
        splitted = [];
      } else {
        splitted.push(item);
      }
    });
    return result;
  }
  var plainArr = splitArray(arr, columnCount);
  // don't know how to explain this
  // you just have to like follow the code
  // and you understand, it's pretty simple
  // it converts `['a', 'b', 'c']` to `a,b,c` string
  plainArr.forEach(function(arrItem) {
    arrItem.forEach(function(item, idx) {
      row += item + ((idx + 1) === arrItem.length ? '' : delimeter);
    });
    row += newLine;
  });
  return initial + row;
}

});
	</script>