<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Models\Evaluation;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EvaluationController extends Controller
{
    public function index(string $participantUuid, Request $request): JsonResponse
    {
        $participant = $this->findAuthorized($participantUuid, $request->user());

        $evaluations = Evaluation::where('participant_id', $participant->id)
            ->where('status', 'shared')
            ->with(['evaluator:id,name_ar,name', 'group:id,name_ar,name', 'group.program:id,name_ar,name'])
            ->orderByDesc('evaluation_date')
            ->paginate(10);

        return response()->json([
            'data' => $evaluations->map(fn ($eval) => [
                'uuid' => $eval->uuid,
                'evaluation_date' => $eval->evaluation_date?->toDateString(),
                'period_from' => $eval->period_from?->toDateString(),
                'period_to' => $eval->period_to?->toDateString(),
                'overall_score' => (float) $eval->overall_score,
                'overall_notes' => $eval->overall_notes,
                'evaluator_name' => $eval->evaluator?->name_ar ?? $eval->evaluator?->name,
                'group_name' => $eval->group?->name_ar ?? $eval->group?->name,
                'program_name' => $eval->group?->program?->name_ar ?? $eval->group?->program?->name,
                'shared_at' => $eval->shared_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $evaluations->currentPage(),
                'last_page' => $evaluations->lastPage(),
                'per_page' => $evaluations->perPage(),
                'total' => $evaluations->total(),
            ],
        ]);
    }

    public function show(string $participantUuid, string $evaluationUuid, Request $request): JsonResponse
    {
        $participant = $this->findAuthorized($participantUuid, $request->user());

        $evaluation = Evaluation::where('uuid', $evaluationUuid)
            ->where('participant_id', $participant->id)
            ->where('status', 'shared')
            ->with([
                'evaluator:id,name_ar,name',
                'group:id,name_ar,name',
                'group.program:id,name_ar,name',
                'scores.criterion',
            ])
            ->firstOrFail();

        $maxPossible = $evaluation->scores->sum(fn ($s) => $s->criterion?->max_score ?? 0);
        $actualTotal = $evaluation->scores->sum('score');

        return response()->json([
            'data' => [
                'uuid' => $evaluation->uuid,
                'evaluation_date' => $evaluation->evaluation_date?->toDateString(),
                'period_from' => $evaluation->period_from?->toDateString(),
                'period_to' => $evaluation->period_to?->toDateString(),
                'overall_score' => (float) $evaluation->overall_score,
                'overall_notes' => $evaluation->overall_notes,
                'evaluator_name' => $evaluation->evaluator?->name_ar ?? $evaluation->evaluator?->name,
                'group_name' => $evaluation->group?->name_ar ?? $evaluation->group?->name,
                'program_name' => $evaluation->group?->program?->name_ar ?? $evaluation->group?->program?->name,
                'shared_at' => $evaluation->shared_at?->toIso8601String(),
                'score_summary' => [
                    'total_score' => (float) $actualTotal,
                    'max_possible' => (float) $maxPossible,
                    'percentage' => $maxPossible > 0 ? round($actualTotal / $maxPossible * 100, 1) : 0,
                ],
                'scores' => $evaluation->scores->map(fn ($score) => [
                    'criterion_name' => $score->criterion?->name_ar ?? $score->criterion?->name,
                    'category' => $score->criterion?->category,
                    'score' => (float) $score->score,
                    'max_score' => $score->criterion?->max_score ?? 0,
                    'percentage' => ($score->criterion?->max_score ?? 0) > 0
                        ? round($score->score / $score->criterion->max_score * 100, 1)
                        : 0,
                    'notes' => $score->notes,
                ]),
            ],
        ]);
    }

    private function findAuthorized(string $uuid, $user): Participant
    {
        $participant = Participant::where('uuid', $uuid)->firstOrFail();
        $personId = $user->person_id;

        if (!$personId) {
            abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
        }

        if ($participant->person_id === $personId) {
            return $participant;
        }

        $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
        if ($guardian && $guardian->participants()->where('participants.id', $participant->id)->exists()) {
            return $participant;
        }

        abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
    }
}
