<?php

namespace App\Http\Requests\Admin\Finance;

use App\Traits\NotificationTrait;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class PayrollRequest extends FormRequest
{
    use NotificationTrait;

    public function authorize(): bool
    {
        return Auth::check();
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'amount' => removeRupiahFormatting($this->amount),
            'incentive' => removeRupiahFormatting($this->incentive),
            'cut' => removeRupiahFormatting($this->cut),
            'shaving_result' => removeRupiahFormatting($this->shaving_result),
            'total' => removeRupiahFormatting($this->total),
        ]);
    }

    public function rules(): array
    {
        $rules = [
            'amount' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
            'incentive' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
            'cut' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
            'total' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
            'shaving_result' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
            'percentage_shaving' => ['required', 'numeric', 'min:0', 'max:100'],
            'description' => ['required', 'string', 'max:65535'],
        ];

        if (! $this->isMethod('put')) {
            $rules['employee'] = ['required', Rule::exists('users', 'id')];
        }

        return $rules;
    }

    protected function failedValidation(Validator $validator): void
    {
        $this->handleValidationFailure($validator);
    }
}
