<?php

namespace Modules\{{ namespace }}\Requests\Admin;

use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class {{ className }}Request extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        if (!Auth::check()) {
            return false;
        }
        if (in_array(Auth::user()->role, ['super_admin', 'admin'])) {
            return true;
        }
        if (Auth::user()->hasModule('{{ kebabPluralModule }}')) {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     * @throws BindingResolutionException
     */
    public function rules(): array
    {
        $rules = [
            'image' => ($this->{{ singularModule }} && $this->{{ singularModule }}->image) ?
                config('general.validation_rules.image_update') :
                config('general.validation_rules.image_store'),
            'sort' => 'required|integer',
        ];

        foreach (languages() as $lang) {
            $lang_rules = [
                'title_' . $lang->local => 'required|string|min:2|max:200',
                'description_' . $lang->local => 'required|min:3',
            ];
            $rules = array_merge($rules, $lang_rules);
        }

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     * @throws BindingResolutionException
     */
    public function attributes(): array
    {
        $languages = languages();
        $field = metaFields('{{ kebabPluralModule }}');
        $local = app()->getLocale();

        $attributes = [
            'image' => $field[$local]['image'] ?? __('{{ pluralModuleLower }}::{{ pluralModuleSnake }}.image'),
            'sort' => $field[$local]['sort'] ?? __('{{ pluralModuleLower }}::{{ pluralModuleSnake }}.sort'),
        ];

        foreach ($languages as $lang) {
            $lngName = count($languages) > 1 ? " ($lang->name)" : "";
            $lang_attributes = [
                'title_' . $lang->local => ($field[$lang->local]['title'] ?? __('{{ pluralModuleLower }}::{{ pluralModuleSnake }}.title')) . $lngName,
                'description_' . $lang->local => ($field[$lang->local]['description'] ?? __('{{ pluralModuleLower }}::{{ pluralModuleSnake }}.description')) . $lngName,
            ];
            $attributes = array_merge($attributes, $lang_attributes);
        }

        return $attributes;
    }
}
