<?php

namespace Modules\Inventory\Livewire\ItemCategories;

use Livewire\Component;
use Modules\Inventory\Entities\InventoryItemCategory;
use Modules\Inventory\Services\InventoryCacheService;
use Livewire\WithPagination;
use Jantinnerezo\LivewireAlert\LivewireAlert;

class ItemCategoryTable extends Component
{
    use WithPagination;
    use LivewireAlert;

    public $search;
    public $itemCategory;
    public $showEditItemCategoryModal = false;
    public $showDeleteItemCategoryModal = false;

    public function showEditItemCategory($id)
    {
        $this->itemCategory = InventoryItemCategory::find($id);
        $this->showEditItemCategoryModal = true;
    }

    public function showDeleteItemCategory($id)
    {
        $this->itemCategory = InventoryItemCategory::find($id);
        $this->showDeleteItemCategoryModal = true;
    }

    public function deleteItemCategory($id)
    {
        $itemCategory = InventoryItemCategory::find($id);
        $itemCategory->delete();
        $this->itemCategory = null;
        $this->alert('success', __('inventory::modules.itemCategory.itemCategoryDeleted'));
        $this->showDeleteItemCategoryModal = false;
    }

    public function render()
    {
        // Use cached categories and filter in memory (for small datasets)
        // For larger datasets, query would be better but cache helps
        $allCategories = InventoryCacheService::getCategoriesForBranch(branch()->id);
        
        if ($this->search) {
            $allCategories = $allCategories->filter(function ($category) {
                return stripos($category->name, $this->search) !== false;
            });
        }
        
        // Convert to paginated collection manually (simple approach)
        $currentPage = request()->get('page', 1);
        $perPage = 10;
        $offset = ($currentPage - 1) * $perPage;
        $paginatedItems = $allCategories->slice($offset, $perPage);
        
        $itemCategories = new \Illuminate\Pagination\LengthAwarePaginator(
            $paginatedItems,
            $allCategories->count(),
            $perPage,
            $currentPage,
            ['path' => request()->url(), 'query' => request()->query()]
        );

        return view('inventory::livewire.item-categories.item-category-table', compact('itemCategories'));
    }
}
