<?php

namespace App\Livewire\Forms\Studio\Manage;

use App\Models\StockOpname;
use App\Models\StockOpnameItem;
use App\Rules\UnsignedInteger;
use Livewire\Form;

class StockOpnameForm extends Form
{
    public StockOpname $stockOpname;

    public array $outlet_stock = [];

    public ?string $note = null;

    public function rules(): array
    {
        return [
            'outlet_stock' => 'array',
            'outlet_stock.*' => ['nullable', new UnsignedInteger],
            'note' => 'nullable',
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'outlet_stock' => 'stock outlet',
            'outlet_stock.*' => 'stock outlet',
            'note' => 'catatan',
        ];
    }

    public function setStockOpname(StockOpname $stockOpname): void
    {
        $stockOpname->load('items');

        $this->stockOpname = $stockOpname;

        $this->note = $stockOpname->note;
    }

    public function update(): void
    {
        $this->validate();

        $this->stockOpname->update(['note' => $this->note]);

        foreach ($this->outlet_stock as $itemId => $qtyPhysical) {
            $item = StockOpnameItem::find($itemId);
            if (! $item) {
                continue;
            }

            $item->qty_physical = $qtyPhysical;
            $item->save();
        }
    }
}
