<?php

namespace App\Modules\Payroll\Requests;

use App\Modules\Payroll\Repositories\PayrollPeriodRepository;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class StorePayrollPeriodRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('payroll.process') ?? false;
    }

    /**
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:191'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }
            $user = $this->user();
            if ($user === null || $user->tenant_id === null) {
                return;
            }
            $tid = (int) $user->tenant_id;
            $repo = app(PayrollPeriodRepository::class);
            if ($repo->hasOverlappingDates(
                $tid,
                (string) $this->input('start_date'),
                (string) $this->input('end_date'),
                null,
            )) {
                $validator->errors()->add('start_date', __('payroll.validation.overlap'));
            }
        });
    }
}
