<?php

namespace App\Http\Requests;

use App\Helpers\CheckOverSelling;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;

class TransferRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'details'       => 'nullable',
            'attachments'   => 'nullable',
            'draft'         => 'nullable|boolean',
            'attachments.*' => 'mimes:' . env('ATTACHMENT_EXTS', 'jpg,png,pdf,docx,xlsx,zip'),

            'date'              => 'required|date',
            'from_warehouse_id' => 'required|exists:warehouses,id',
            'to_warehouse_id'   => 'required|exists:warehouses,id|different:from_warehouse_id',
            'reference'         => 'nullable|max:50|unique:transfers,reference,' . optional($this->route('transfer'))->id,

            'items'                    => 'required|array|min:1',
            'items.*.id'               => 'nullable',
            'items.*.transfer_item_id' => 'nullable',
            'items.*.has_serials'      => 'nullable',
            'items.*.has_variants'     => 'nullable',
            'items.*.quantity'         => 'required|numeric',
            'items.*.old_quantity'     => 'nullable|numeric',
            'items.*.item_id'          => 'required|exists:items,id',
            'items.*.unit_id'          => 'nullable|exists:units,id',
            'items.*.selected'         => 'nullable|array|required_if:items.*.has_variants,1',
            'items.*.weight'           => 'nullable|numeric|required_if:items.*.track_weight,1',
        ];
    }

    public function withValidator($validator)
    {
        $validator->setImplicitAttributesFormatter(function ($attribute) {
            $attributes = explode('.', $attribute);
            if ('items' == $attributes[0]) {
                if ($attributes[2]) {
                    return __('Item') . ' ' . ((int) $attributes[1] + 1) . ' ' . __($attributes[2]) . ' ' . (isset($attributes[3]) ? ((int) $attributes[3] + 1) : '');
                }
                return __('Item') . ' ' . ((int) $attributes[1] + 1);
            } elseif ('attachments' == $attributes[0]) {
                return 'attachments ' . ((int) $attributes[1] + 1);
            }
            return $attributes;
        });
    }

    protected function passedValidation()
    {
        if (!$this->input('draft') && !get_settings('over_selling')) {
            $error = (new CheckOverSelling())->check($this->input('items'), $this->input('from_warehouse_id'));
            if ($error) {
                throw ValidationException::withMessages($error);
            }
        }
    }
}
