<?php

namespace App\Livewire\Parent;

use App\Domain\Financial\Models\Invoice;
use App\Domain\Identity\Models\Guardian;
use App\Domain\Identity\Services\GuardianResolver;
use App\Domain\Participant\Models\Participant;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.parent')]
#[Title('المالية - بوابة ولي الأمر')]
class ParentFinances extends Component
{
    use WithPagination;

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

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

    public function render()
    {
        $childrenIds = $this->getChildrenIds();

        // Outstanding balance summary
        $totalOutstanding = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $childrenIds)
            ->whereIn('status', ['sent', 'partially_paid', 'overdue'])
            ->sum('due_amount');

        $totalPaid = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $childrenIds)
            ->sum('paid_amount');

        $overdueCount = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $childrenIds)
            ->where('status', 'overdue')
            ->count();

        // Filtered invoice list
        $invoicesQuery = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $childrenIds)
            ->with('billable.person')
            ->orderByDesc('issue_date');

        if ($this->statusFilter !== '') {
            $invoicesQuery->where('status', $this->statusFilter);
        }

        $invoices = $invoicesQuery->paginate(15);

        return view('livewire.parent.parent-finances', [
            'invoices' => $invoices,
            'totalOutstanding' => $totalOutstanding,
            'totalPaid' => $totalPaid,
            'overdueCount' => $overdueCount,
        ]);
    }

    private function getGuardian(): Guardian
    {
        $user = auth()->user();

        // Display only. Authorisation and scoping go through GuardianResolver:
        // ->first() on a non-unique column meant a guardian holding two rows
        // saw one set of children and was 403'd on the rest, and an adult
        // member with no guardian row hard-failed on every screen here.
        return app(GuardianResolver::class)->guardiansFor($user)->first()
            ?? Guardian::where('user_id', $user->id)->firstOrFail();
    }

    private function getChildrenIds(): array
    {
        return app(GuardianResolver::class)->participantIdsFor(auth()->user());
    }
}
