<?php

namespace App\Livewire\Portal;

use App\Domain\Financial\Models\Installment;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Models\Payment;
use App\Domain\Financial\Models\Wallet;
use App\Domain\Participant\Models\Participant;
use App\Livewire\Portal\Concerns\PortalScreen;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Money, and money is family-scoped.
 *
 * Three sections, not three screens: عليك (what is owed — invoices and
 * instalments), السجل (what has been paid), المحفظة (the balance held). The
 * old portal had ParentFinances quietly ignoring the child switcher and
 * aggregating every child, which is the domain saying that a household has one
 * balance even when it has three players.
 */
#[Layout('layouts.portal')]
#[Title('المدفوعات')]
class PortalPayments extends Component
{
    use PortalScreen, WithPagination;

    /** due | history | wallet */
    #[Url(as: 'tab')]
    public string $tab = 'due';

    public function mount(): void
    {
        $this->authorizePortal();
    }

    public function updatedTab(): void
    {
        if (! in_array($this->tab, ['due', 'history', 'wallet'], true)) {
            $this->tab = 'due';
        }

        $this->resetPage();
    }

    public function render()
    {
        $familyIds = $this->familyParticipantIds();

        $outstanding = Invoice::whereIn('billable_id', $familyIds)
            ->where('billable_type', Participant::class)
            ->whereIn('status', ['sent', 'partially_paid', 'overdue'])
            ->with('items')
            ->orderBy('due_date');

        $history = Payment::whereIn('payer_id', $familyIds)
            ->where('payer_type', Participant::class)
            ->where('direction', 'inbound')
            ->with('invoice')
            ->orderByDesc('payment_date')
            ->orderByDesc('id');

        return view('livewire.portal.portal-payments', [
            'totalDue' => (int) Invoice::whereIn('billable_id', $familyIds)
                ->where('billable_type', Participant::class)
                ->whereIn('status', ['sent', 'partially_paid', 'overdue'])
                ->sum('due_amount'),
            'invoices' => $this->tab === 'due' ? $outstanding->paginate(10) : collect(),
            'payments' => $this->tab === 'history' ? $history->paginate(10) : collect(),
            'installments' => $this->tab === 'due'
                ? Installment::whereHas('paymentPlan.invoice', function ($q) use ($familyIds) {
                    $q->whereIn('billable_id', $familyIds)->where('billable_type', Participant::class);
                })
                    ->whereIn('status', ['pending', 'overdue'])
                    ->with('paymentPlan.invoice')
                    ->orderBy('due_date')
                    ->get()
                : collect(),
            'wallets' => $this->tab === 'wallet'
                ? Wallet::where('owner_type', Participant::class)
                    ->whereIn('owner_id', $familyIds)
                    ->with('owner.person')
                    ->get()
                : collect(),
            // can_authorize_payment has existed since 2024 with zero readers,
            // so every guardian has had full financial access to every linked
            // child. The portal is where that column finally gates something.
            'payableIds' => $this->portal()->payableParticipantIds(),
        ]);
    }
}
