<?php

namespace App\Livewire\Parent;

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

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