<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Models\Warehouse;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\WithSorting;
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, WithSorting;

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

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'name_ar';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'asc';
        }
    }

    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($this->sortBy, $this->sortDir);

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