<?php

namespace Modules\Order\Requests\Api\Order;

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\Services\CartService;
use Modules\Product\Services\ProductService;
use Modules\Product\Services\ProductWarehouseService;
use Modules\User\Services\AccountService;

class CreateRequest extends FormRequest
{
    public function __construct(
        private ProductService $productService,
        private CartService $cartService,
        private AccountService $accountService,
        private ProductWarehouseService $productWarehouseService,
    ){}

    /**
     * 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()
    {
        $account = $this->accountService->getAccount();
        $products = $this->cartService->get([
            'user_status'=>$account['status'],
            'user_id'=>$account['user']->id
        ]);
        $rules =
            [
                'payment_way_id'=>
                [
                    'required',
                    Rule::exists('payment_ways','id')->whereNull('deleted_at')
                ]
            ];
        if (count($products) == 0)
        {
            return ['cart_empty'=>'required'];
        }
        // if (is_null($account['user']->name))
        // {
        //     return [
        //         'fill_profile'=>'required'
        //     ];
        // }
        if (is_null($account['user']->address->address))
        {
            return [
                'fill_address'=>'required'
            ];
        }
        foreach ($products as $row)
        {
            $stock = $this->productService->productWarehouse([
                'product_id'=>$row->product_id,
                'warehouse_id'=>$row->warehouse_id,
                'option_id'=>$row->option_id,
            ]);
            if (!$stock)
            {
                return['over'=>'required'];
            }
            if ($row->count > $stock->count)
            {
                return['over'=>'required'];
            }
        }
        return $rules;
    }

    public function messages()
    {
        return [
            'over_count.required' => __('web.over_count'),
            'product_over.required' => __('web.product_over'),
            'product_empty.required' => __('web.product_empty'),
        ];
    }

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

        $attributes= [
            'cart_empty'=>__('web.cart_empty'),
            'payment_way_id'=>__('web.payment_way_id'),
            'fill_profile'=>__('web.fill_profile'),
            'fill_address'=>__('web.fill_address')
        ];
        $account = $this->accountService->getAccount();
        $products = $this->cartService->get([
            'user_status'=>$account['status'],
            'user_id'=>$account['user']->id
        ]);
        foreach ($products as $row)
        {
            $stock = $this->productService->productWarehouse([
                'product_id'=>$row->product_id,
                'warehouse_id'=>$row->warehouse_id,
                'option_id'=>$row->option_id,
            ]);
            if (!$stock)
            {
                $attributes['over'] = __('web.empty_product'). ' : '.$row->product->currentDescription->title ;
            }
            if ($row->count > $stock->count)
            {
                $attributes['over'] = __('web.product_over_count'). ' : '.$row->product->currentDescription->title ;
            }

        }
        return $attributes;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests

        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));

    }
}
