<?php

namespace App\Rules\Movement;

use App\Models\Approval;
use App\Models\Movement;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class MaxQty implements ValidationRule
{
    protected $approval_id;

    public function __construct($approval_id)
    {
        $this->approval_id = $approval_id;
    }
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $approval = Approval::with('movements')->first();
        $currentSum = $approval->movements->sum('qty');
        $remainder = $approval->qty - $currentSum;

        if ($value > $remainder) {
            $fail(__("الحقل :attribute يجب ان لا يكون اكبر من القيمة المتبقية لحركات هذه الموافقة ($remainder)."));
        }
    }
}
