<?php


namespace Modules\ChipOrder\Requests\Api;



use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class ChipOrderRequest extends FormRequest
{
    public function authorize()
    {
        return auth()->check() && auth()->user()->role == 4;
    }

    public function rules()
    {
        return [
            'address_id' => 'required|exists:addresses,id',
            'products' => 'required|array|min:1',
            'products.*.chip_id' => 'required|exists:chips,id',
            'products.*.count' => 'required|integer|min:1',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'address_id' => __('orders.address_id'),
            'products' => __('orders.products'),
            'products.*.chip_id' => __('orders.product_id'),
            'products.*.count' => __('orders.count')
        ];
    }

    /**
     * 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)
    {
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message' => $message, 'errors' => $errors], 400));
    }
}
