<?php

namespace App\Livewire\Evaluations;

use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Training\Models\Evaluation;
use App\Domain\Training\Services\EvaluationService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('عرض التقييم')]
class EvaluationShow extends Component
{
    public Evaluation $evaluation;

    public function mount(Evaluation $evaluation): void
    {
        $this->authorize('evaluations.list');
        $this->evaluation = $evaluation->load(['participant.person', 'group', 'evaluator', 'approver', 'scores.criterion']);
    }

    public function approve(EvaluationService $service): void
    {
        try {
            $this->authorize('evaluations.approve');
            $service->approve($this->evaluation, auth()->user());
            $this->evaluation = $this->evaluation->fresh(['participant.person', 'group', 'evaluator', 'approver', 'scores.criterion']);
            session()->flash('success', __('تم اعتماد التقييم بنجاح'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function share(EvaluationService $service): void
    {
        try {
            $this->authorize('evaluations.share');
            $service->share($this->evaluation);
            $this->evaluation = $this->evaluation->fresh(['participant.person', 'group', 'evaluator', 'approver', 'scores.criterion']);
            session()->flash('success', __('تم مشاركة التقييم مع ولي الأمر'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.evaluations.evaluation-show');
    }
}
