<?php

namespace App\Http\Requests;

use App\Models\PermanentEmployeeAdvance;
use App\Models\PermanentEmployeeSalaryPayment;
use App\Support\NumberFormat;
use Illuminate\Foundation\Http\FormRequest;

class UpdatePermanentEmployeeSalaryPaymentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user()?->can('permanent-salaries.manage');
    }

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'allowance' => ['required', 'numeric', 'min:0'],
            'salary_increment' => ['required', 'numeric', 'min:0'],
            'advance_deduction' => ['required', 'numeric', 'min:0'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }

            /** @var PermanentEmployeeSalaryPayment $payment */
            $payment = $this->route('salaryPayment');

            if (! $payment->isDraft()) {
                $validator->errors()->add(
                    'allowance',
                    __('Only draft salary records can be edited.'),
                );

                return;
            }

            $outstanding = PermanentEmployeeAdvance::outstandingBalance(
                $payment->permanent_employee_id,
                $payment->id,
            );

            if ((float) $this->input('advance_deduction') > $outstanding) {
                $validator->errors()->add(
                    'advance_deduction',
                    __('Advance deduction cannot exceed the outstanding advance balance of :amount.', [
                        'amount' => NumberFormat::money($outstanding),
                    ]),
                );
            }
        });
    }
}
