<?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']);
  
        $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, 0, $updated_ids));
        
        $inserted_manifest_id = $pdo->lastInsertId();
        
        $updated_idsarray = explode(',', $updated_ids);
        $success_ids =[];
        $failure_ids =[];
        $report_data = [];
       
       foreach($_POST['updated_ids'] as $ids){  
        
        $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'] ==''){
           
           $awb_no = $ewaybill_data['awb_no'];

$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();
        
        $report_data[] = ['awb' => $awb_no, 'status' => 'Success', 'reason' => ''];
       } else {
        $statement = $pdo->prepare("SELECT awb_no FROM pickup_entry  where id=$ids");
        $statement->execute();
        $awb_data = $statement->fetch(PDO::FETCH_ASSOC);
        $awb_no = $awb_data ? $awb_data['awb_no'] : 'Unknown';
        $reason = 'E-way bill is not empty or AWB not found';
        if($ewaybill_data && $ewaybill_data['ewaybill'] !=''){
            $reason = 'E-way bill is not empty';
        }
        
        $report_data[] = ['awb' => $awb_no, 'status' => 'Failure', 'reason' => $reason];
       }
       
}
        $pdo->commit();
        $responses['error']=false;
        $responses['meassge']='Status Updated Successfully: ';
        $responses['failure_data']=$failure_reasons;
        $responses['manifest_id']=$inserted_manifest_id;
        $responses['report_data'] = $report_data;
    }catch(exception $e){
        $pdo->rollBack();
        $responses['error']=true;
        $responses['meassge']="Something Went Wrong";
    }
    print_r(json_encode($responses));
}
?>