<?php

namespace App\Livewire\Studio\Master\Warehouse;

use App\Models\Warehouse;
use App\Traits\Authorization\WithAuthorization;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Detail Gudang')]
class Show extends Component
{
    use WithAuthorization;

    public Warehouse $warehouse;

    public function mount(Warehouse $warehouse): void
    {
        $this->warehouse = $warehouse;
    }

    public function getStatsProperty()
    {
        $perfumesCount = $this->warehouse->perfumes()->count();
        $productsCount = $this->warehouse->products()->count();
        $bottlesCount = $this->warehouse->bottles()->count();
        $totalItems = $perfumesCount + $productsCount + $bottlesCount;

        return [
            [
                'title' => 'Total Item',
                'value' => number_format($totalItems, 0, ',', '.'),
            ],
            [
                'title' => 'Parfum',
                'value' => number_format($perfumesCount, 0, ',', '.'),
            ],
            [
                'title' => 'Produk',
                'value' => number_format($productsCount, 0, ',', '.'),
            ],
            [
                'title' => 'Botol',
                'value' => number_format($bottlesCount, 0, ',', '.'),
            ],
        ];
    }

    public function getItemsProperty()
    {
        $warehouse = $this->warehouse;

        $perfumes = $warehouse->perfumes()->get()->map(function ($item) {
            return [
                'id' => 'perfume_'.$item->id,
                'type' => 'Parfum',
                'name' => $item->name,
                'stock' => $item->pivot->stock ?? 0,
            ];
        });

        $products = $warehouse->products()->get()->map(function ($item) {
            return [
                'id' => 'product_'.$item->id,
                'type' => 'Produk',
                'name' => $item->name,
                'stock' => $item->pivot->stock ?? 0,
            ];
        });

        $bottles = $warehouse->bottles()->get()->map(function ($item) {
            return [
                'id' => 'bottle_'.$item->id,
                'type' => 'Botol',
                'name' => $item->name,
                'stock' => $item->pivot->stock ?? 0,
            ];
        });

        return $perfumes->concat($products)->concat($bottles);
    }

    public function render(): View
    {
        return view('livewire.studio.master.warehouse.show', [
            'pageTitle' => 'Detail Gudang',
            'stats' => $this->stats,
        ]);
    }
}
