<?php

namespace App\Service;
use DB;
use App\Service\cms\OrderService;
use App\Models\cms\ContainerDetail;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models\cms\PreArrivalDeparture;
use App\Models\cms\Order;
use App\Models\cms\ContainerOwner;
use App\Models\cms\LogisticProvider;
use App\Models\cms\Yard;
use App\Models\cms\Masters\ContainerType;


class ImportApprovalService
{

    // Import Containers for Approved

    public function importArrivalApproval($id){
        $today = new Carbon();

        // Update Approved
        $arrival=PreArrivalDeparture::where('id',$id)->first();
        $arrival['approved']=1;
        $arrival['status']=1;
        $arrival->update();

        $generateAidno=$this->generateRandomPID();
        
        if($arrival['container_detail_ids']!=null){
            foreach (explode(',',$arrival['container_detail_ids']) as $key => $value) {
                $orders=Order::create([
                    // 'date'=>$today->format('Y-m-d'),
                    'date'=>'2024-04-14',
                    'pid_no'=>$generateAidno
                ]);
                $orders['arrival_id']=$arrival['id'];
                $orders['order_id']='OID'.$orders['id'];
                $orders->update();

                $container=ContainerDetail::where('id',$value)->first();
                $container['order_id']=$orders['id'];
                $container['pid_no']=$generateAidno;
                $container->update();
            }
        
        }

        // dd($arrival);

        // Update the container type availability
        $orderservice=new OrderService;

        $container_details=ContainerDetail::whereIn('id',explode(',',$arrival['container_detail_ids']))->get();

        foreach ($container_details as $key => $details) {
            if($arrival['block_id']!=null){
                $orderservice->availableContainertype($arrival['block_id'],$details,1);
            }
        }

        return true;
    }

    private function generateRandomPID(){

        $unique = false;
    
        while (!$unique) {
            $random_string = 'AID'.rand(10000,99999);
            $count = Order::where('pid_no', $random_string)->count();
            if ($count == 0) {
                $unique = true;
            }
        }
    
        return $random_string;
    }
}