<?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\Component;

#[Layout('layouts.parent')]
#[Title('تفاصيل الفاتورة - بوابة ولي الأمر')]
class ParentInvoiceDetail extends Component
{
    public Invoice $invoice;

    public function mount(string $invoice): void
    {
        $this->invoice = Invoice::where('uuid', $invoice)->firstOrFail();

        // Validate the invoice belongs to one of guardian's children
        $childrenIds = $this->getChildrenIds();

        if (
            $this->invoice->billable_type !== Participant::class
            || ! in_array($this->invoice->billable_id, $childrenIds)
        ) {
            abort(403, __('ليس لديك صلاحية عرض هذه الفاتورة'));
        }
    }

    public function render()
    {
        $this->invoice->load(['items', 'payments', 'billable.person']);

        return view('livewire.parent.parent-invoice-detail', [
            'invoice' => $this->invoice,
        ]);
    }

    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();
    }
}
