<?php

namespace App\Livewire\Parent;

use App\Domain\Identity\Models\Guardian;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Enums\EvaluationStatus;
use App\Domain\Training\Models\Evaluation;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

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

    public string $activeTab = 'info';

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

        // Validate participant belongs to guardian
        $childrenIds = $this->getChildrenIds();

        if (! in_array($this->participant->id, $childrenIds)) {
            abort(403, __('ليس لديك صلاحية عرض هذا الملف'));
        }
    }

    public function setTab(string $tab): void
    {
        $this->activeTab = $tab;
    }

    public function render()
    {
        $this->participant->load(['person', 'branch', 'primaryActivity']);

        // Active enrollments with group and program
        $enrollments = $this->participant->activeEnrollments()
            ->with(['group', 'program'])
            ->get();

        // All enrollments (historical)
        $allEnrollments = $this->participant->enrollments()
            ->with(['group', 'program'])
            ->orderByDesc('enrollment_date')
            ->get();

        // Shared evaluations only
        $evaluations = Evaluation::where('participant_id', $this->participant->id)
            ->where('status', EvaluationStatus::Shared)
            ->with(['group', 'evaluator'])
            ->orderByDesc('evaluation_date')
            ->get();

        return view('livewire.parent.parent-child-detail', [
            'participant' => $this->participant,
            'enrollments' => $enrollments,
            'allEnrollments' => $allEnrollments,
            'evaluations' => $evaluations,
        ]);
    }

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