<?php 
ob_start();
session_start();
include "../inc/config.php";
include "../inc/session.php";


if(isset($_POST['type']) && $_POST['type']=='scanning_status_update_api'){
    try{
        $pdo->beginTransaction(); 
        
    $from_branch=$_POST['from_branch'] ?? 0;    
        
    $unique_id = "1000";
    $statement = $pdo->prepare("SHOW TABLE STATUS WHERE `name` = 'manifest'");
    $statement->execute();
    $memeber_id_result = $statement->fetchAll(PDO::FETCH_ASSOC); 
    foreach ($memeber_id_result as $result) {
        $unique_id = $unique_id + $result['Auto_increment'];
    }
    $FromBranch ='';
    $prefix='';
    $statement = $pdo->prepare("SELECT * FROM tbl_branch where id=$from_branch");
    $statement->execute();
    $branch_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    if($branch_data){
        $prefix=$branch_data[0]['prefix_for_manifest'];
        $FromBranch=$branch_data[0]['name'];
        $state_code=$branch_data[0]['state_code'];
    }
    
    
    $manifest_id = $prefix.$unique_id;
    
    
    
        $updated_ids = implode(',', $_POST['updated_ids']);
        
        //$updated_box_ids = implode(',', $_POST['updated_awb_box']);
        
        
        
        $update_status=$_POST['update_status'];
        $update_status_name=$_POST['update_status_name'];
        $status_location=$_POST['status_location'];
        $status_location_name=$_POST['status_location_name'];
        
        $to_branch_name=$_POST['to_branch_name'];
        
        $status_description = $_POST['status_description']." ".$to_branch_name;
        $status_date = $_POST['status_date'];
        
        
        
        $to_branch=$_POST['to_branch'];
        $coloader=$_POST['coloader'];
        $vehicle_no=$_POST['vehicle_no'];
        $driver_name = $_POST['driver_name'];
        $driver_mobile=$_POST['driver_mobile'];
        $remark=$_POST['remark'];
        $reason=$_POST['reason']?? 2;
        // $state_code=$_POST['state_code'];
        
        $count = count($_POST['updated_ids']);
        

        $statement1 = $pdo->prepare("INSERT INTO manifest (`manifest_id`, `origin`, `destination`, `entry_date`, `no_of_entry`, 
                                    `coloader_id`, `vehicle_no`, `driver_name`, `driver_mobile_no`, manifest_type, ids) 
                                    VALUES (?,?,?,?,?,
                                    ?,?,?,?,?,?)");
        $result= $statement1->execute(array($manifest_id, $from_branch, $to_branch, $status_date, $count, 
                                        $coloader, $vehicle_no, $driver_name, $driver_mobile, 2, $updated_ids));
        
        error_log("INSERT INTO manifest (`manifest_id`, `origin`, `destination`, `entry_date`, `no_of_entry`, 
                                    `coloader_id`, `vehicle_no`, `driver_name`, `driver_mobile_no`, manifest_type, ids) 
                                    VALUES ($manifest_id, $from_branch, $to_branch, $status_date, $count, 
                                        $coloader, $vehicle_no, $driver_name, $driver_mobile, 2, $updated_ids)");
        
        $manifest_id = $pdo->lastInsertId();
        
  
        /*$s="UPDATE pickup_entry SET status='$update_status',last_updated_status_date='$status_date',delivered_date='$status_date' WHERE id in ($updated_ids)";*/
    
        
        $updated_idsarray = explode(',', $updated_ids);
        $success_ids =[];
        $failure_ids =[];
        $failure_reasons =[];
       
       foreach($_POST['updated_ids'] as $ids){  
           
           
           error_log('forloop ids  :'.$ids);
                /*eway starts*/
        
        $statement = $pdo->prepare("SELECT * FROM pickup_entry  where id=$ids");
        $statement->execute();
        $ewaybill_data = $statement->fetch(PDO::FETCH_ASSOC);  
           
       if($ewaybill_data && $ewaybill_data['ewaybill'] ==''){
           

$statement1 = $pdo->prepare("
    INSERT INTO tbl_tracking (
        pickup_entry_id, user_id, location, location_id, status, status_code, 
        description, remark, receiver_name, receiver_mobile, relation, reason, 
        delivery_date, created_at
    ) 
    VALUES (
        :pickup_entry_id, :user_id, :location, :location_id, :status, :status_code, 
        :description, :remark, :receiver_name, :receiver_mobile, :relation, :reason, 
        :delivery_date, :created_at
    )
");

        $statement1->execute([
            ':pickup_entry_id'   => $ids,
            ':user_id'           => $session_id,
            ':location'          => $status_location_name,
            ':location_id'       => $status_location,
            ':status'            => $update_status_name,
            ':status_code'       => $update_status,
            ':description'       => $status_description,
            ':remark'            => '', // Assuming no value
            ':receiver_name'     => '', // Assuming no value
            ':receiver_mobile'   => '', // Assuming no value
            ':relation'          => '', // Assuming no value
            ':reason'            => '', // Assuming no value
            ':delivery_date'     => $status_date,
            ':created_at'        => $status_date
        ]);
       $result= $statement1->execute();
        $statement1 = $pdo->prepare("UPDATE pickup_entry SET status_code='$update_status',status='$update_status_name',last_updated_status_date='$status_date',delivered_date='$status_date' WHERE id = $ids");
        $statement1->execute();
        
       }
       
       
       
        
        if($ewaybill_data && $ewaybill_data['ewaybill'] !='' ){
            // Declare values as local variables
            $new_date = date('d/m/Y', strtotime($status_date));
            $ewbNo = $ewaybill_data['ewaybill'] ;
            $vehicleNo = $vehicle_no;
            $fromPlace = $FromBranch;
            $fromState = $state_code;
            $reasonCode = $reason;
            $reasonRem = $remark;
            $transMode = '1';
            $transDocNo = $manifest_id;
            $transDocDate = $new_date;
            $url = $baseUrl . "/ewaybillapi/v1.03/ewayapi/vehewb?email=" . urlencode($authemail) ;
            
            
            
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
            //   CURLOPT_URL => $url,
             CURLOPT_URL => $url,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'POST',
              CURLOPT_POSTFIELDS =>'{
                "ewbNo": '.$ewbNo.',
                "vehicleNo": "'.$vehicleNo.'",
                "fromPlace": "'.$fromPlace.'",
                "fromState": '.$fromState.',
                "reasonCode": "'.$reason.'",
                "reasonRem": "'.$reasonCode.'",
                "transMode": "1"
            }',
     CURLOPT_HTTPHEADER => array(
                "ip_address: $authip_address",
                "client_id: $authclient_id",
                "client_secret: $authclient_secret",
                "gstin: $authgstin",
                'Content-Type: application/json',
                'Accept: application/json'
  ),
));
      
            $response = curl_exec($curl);
            
            // Close cURL
            curl_close($curl);
            error_log(json_encode($response.'stephen not working'));
            $response_data = json_decode($response, true);
            if ($response_data['status_cd'] == '1') {
                 $success_ids[] = $ids;
                    $vehUpdDate = $response_data['data']['vehUpdDate'] ?? null;
                    $statusDesc = $response_data['status_desc'] ?? 'No Description';
                 
                  try {
                      $stmt = $pdo->prepare("
                          INSERT INTO vehicle_update_details 
                          (pid, vehicle_update_date, valid_upto_date, status_description, created_at, updated_at)
                          VALUES (:pid, :vehicle_update_date, :valid_upto_date, :status_description, NOW(), NOW())
                      ");
                      $stmt->execute([
                          ':pid' => $ewbNo,
                          ':vehicle_update_date' => $vehUpdDate,
                          ':valid_upto_date' => $vehUpdDate,
                          ':status_description' => $statusDesc
                      ]);
                  } catch (Exception $e) {
                      $failure_ids[] = $ewbNo;
                      $errors[] = "Eway Bill No: $ewbNo DB Insert failed: " . $e->getMessage();
                  }
                 /*insert status ends*/
                 
                  $statement1 = $pdo->prepare("INSERT INTO tbl_tracking (pickup_entry_id,user_id,location,location_id,status,status_code,description,remark,receiver_name,receiver_mobile,relation,reason,delivery_date,created_at) 
                        	                 VALUES ($ids,$session_id,'$status_location_name','$status_location','$update_status_name',$update_status,'$status_description','','','','','','$status_date','$status_date')");
                  $result= $statement1->execute();
                  $statement1 = $pdo->prepare("UPDATE pickup_entry SET status_code='$update_status',status='$update_status_name',last_updated_status_date='$status_date',delivered_date='$status_date' WHERE id = $ids");
                  $statement1->execute();
        
            }else{
                $failure_ids[] = $ids;
                
                
                
                
                
                /*starts*/
                    $msg = json_decode($response_data['error']['message'], true);
                   if (isset($msg['errorCodes'])) {
                    // Trim any extra spaces and commas
                    $codes = trim($msg['errorCodes'], ", ");
                    
                    // Convert the comma-separated string to an array
                    $codeArray = explode(",", $codes);
                
                    $Err = [];
                
                    foreach ($codeArray as $code) {
                        $code = trim($code); 
                        $stmt = $pdo->prepare("SELECT * FROM api_error WHERE errorCode = :code");
                        $stmt->execute(['code' => $code]);
                        $ErrData = $stmt->fetch(PDO::FETCH_ASSOC);
                        if ($ErrData && isset($ErrData['errorDesc'])) {
                            $Err[] = $ErrData['errorDesc'];
                        }
                    }
                    $errordetails = implode(", ", $Err);
                }
                /*ends*/
                
                $failure_reasons[]="Eway Bill No :" .$ewaybill_data['ewaybill']." , AWB No :".$ewaybill_data['cscs_awb'].":". $errordetails. "\n";
                
            }
            
        }
        
        /*eway ends*/
       }
        
        
      
                
        /*Remove Pickup Entry ids*/
        $final_updatedids = array_diff($updated_idsarray, $failure_ids);
        $comma_separated = implode(',', $final_updatedids);
        $counts = count($final_updatedids);
        $error_log=json_encode($failure_reasons);
        
        $statement1 = $pdo->prepare("UPDATE manifest SET ids='$comma_separated',no_of_entry= $counts,error_log='$error_log' WHERE id = $manifest_id");
        $statement1->execute();
        
        
        $pdo->commit();
        $responses['error']=false;
        $responses['meassge']='Status Updated Successfully: ';
        $responses['failure_data']=$failure_reasons;
        $responses['manifest_id']=$manifest_id;
    }catch(exception $e){
        $pdo->rollBack();
        $responses['error']=true;
        $responses['meassge']="Something Went Wrong";
        error_log($e);
    }
    print_r(json_encode($responses));
}
?>