<?php

namespace App\Service\cms;
use DB;
use App\Models\cms\Order;
use Carbon\Carbon;
use App\Models\cms\Block;
use App\Models\cms\PreArrivalDeparture;
use App\Models\cms\ContainerDetail;

class OrderService{

    public function updateOrder($request,$id){

        $order=Order::where('id',$id)->first();

        return $order;
    }

    public function availableSpaceBlock($blockid){

        $block=Block::findorfail($blockid);

        $orders=Order::where('status',0)->with('arrival')
            ->whereHas('arrival',function($query) use ($blockid){
                $query->where('block_id',$blockid)->where('approved',1);
            })
            ->get();

        $occupiedsize=0;

        foreach ($orders as $key => $value) {

            $container_details=ContainerDetail::where('order_id',$value['id'])->with('container_types')->get();

            foreach ($container_details as $key => $data) {
                
                if($data['container_types']['type_size']){
                    $occupiedsize +=$data->container_types->type_size / 40;
                }
                
            }
           
        }
        
        $block['available_space']=$block['capacity'] - $occupiedsize;

        $block->update();

        return $block;
        
    }

    public function availableContainertype($blockid,$details,$operator){

        $block=Block::findorfail($blockid);
        
        if(json_decode($block['container_types'])){

            $containers_types=[];
            foreach (json_decode($block['container_types']) as $key => $value) {

                if($value->container_type==$details['container_type']){
                    $data=[
                        'id'=>$value->id,
                        'container_type'=>$value->container_type,
                        'capacity'=>$value->capacity,
                        'stored_containers'=>$value->stored_containers - $operator
                    ];
                } else {
                    $data=[
                        'id'=>$key+1,
                        'container_type'=>$value->container_type,
                        'capacity'=>$value->capacity,
                        'stored_containers'=>$value->stored_containers
                    ];
                }
                if(isset($value)){
                    array_push($containers_types, $data);
                }
            }
            $block['container_types']=$containers_types;

            $block->update();
        }

        return true;
    }
}