<?php

namespace Modules\Travel\Http\Requests;

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

class TravelExpenseRequest extends FormRequest
{
    use ApiReturnFormatTrait;
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'date'                        => 'required|date',
            'mode_of_transportation'      => 'nullable|in:' . implode(',', ModeOfTransportationEnum::toArray()),
            'expense_category_id'         => 'required|array',
            'expense_category_id.*'       => 'required|integer',
            'title'                       => 'required|array',
            'title.*'                     => 'nullable|string|min:0|max:255',
            'amount'                      => 'required|array',
            'amount.*'                    => 'nullable|numeric|min:0',
            'remark'                      => 'nullable|array',
            'remark.*'                    => 'nullable|string|max:255',
            'rating_of_travel_experience' => 'nullable|integer|between:1,5',
        ];

        // Add the travel_plan_id validation for API requests only
        if ($this->isApiRequest()) {
            $rules['travel_plan_id'] = 'required|integer';
            $rules['file_id']   = 'nullable|array';
            $rules['file_id.*'] = 'nullable';
        } else {
            $rules['file']   = 'nullable|array';
            $rules['file.*'] = 'nullable|file|mimes:jpg,jpeg,png,pdf,doc,docx';
        }

        return $rules;
    }


    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Custom messages for validation errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'travel_plan_id.required'             => _trans('response.The travel plan field is required.'),
            'travel_plan_id.integer'              => _trans('response.The travel plan ID must be a valid number.'),
            'expense_category_id.required'        => _trans('response.The expense category field is required.'),
            'expense_category_id.*.required'      => _trans('response.Each expense category field is required.'),
            'expense_category_id.*.integer'       => _trans('response.Each expense category must be a valid number.'),
            'date.required'                       => _trans('response.The date is required.'),
            'date.date'                           => _trans('response.Please provide a valid date.'),
            'mode_of_transportation.required'     => _trans('response.Mode of transportation is required.'),
            'mode_of_transportation.in'           => _trans('response.Selected mode of transportation is invalid.'),
            'amount.required'                     => _trans('response.The amount field is required.'),
            'amount.*.numeric'                    => _trans('response.Each amount must be a valid number.'),
            'amount.*.min'                        => _trans('response.Amount cannot be negative.'),
            'file.*.file'                         => _trans('response.Please upload a valid file.'),
            'file.*.mimes'                        => _trans('response.Supported file types are jpg, jpeg, png, pdf, doc, docx.'),
            'remark.*.string'                     => _trans('response.Remark must be a string.'),
            'rating_of_travel_experience.between' => _trans('response.Rating must be between 1 and 5.'),
        ];
               
    }


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

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @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
    }
}
