<?php

namespace Modules\SpecialAttendance\Http\Requests;

use App\Helpers\CoreApp\Traits\ApiReturnFormatTrait;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class DeductionAppealRequest extends FormRequest
{
    use ApiReturnFormatTrait;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'appeal_details' => 'required|string|max:2000',
            'attachment' => 'nullable|file|mimes:jpg,png,pdf,doc,docx|max:2048',
        ];
    }

    public function messages()
    {
        return [
            'appeal_details.required' => _trans('validation.Deduction Appeal is Required'),
            'appeal_details.max' => _trans('validation.Deduction Appeal must not exceed 2000 characters'),
            'attachment.mimes' => _trans('validation.Invalid file type. Only jpg, png, pdf, doc, and docx are allowed'),
            'attachment.max' => _trans('validation.File size must not exceed 2MB'),
        ];
    }

    /**
     * Check if the request is coming from an API.
     *
     * @return bool
     */
    protected function isApiRequest()
    {
        return $this->expectsJson();
    }

    /**
     * Handle a failed validation attempt.
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        if ($this->isApiRequest()) {
            throw new HttpResponseException(
                $this->responseWithError(
                    _trans('response.Validation Error'),
                    $validator->errors()->all(),
                    422
                )
            );
        }

        parent::failedValidation($validator); // For web requests, use the standard behavior
    }
}
