<?php

namespace Modules\Order\Requests\Web;

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\Order\Enums\OrderStatusEnum;

class OrderRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $request = request();
        $statuses = OrderStatusEnum::values();
        $rules =
        [
            'name'=>
            [
                'required',
                'string',
                'min:3',
                'max:150'
            ],
            'email'=>
            [
                'required',
                'email',
                'max:150'
            ],
            'phone'=>
            [
                'required',
                'numeric',
                'digits:9',
                'regex:/^5/'
            ],
            'status'=>
            [
                'required',
                'in:'.implode(',',$statuses)
            ],
            'count_hours'=>
            [
                'required',
                'numeric',
                'max:24'
            ],
            'reservation_date'=>
            [
                'required',
                'date',
                'after_or_equal:'.date('Y-m-d')
            ],
            'reservation_time'=>
            [
                'required',
                'date_format:H:i'
            ],
            'note'=>
            [
                'nullable',
                'string',
                'max:500'
            ],
            'photo_usage'=>
            [
                'required',
                'bool'
            ],
            'additions.*.attribute_id'=>
            [
                'nullable',
                Rule::exists('attributes','id')->whereNull('deleted_at')
            ],
            'additions.*.count' => [
                function ($attribute, $value, $fail) use ($request) {
                    // Extract index from "additions.X.count"
                    $index = explode('.', $attribute)[1];

                    // Check if attribute_id exists in the same array item
                    if (isset($request->additions[$index]['attribute_id']) && empty($value)) {
                        $fail(__('web.count_is_required_attribute'));
                    }

                    // Ensure count is an integer when provided
                    if (!empty($value) && !is_numeric($value)) {
                        $fail(__('web.is_numeric'));
                    }

                    // Ensure count is at least 1 when provided
                    if (!empty($value) && $value < 1) {
                        $fail(__('web.count_min_1'));
                    }
                }
            ],
        ];

//        if (request('additions'))
//        {
//            foreach (request('additions') as $addition)
//            {
//                if(count($addition) == 2)
//                {
//                    if()
//                    {
//                        $rules['additions.*.attribute_id'] =
//                        [
//                            'required',
//                            Rule::exists('attributes','id')->whereNull('deleted_at')
//                        ];
//                    }
//                    $rules['additions.*.count'] =
//                    [
//                        'required',
//                        'numeric',
//                        'min:1'
//                    ];
//                }
//            }
//        }

        if (request('status') == OrderStatusEnum::PACKAGE->value)
        {
            $rules['package_ids'] =
            [
                'required',
                'array',
                Rule::exists('packages','id')->whereNull('deleted_at')
            ];
        }
        elseif (request('status') == OrderStatusEnum::SERVICE->value)
        {
            $rules['service_ids'] =
            [
                'required',
                'array',
                Rule::exists('services','id')->whereNull('deleted_at')
            ];
        }

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes =
        [
            'name'=>__('web.name'),
            'email'=>__('web.email'),
            'phone'=>__('web.phone'),
            'status'=>__('web.reservation_status'),
            'count_hours'=>__('web.count_hours'),
            'reservation_date'=>__('web.reservation_date'),
            'reservation_time'=>__('web.reservation_time'),
            'note'=>__('web.note'),
            'photo_usage'=>__('web.photo_usage'),
            'attribute_ids'=>__('web.attribute_ids'),
            'package_ids'=>__('web.package_ids'),
            'service_ids'=>__('web.service_ids'),
        ];

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