<?php

namespace App\Classes\General\Eloquent\Filters;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\PackingList;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class PackingListLimitOneByTypeOrderedByInvoiceDate implements Filter
{

    /**
     * @param Builder $builder
     * @param $value
     * @return Builder|mixed
     */
    public static function apply(Builder $builder, $value)
    {
        return $builder->select('packing_lists.*')->join('transactions', function($join){
            $join->on('transactions.owner_id', '=', 'packing_lists.id');
            $join->where('transactions.owner_type', '=', PackingList::class);
            $join->where('transactions.status', '=', ApprovalStatus::APPROVED);
            $join->whereRaw('(transactions.type <> 16 OR transactions.id = (
                SELECT id FROM transactions WHERE owner_id = packing_lists.id AND type = 16 LIMIT 1
            ))');
        })->orderBy('transactions.updated_at', 'DESC');
    }

}
