<?php

namespace Modules\DailyLog\Requests\Admin;

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\Category\Models\Category;
use Modules\ContactList\Enums\ContactStatusEnum;
use Modules\DailyLog\Enums\DailyLogActionEnum;
use Modules\DailyLog\Enums\DailyLogObjectiveEnum;
use Modules\DailyLog\Enums\DailyLogTypeEnum;
use Modules\DailyLog\Models\DailyLog;
use Modules\DailyLog\Services\DailyLogService;
use Modules\User\Enums\UserRoleEnum;

class DailyLogRequest extends FormRequest
{
    public function __construct(
        private DailyLogService $dailyLogService,
    ){}

    /**
     * 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('daily_logs'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $dailyLog = $this->dailyLogService->checkItem($this->route('daily_log') ?? 0 );
        if($dailyLog)
        {
            if($dailyLog->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $types = DailyLogTypeEnum::values();
        $objectives = DailyLogObjectiveEnum::values();
        $next_actions = DailyLogActionEnum::values();
        $statuses = ContactStatusEnum::values();
        $rules =
        [
            'employee_id' =>
            [
                'required',
                Rule::exists('users', 'id')->whereIn('role',UserRoleEnum::employees())->whereNull('deleted_at')
            ],
            'contact_list_id' =>
            [
                'required',
                Rule::exists('contact_lists', 'id')->whereNull('deleted_at')
            ],
            'date'=>
            [
                'required',
                'date'
            ],
            'type'=>
            [
                'required',
                'in:'.implode(',',$types),
            ],
            'objective'=>
            [
                'required',
                'in:'.implode(',',$objectives),
            ],
            'estimated_sale'=>
            [
                'nullable',
                'string',
                'max:250'
            ],
            'next_action'=>
            [
                'required',
                'in:'.implode(',',$next_actions),
            ],
            'next_contact'=>
            [
                'nullable',
                'date'
            ],
            'status'=>
            [
                'nullable',
                'in:'.implode(',',$statuses),
            ]
        ];
        if(request('objective') == DailyLogObjectiveEnum::OTHER->value)
        {
            $rules['objective_other'] = 
            [
                'required',
                'string',
                'max:255'
            ];
        }
        return $rules;
    }

    public function messages()
    {
        return [
            'locked.required'=>__('dashboard.locked'),
        ];
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes=
        [
            'start_price'=>__('categories.start_price'),
            'end_price'=>__('categories.end_price'),
            'employee_id'=>__('daily_logs.employee_id'),
            'contact_list_id'=>__('daily_logs.contact_list_id'),
            'date'=>__('daily_logs.date'),
            'type'=>__('daily_logs.type'),
            'objective'=>__('daily_logs.objective'),
            'estimated_sale'=>__('daily_logs.estimated_sale'),
            'next_action'=>__('daily_logs.next_action'),
            'next_contact'=>__('daily_logs.next_contact'),
            'status'=>__('daily_logs.status'),
            'objective_other'=>__('daily_logs.objective_other')
        ];

        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);
        }
    }
}
