<?php

namespace App\Http\Requests\PurchaseMaker;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {

        return [
            'list.*.product' => 'required',
            'list.*.quantity' => 'required|numeric',
            'list.*.carton_box' => 'nullable|numeric',
            // 'list.*.price' => 'required|numeric',
            // 'list.*.total' => 'required|numeric',

        ];
    }

    protected function prepareForValidation(): void
    {
        $list = $this->input('list', []);

        foreach ($list as $index => $item) {
            if (array_key_exists('carton_box', $item) && $item['carton_box'] === '') {
                $list[$index]['carton_box'] = null;
            }
        }

        $this->merge(['list' => $list]);
    }

    public function failedValidation($validator)
    {
        $errors = $validator->errors();

        throw new HttpResponseException(response()->json(['errors' => $errors], 422));
    }
}
