<?php

namespace App\Classes\General\Eloquent\Filters;

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

class IsNotFullyRefunded implements Filter
{

    /**
     * @param Builder $builder
     * @param $value
     * @return Builder|mixed
     */
    public static function apply(Builder $builder, $value)
    {
        return $builder->withSum(['transactions as total_refund_amount' => function($q) {
            $q->refunds()->where('status', ApprovalStatus::APPROVED);
        }], 'original_amount')
        ->having('total_refund_amount', '<', DB::raw('original_amount'));
    }
}
