<?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\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();

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