<?php

namespace App\Livewire\Wallets;

use App\Domain\Financial\Models\Wallet;
use App\Domain\Participant\Models\Participant;
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 WalletList extends Component
{
    use WithPagination, UsesBranchScope;

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

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

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

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

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

        $query = Wallet::query()
            ->with('owner')
            ->when($branchId, fn ($q) => $q->whereHasMorph('owner', [Participant::class], fn ($pq) => $pq->where('branch_id', $branchId)))
            ->when($this->search, function ($q) {
                $q->whereHasMorph('owner', [\App\Domain\Participant\Models\Participant::class], function ($pq) {
                    $pq->whereHas('person', function ($ppq) {
                        $ppq->where('name_ar', 'ilike', "%{$this->search}%")
                            ->orWhere('name', 'ilike', "%{$this->search}%");
                    });
                });
            })
            ->when($this->activeFilter !== '', function ($q) {
                $q->where('is_active', $this->activeFilter === '1');
            })
            ->orderByDesc('balance');

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