<?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()
    {
        // No hand-written branch clause: BranchScope already narrows this to
        // the branch's own stores, and a second one here would only be a copy
        // that drifts.
        $query = Warehouse::query()
            ->with(['branch', 'inventoryLevels'])
            ->withCount('inventoryLevels')
            ->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),
        ]);
    }
}
