<?php

namespace App\Livewire\Parent;

use App\Domain\Identity\Models\Guardian;
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 ParentEvaluationDetail extends Component
{
    public Evaluation $evaluation;

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

        // Validate: evaluation belongs to guardian's child AND status = 'shared'
        $childrenIds = $this->getChildrenIds();

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

        if ($this->evaluation->status !== EvaluationStatus::Shared) {
            abort(403, __('هذا التقييم غير متاح للعرض'));
        }
    }

    public function render()
    {
        $this->evaluation->load([
            'scores.criterion',
            'participant.person',
            'group',
            'evaluator',
        ]);

        return view('livewire.parent.parent-evaluation-detail', [
            'evaluation' => $this->evaluation,
        ]);
    }

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