<?php

namespace Modules\Team\Requests\Admin;

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

class TeamRequest 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('teams')) {
            return true;
        }
        return Auth::check();
    }

    public function rules()
    {
        $rules = [
            'image' => [
                request()->isMethod('POST') ? 'required' : 'nullable',
                'image',
                'mimes:jpeg,png,jpg,gif,svg',
                'max:2048'
            ],
        ];

        foreach (languages() as $lang) {
            $lang_rules = [
                'name_' . $lang->local => 'required|max:100',
                'job_' . $lang->local => 'required|max:100',
            ];
            $rules = array_merge($rules, $lang_rules);
        }

        return $rules;
    }

    public function attributes()
    {
        $attributes = [];
        foreach (languages() as $lang) {
            $attributes = array_merge($attributes, [
                'name_' . $lang->local => __('teams.name') . ' ' . $lang->local,
                'job_' . $lang->local => __('teams.job') . ' ' . $lang->local,
            ]);
        }
        return $attributes;
    }

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

