<?php

namespace App\Livewire\Invoices;

use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\AppliesRoleScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('الفواتير')]
class InvoiceList extends Component
{
    use WithPagination, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'invoices.list';

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

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

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

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

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

        $query = Invoice::with(['billable.person'])
            ->when($branchId, fn ($q) => $q->whereHasMorph('billable', [Participant::class], fn ($pq) => $pq->where('branch_id', $branchId)))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('number', 'ilike', "%{$search}%")
                       ->orWhere('contact_name', 'ilike', "%{$search}%");
                });
            })
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->orderByDesc('created_at');

        $this->applyRoleScope($query);

        return view('livewire.invoices.invoice-list', [
            'invoices' => $query->paginate(20),
            'statusOptions' => collect(InvoiceStatus::cases())->mapWithKeys(
                fn (InvoiceStatus $s) => [$s->value => $s->label()]
            )->toArray(),
        ]);
    }
}
