<?php

namespace App\Http\Requests;

use Illuminate\Validation\Rule;
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;

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

        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()

    {
        $local = getCurrentLocale();
        $rules=[
            'name_'.$local=> 'required|min:3|max:100',
            'is_offer' => 'nullable|in:1,0',
        ];
        if (request('update_hall_flag')){
            $rules['images'] = 'nullable|array';
        } else {
            $rules['images'] = 'required|array';
        }
        $rules['reservation_way'] = 'required|in:direct,accept_request';
        $rules['category_id'] = 'required|exists:categories,id';
        $rules['occasions'] = 'required|array|exists:occasions,id';
        $rules['capacity'] = 'required|numeric|min:1';
        $rules['total_capacity'] = 'required|numeric|min:1';
        $rules['min_capacity'] = 'required|numeric|min:1';
        $rules['reservation_type'] = 'required|in:person_count,days_count';
        $rules['booking_amount_per_person'] = 'required_if:reservation_type,person_count|nullable|gt:0';
        $rules['booking_amount_per_day'] = 'required_if:reservation_type,days_count|nullable|gt:0';
        $rules['region_id'] = 'required|exists:regions,id';
        $rules['city_id'] = 'required|exists:cities,id';
        $rules['sector_id'] = 'required|exists:sectors,id';
        $rules['street'] = 'required|min:3|max:200';

        $rules['added_services_name'] = 'required|array';
        foreach (request('added_services_name') as $name) {
            if (!$name){
                $rules['all_added_services_name'] = 'required';
            }
        }

        $rules['added_services_price'] = 'required|array';
        foreach (request('added_services_price') as $price) {
            if ($price <= 0){
                $rules['all_added_services_price'] = 'required|numeric|gt:0';
            }

        }

        $rules['added_services_description'] = 'required|array';
        foreach (request('added_services_description') as $desc) {
            if (!$desc){
                $rules['all_added_services_description'] = 'required';
            }
        }

        if (request('update_hall_flag')){
            $rules['added_services_image'] = 'nullable|array';

        } else {
            $rules['added_services_image'] = 'required|array';
        }

        foreach (request('old_added_services_image') as $image) {
            if (!$image){
                $rules['all_added_services_image'] = 'required';
            }
        }

//        dd(request()->all());


        if (request('available_dates_from')){
            foreach (request('available_dates_from') as $from) {
                if (!$from){
                    $rules['all_available_dates_from'] = 'required';
                }
            }
        }

        if (request('available_dates_to')){
            foreach (request('available_dates_to') as $key => $to) {
                if (!$to){
                    $rules['all_available_dates_to'] = 'required';
                }
                if (strtotime($to) < strtotime(request('available_dates_from')[$key])){
                    $rules['all_available_dates_to'] = 'required|after:available_dates_from';
                }
            }
        }

        if (request('discount_percentage')){
            foreach (request('discount_percentage') as $percentage) {
                if (empty($percentage)){
                    $rules['all_discount_percentage'] = 'required|numeric|min:1|not_in:0|gt:0';
                }
                if ($percentage != 'empty' && $percentage <= 0){
                    $rules['all_discount_percentage'] = 'required|numeric|min:1|not_in:0|gt:0';
                }
            }
        }

        $rules['description_'.$local] = 'required|min:3|max:400';


//        dd(request()->all());
        return $rules;
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $field = metaFields('halls');
        $local = getCurrentLocale();
        $attributes=[
            'user_id' => $field[$local]['user_id'] ?? __('halls.user_id'),
            'category_id' => $field[$local]['category_id'] ?? __('halls.category_id'),
            'occasions' => $field[$local]['occasions'] ?? __('halls.occasions'),
            'added_services_name' => $field[$local]['added_services_name'] ?? __('halls.added_services_name'),
            'added_services_description' => $field[$local]['added_services_description'] ?? __('halls.added_services_description'),
            'added_services_price' => $field[$local]['added_services_price'] ?? __('halls.added_services_price'),
            'added_services_image' => $field[$local]['added_services_image'] ?? __('halls.added_services_image'),
            'capacity' => $field[$local]['capacity'] ?? __('halls.capacity'),
            'total_capacity' => $field[$local]['total_capacity'] ?? __('halls.total_capacity'),
            'min_capacity' => $field[$local]['min_capacity'] ?? __('halls.min_capacity'),
            'reservation_way' => $field[$local]['reservation_way'] ?? __('halls.reservation_way'),
            'reservation_type' => $field[$local]['reservation_type'] ?? __('halls.reservation_type'),
            'region_id' => $field[$local]['region_id'] ?? __('halls.region_id'),
            'city_id' => $field[$local]['city_id'] ?? __('halls.city_id'),
            'sector_id' => $field[$local]['sector_id'] ?? __('halls.sector_id'),
            'street' => $field[$local]['street'] ?? __('halls.street'),
            'images' => $field[$local]['images'] ?? __('halls.images'),
            'booking_amount_per_person' => $field[$local]['booking_amount_per_person'] ?? __('halls.booking_amount_per_person'),
            'all_added_services_name' => $field[$local]['added_services_name'] ?? __('halls.added_services_name'),
            'all_available_dates_from' => $field[$local]['available_dates_from'] ?? __('halls.available_dates_from'),
            'all_available_dates_to' =>  __('halls.all_available_dates_to'),
            'all_added_services_price' => $field[$local]['added_services_price'] ?? __('halls.all_added_services_price'),
            'all_added_services_description' => $field[$local]['added_services_description'] ?? __('halls.added_services_description'),
            'all_added_services_image' => $field[$local]['added_services_image'] ?? __('halls.added_services_image'),
            'all_reserved_date' => $field[$local]['reserved_date'] ?? __('halls.reserved_date'),
            'all_discount_percentage' => $field[$local]['discount_percentage'] ?? __('halls.discount_percentage'),
            'is_offer' => $field[$local]['is_offer'] ?? __('halls.is_offer'),

        ];

        foreach (languages() as $lang) {
            $lang_attributes=[
                'name_'.$lang->local=> $field[$lang->local]['name'] ?? __('halls.name'),
                'description_'.$lang->local=> $field[$lang->local]['description'] ?? __('halls.description'),
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }

    public function messages()
    {
        return [
            'all_discount_percentage.required' => __('halls.all_discount_percentage_required'),
            'booking_amount_per_person.required_if' => __('halls.booking_amount_per_person_required_if'),
            'booking_amount_per_person.gt' => __('halls.booking_amount_per_person_required_if'),
            'booking_amount_per_day.required_if' => __('halls.booking_amount_per_day_required_if'),
            'booking_amount_per_day.gt' => __('halls.booking_amount_per_day_required_if'),
            'all_added_services_price.gt' => __('halls.all_added_services_price_gt'),
            'all_added_services_price.numeric' => __('halls.all_added_services_price_gt'),

        ];
    }
    /**
     * 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::ajax()){
            $errors = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['errors' => $errors]));
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
