<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class MasterMenuRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $menuId = $this->route('menu')?->id;

        return [
            'id_stand' => [
                'required',
                'integer',
                Rule::exists('master_stand', 'id')->where(function ($query) {
                    $query->whereNull('deleted_at');
                }),
            ],
            'nama' => ['required', 'string', 'max:255'],
            'type_menu' => ['required', Rule::in(['makanan', 'minuman', 'snack'])],
            'harga_pokok' => ['nullable', 'numeric', 'min:0'],
            'harga_jual' => ['nullable', 'numeric', 'min:0'],
            'image' => ['nullable', 'image', 'max:2048'],
            'is_active' => ['sometimes', 'boolean'],
            'is_package' => ['sometimes', 'boolean'],
            'package_items' => ['nullable', 'array'],
            'package_items.*.id_menu' => [
                'nullable',
                'integer',
                Rule::notIn([$menuId]),
                Rule::exists('master_menu', 'id')->where(function ($query) {
                    $query->where('is_active', true)->whereNull('deleted_at');
                }),
            ],
            'package_items.*.qty' => ['nullable', 'integer', 'min:1'],
        ];
    }

    protected function prepareForValidation(): void
    {
        $rawItems = $this->input('package_items', []);
        if (! is_array($rawItems)) {
            $rawItems = [];
        }

        $packageItems = [];
        foreach ($rawItems as $row) {
            if (! is_array($row)) {
                continue;
            }

            $idMenu = $row['id_menu'] ?? null;
            $qty = $row['qty'] ?? null;
            if ($idMenu === null || $idMenu === '') {
                continue;
            }

            $packageItems[] = [
                'id_menu' => $idMenu,
                'qty' => $qty,
            ];
        }

        $this->merge([
            'is_active' => $this->boolean('is_active'),
            'is_package' => $this->boolean('is_package'),
            'package_items' => $packageItems,
        ]);
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if (! $this->boolean('is_package')) {
                return;
            }

            $items = collect($this->input('package_items', []));
            if ($items->isEmpty()) {
                $validator->errors()->add('package_items', 'Komponen paket wajib diisi minimal 1 item.');
                return;
            }

            foreach ($items as $index => $item) {
                if (blank($item['qty'] ?? null)) {
                    $validator->errors()->add("package_items.{$index}.qty", 'Qty komponen paket wajib diisi.');
                }
            }
        });
    }
}
