<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\ApiErrorCodes;

final class EvaluationController extends ApiController
{
    public function criteria(Request $request, int $groupId): Response
    {
        $coach = App::getInstance()->currentCoach();
        $db = App::getInstance()->db();

        $group = $db->selectOne(
            "SELECT tg.*, sd.id as discipline_id, sd.name_ar as discipline_name
             FROM training_groups tg
             JOIN academy_levels al ON al.id = tg.level_id
             JOIN academies a ON a.id = tg.academy_id
             LEFT JOIN sport_disciplines sd ON sd.id = a.discipline_id
             WHERE tg.id = ? AND tg.coach_id = ?",
            [$groupId, (int) $coach->id]
        );

        if (!$group) {
            return $this->errorResponse('المجموعة غير موجودة أو لا تخصك', 404, [], ApiErrorCodes::NOT_FOUND);
        }

        $criteria = [];
        if ($group['discipline_id']) {
            $criteria = $db->select(
                "SELECT id, name_ar, name_en, category, max_score, weight
                 FROM evaluation_criteria
                 WHERE discipline_id = ?
                 ORDER BY category, id",
                [(int) $group['discipline_id']]
            );
        }

        return $this->successResponse([
            'group' => [
                'id' => (int) $group['id'],
                'name_ar' => $group['name_ar'],
                'discipline_name' => $group['discipline_name'],
            ],
            'criteria' => $criteria,
        ]);
    }

    public function store(Request $request): Response
    {
        $coach = App::getInstance()->currentCoach();
        $db = App::getInstance()->db();
        $input = $request->jsonBody();

        $playerId = (int) ($input['player_id'] ?? 0);
        $disciplineId = (int) ($input['discipline_id'] ?? 0);
        $scoresJson = $input['scores'] ?? [];
        $overallScore = $input['overall_score'] ?? null;
        $skillLevel = $input['skill_level'] ?? null;
        $strengthsAr = $input['strengths_ar'] ?? null;
        $weaknessesAr = $input['weaknesses_ar'] ?? null;
        $coachNotes = $input['coach_notes'] ?? null;

        if ($playerId <= 0 || $disciplineId <= 0 || empty($scoresJson)) {
            return $this->errorResponse('بيانات التقييم غير مكتملة', 422, [], ApiErrorCodes::VALIDATION_FAILED);
        }

        $player = $db->selectOne("SELECT id FROM players WHERE id = ? AND is_archived = 0", [$playerId]);
        if (!$player) {
            return $this->errorResponse('اللاعب غير موجود', 404, [], ApiErrorCodes::NOT_FOUND);
        }

        $db->insert('player_evaluations', [
            'player_id' => $playerId,
            'discipline_id' => $disciplineId,
            'evaluator_coach_id' => (int) $coach->id,
            'evaluation_date' => date('Y-m-d'),
            'overall_score' => $overallScore,
            'skill_level' => $skillLevel,
            'scores_json' => json_encode($scoresJson, JSON_UNESCAPED_UNICODE),
            'strengths_ar' => $strengthsAr,
            'weaknesses_ar' => $weaknessesAr,
            'coach_notes' => $coachNotes,
            'parent_visible' => 1,
            'status' => 'submitted',
            'created_by' => (int) $coach->id,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        return $this->successResponse(['submitted' => true], 201);
    }

    public function index(Request $request): Response
    {
        $coach = App::getInstance()->currentCoach();
        $db = App::getInstance()->db();

        $page = max(1, (int) ($request->get('page') ?? 1));
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM player_evaluations WHERE evaluator_coach_id = ?",
            [(int) $coach->id]
        )['cnt'] ?? 0);

        $evaluations = $db->select(
            "SELECT pe.id, pe.evaluation_date, pe.overall_score, pe.skill_level, pe.status,
                    p.full_name_ar as player_name, sd.name_ar as discipline_name
             FROM player_evaluations pe
             JOIN players p ON p.id = pe.player_id
             LEFT JOIN sport_disciplines sd ON sd.id = pe.discipline_id
             WHERE pe.evaluator_coach_id = ?
             ORDER BY pe.evaluation_date DESC
             LIMIT ? OFFSET ?",
            [(int) $coach->id, $perPage, $offset]
        );

        return $this->paginatedResponse($evaluations, $total, $page, $perPage);
    }
}
