<?php

namespace App\Livewire\Parent;

use App\Domain\Identity\Models\Guardian;
use App\Domain\Identity\Services\GuardianResolver;
use App\Domain\Participant\Models\Participant;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.parent')]
#[Title('الملف الشخصي - بوابة ولي الأمر')]
class ParentProfile extends Component
{
    public function logout(): void
    {
        Auth::logout();
        session()->invalidate();
        session()->regenerateToken();

        $this->redirect(route('login'));
    }

    public function render()
    {
        $user = auth()->user();
        $guardian = $this->getGuardian();
        $childrenIds = $this->getChildrenIds();

        $children = Participant::whereIn('id', $childrenIds)
            ->with(['person', 'activeEnrollments.group', 'activeEnrollments.program', 'branch'])
            ->get();

        $person = $guardian->person;

        return view('livewire.parent.parent-profile', [
            'guardian' => $guardian,
            'person' => $person,
            'children' => $children,
            'user' => $user,
        ]);
    }

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