<?php

namespace App\Classes\General\Eloquent\Filters;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;

class PackingListDeliveryStatus implements Filter
{

    /**
     * @param Builder $builder
     * @param $value
     * @return Builder|mixed
     */
    public static function apply(Builder $builder, $value)
    {
        return $value == 1 ? $builder->whereHas('containers', function ($query){
            $query->where('containers.status', ApprovalStatus::COMPLETED);
        })->whereDoesntHave('transports') : ($value == 2 ? $builder->whereHas('transports', function (Builder $query) use ($value) {
            $query->whereDoesntHave('schedules', function (Builder $query) use ($value) {
                $query->where('status', '!=', ApprovalStatus::EXPIRED)->where('eta', '<=',  Carbon::now());
            });
        }) : $builder->whereHas('transports', function (Builder $query) use ($value) {
            $query->whereHas('schedules', function (Builder $query) use ($value) {
                $query->where('status', '!=', ApprovalStatus::EXPIRED)->where('eta', '<=',  Carbon::now());
            });
        }));
    }
}
