<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\Item;
use App\Modules\Inventory\Models\ItemCategory;
use App\Modules\Inventory\Repositories\ItemRepository;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ItemCatalogPageController extends Controller
{
    public function __construct(
        private readonly ItemRepository $items,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', Item::class);
        $categoryId = $request->integer('category_id') ?: null;
        if ($categoryId === 0) {
            $categoryId = null;
        }

        return view('pages.inventory.items.index', [
            'items' => $this->items->paginatedCatalog($categoryId),
            'categories' => ItemCategory::query()->orderBy('code')->get(['id', 'code', 'name']),
            'filterCategoryId' => $categoryId,
        ]);
    }

    public function show(Item $item): View
    {
        $this->authorize('view', $item);
        $detail = $this->items->findOperationalCatalog((int) $item->id);
        abort_if($detail === null, 404);

        return view('pages.inventory.items.show', [
            'item' => $detail,
        ]);
    }
}
