<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Models\Warehouse;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المستودعات')]
class WarehouseList extends Component
{
    use WithPagination, UsesBranchScope;

    #[Url]
    public string $search = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $query = Warehouse::query()
            ->with(['branch', 'inventoryLevels'])
            ->withCount('inventoryLevels')
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('name_ar', 'ilike', "%{$search}%")
                       ->orWhere('code', 'ilike', "%{$search}%");
                });
            })
            ->orderBy('name_ar');

        return view('livewire.inventory.warehouse-list', [
            'warehouses' => $query->paginate(20),
        ]);
    }
}
