<?php

namespace App\Livewire\Parent;

use App\Domain\Financial\Models\Invoice;
use App\Domain\Identity\Models\Guardian;
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();

        return Guardian::where('person_id', $user->person_id)->first()
            ?? Guardian::where('user_id', $user->id)->firstOrFail();
    }

    private function getChildrenIds(): array
    {
        return $this->getGuardian()->participants()->pluck('participants.id')->toArray();
    }
}
