<?php

namespace App\Livewire\Wallets;

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

    protected string $scopePermission = 'wallets.list';

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

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

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

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

        $this->applyRoleScope($query);

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