<?php

namespace App\Livewire\Studio\Manage\StockOpname;

use App\Enums\StockOpnameStatus;
use App\Livewire\Forms\Studio\Manage\StockOpnameForm;
use App\Models\StockOpname;
use App\Models\StockOpnameItem;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithConfirmation;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Kelola Stock Opname')]
class Manage extends Component
{
    use WithAuthorization, WithConfirmation;

    public StockOpnameForm $form;

    public Collection $items;

    public function mount(StockOpname $stockOpname): void
    {
        if ($stockOpname->status !== StockOpnameStatus::PROCESS) {
            abort(403);
        }

        $this->items = StockOpnameItem::with('itemable')
            ->where('stock_opname_id', $stockOpname->id)
            ->get();

        $outletStock = [];
        foreach ($this->items as $item) {
            $outletStock[$item->id] = $item->qty_physical;
        }

        $this->form->outlet_stock = $outletStock;

        $this->form->setStockOpname($stockOpname);
    }

    public function updated(string $propertyName, $value): void
    {
        $this->canOrAbort('manage stock opname');

        $this->form->update();

        if (str_starts_with($propertyName, 'form.outlet_stock.')) {
            $itemId = explode('.', $propertyName)[2];

            $item = $this->items->firstWhere('id', $itemId);
            if ($item) {
                $item->qty_physical = $value;
                $item->difference = $value - $item->qty_system;
            }
        }
    }

    public function render(): View
    {
        return view('livewire.studio.manage.stock-opname.manage', [
            'pageTitle' => 'Kelola Stock Opname',
        ]);
    }
}
