<?php

namespace App\Livewire\Parent;

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

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