<?php

namespace App\Livewire\Parent;

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

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