<?php

namespace Modules\Canteen\Requests\Admin;

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

class CanteenRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $role = UserRoleEnum::admins();
        if (!Auth::check()) {
            return false;
        }
        if (!in_array(Auth::user()->role, $role)) {
            return false;
        }
        if (Auth::user()->hasModule('canteens')) {
            return true;
        }
        return Auth::check();
    }
    public function __construct(
        private UserService $userService
    ) {
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $user_id = null;
        if ($this->canteen) {
            $user_id = $this->userService->canteenUser($this->canteen)->id ?? null;
        }
        $notIn = null;
        if ($this->canteen) {
            $notIn = DB::table('canteens')
                ->where('id', '!=', $this->canteen) // Ignore the current record
                ->pluck('school_id')
                ->toArray();
        }
        if (!$this->canteen) {
            $notIn = DB::table('canteens')
                ->pluck('school_id')
                ->toArray();
        }
        $rules =
            [
                'school_id' =>
                    [
                        'required',
                        Rule::exists('schools', 'id')->whereNull('deleted_at'),
                        Rule::notIn($notIn),
                    ],
                // 'image'=>
                //     [
                //         'required'
                //     ],
                'account_name' =>
                    [
                        'required',
                        'string',
                        'max:100'
                    ],
                'account_number' =>
                    [
                        'required',
                        'string',
                        'max:100'
                    ],
                'bank_name' =>
                    [
                        'required',
                        'string',
                        'max:100'
                    ],
                'iban' =>
                    [
                        'required',
                        'string',
                        'max:100'
                    ],
                'id_number' =>
                    [
                        'required',
                        'string'
                    ],
                'email' =>
                    [
                        'required',
                        'email',
                        Rule::unique('users', 'email')->ignore($user_id)
                    ],
                'phone' =>
                    [
                        'required',
                        'numeric',
                        Rule::unique('users', 'phone')->ignore($user_id)
                    ],
                'password' =>
                    [
                        $this->canteen ? 'sometimes' : 'required',
                        'confirmed'
                    ],

            ];

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


        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes = [
            'id_number' => __('users.id_number'),
            'email' => __('users.email'),
            'image' => __('canteens.image'),
            'phone' => __('users.phone'),
            'password' => __('users.password'),
            'password_confirmation' => __('users.password_confirmation'),
            'school_id' => __('canteens.school_id'),
            'account_name' => __('canteens.account_name'),
            'account_number' => __('canteens.account_number'),
            'bank_name' => __('canteens.bank_name'),
            'iban' => __('canteens.iban'),

        ];
        foreach (languages() as $lang) {
            $lang_attributes = [
                'title_' . $lang->local => __('canteens.title') . ' ' . $lang->local,
            ];
            $attributes = array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param Validator $validator
     * @return void
     *
     * @throws ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        if (Request::wantsJson()) {
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(response()->json(['errors' => $errors], 422));
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
