<?php

namespace Modules\Banner\Requests\Admin;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Validation\ValidationException;
use Modules\User\Enums\UserRoleEnum;

class BannerRequest extends FormRequest
{
    public function authorize()
    {
        $role = UserRoleEnum::admins();
        if (! Auth::check()) {
            return false;
        }
        if (! in_array(Auth::user()->role, $role)) {
            return false;
        }
        if (Auth::user()->hasModule('banners')) {
            return true;
        }
        return Auth::check();
    }

    public function rules()
    {
        $rules = [
            'image' => ($this->banner ? 'nullable' : 'required') . '|image|max:5120',
        ];

        foreach (languages() as $language) {
            $rules['title_' . $language->local] = ['required', 'regex:/^[\p{L}\p{N}\s]+$/u', 'max:60'];
            $rules['description_' . $language->local] = ['required', 'min:3','max:180' ];
        }

        return $rules;
    }

    public function attributes()
    {
        $attributes = [
            'image' => __('banners.image'),
        ];

        foreach (languages() as $language) {
            $attributes['title_' . $language->local] = __('banners.title') . ' ' . $language->local;
            $attributes['description_' . $language->local] = __('banners.description') . ' ' . $language->local;
        }

        return $attributes;
    }

    protected function failedValidation(Validator $validator)
    {
        if (Request::wantsJson()) {
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(response()->json(['errors' => $errors], 422));
        }

        parent::failedValidation($validator);
    }
}
