<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Services\CoachAssessmentService;

class CoachAssessmentController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $coachDisciplineIds = $this->getCoachDisciplineIds();
        $filterDiscipline = (int) $request->get('discipline_id', 0);

        $disciplines = $db->select(
            "SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar"
        );

        $players = CoachAssessmentService::getPendingPlayers($coachDisciplineIds, $filterDiscipline ?: null);

        return $this->view('SportsActivity.Views.assessment.index', [
            'players'          => $players,
            'disciplines'      => $disciplines,
            'coachDisciplines' => $coachDisciplineIds,
            'filterDiscipline' => $filterDiscipline,
        ]);
    }

    public function assess(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $registrationId = (int) $id;

        $registration = $db->selectOne(
            "SELECT r.*, p.full_name_ar, p.full_name_en, p.national_id as player_nid,
                    p.date_of_birth, p.gender, p.phone, p.photo_path, p.player_type as p_type,
                    p.medical_status, r.selected_disciplines
             FROM sa_registrations r
             INNER JOIN sa_players p ON p.id = r.player_id
             WHERE r.id = ?",
            [$registrationId]
        );

        if (!$registration) {
            return $this->redirect('/sa/coach-assessment')->withError('التسجيل غير موجود');
        }

        $selectedDisciplineIds = [];
        if (!empty($registration['selected_disciplines'])) {
            $decoded = json_decode($registration['selected_disciplines'], true);
            if (is_array($decoded)) {
                foreach ($decoded as $d) {
                    $selectedDisciplineIds[] = is_array($d) ? (int) ($d['id'] ?? 0) : (int) $d;
                }
            }
        }

        $coachDisciplineIds = $this->getCoachDisciplineIds();
        $relevantDisciplineIds = !empty($coachDisciplineIds)
            ? array_intersect($selectedDisciplineIds, $coachDisciplineIds)
            : $selectedDisciplineIds;

        if (empty($relevantDisciplineIds)) {
            $relevantDisciplineIds = $selectedDisciplineIds;
        }

        $groups = CoachAssessmentService::getAvailableGroups($relevantDisciplineIds);

        $db2 = App::getInstance()->db();
        $programs = [];
        if (!empty($relevantDisciplineIds)) {
            $ph = implode(',', array_fill(0, count($relevantDisciplineIds), '?'));
            $programs = $db2->select(
                "SELECT p.id, p.code, p.name_ar, p.monthly_fee_member, p.monthly_fee_nonmember,
                        p.session_duration_minutes, p.sessions_per_week, p.max_capacity,
                        d.id as discipline_id, d.name_ar as discipline_name
                 FROM sa_programs p
                 LEFT JOIN sa_disciplines d ON d.id = p.discipline_id
                 WHERE p.discipline_id IN ({$ph}) AND p.is_active = 1 AND p.is_archived = 0
                 ORDER BY d.name_ar, p.name_ar",
                array_map('intval', $relevantDisciplineIds)
            );
        }

        return $this->view('SportsActivity.Views.assessment.assess', [
            'registration'          => $registration,
            'groups'                => $groups,
            'programs'              => $programs,
            'selectedDisciplineIds' => $selectedDisciplineIds,
        ]);
    }

    private function getCoachDisciplineIds(): array
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();
        if (!$employee) {
            return [];
        }

        $coach = $db->selectOne(
            "SELECT id FROM sa_coaches WHERE employee_id = ? AND is_active = 1 AND is_archived = 0",
            [(int) $employee->id]
        );
        if (!$coach) {
            return [];
        }

        $rows = $db->select(
            "SELECT discipline_id FROM sa_coach_disciplines WHERE coach_id = ?",
            [(int) $coach['id']]
        );

        return array_map(fn($r) => (int) $r['discipline_id'], $rows);
    }

    public function submit(Request $request, string $id): Response
    {
        $registrationId = (int) $id;
        $groupId = (int) $request->post('group_id', 0);
        $skillLevel = trim((string) $request->post('skill_level', ''));
        $notes = trim((string) $request->post('assessment_notes', ''));

        if ($groupId === 0) {
            return $this->redirect('/sa/coach-assessment/' . $id)->withError('يجب اختيار المجموعة');
        }
        if ($skillLevel === '') {
            return $this->redirect('/sa/coach-assessment/' . $id)->withError('يجب تحديد المستوى');
        }

        $employee = App::getInstance()->currentEmployee();
        $assessedBy = $employee ? (int) $employee->id : 0;

        $result = CoachAssessmentService::assess($registrationId, $groupId, $skillLevel, $notes, $assessedBy);

        if (!$result['success']) {
            return $this->redirect('/sa/coach-assessment/' . $id)->withError($result['error']);
        }

        return $this->redirect('/sa/coach-assessment')
            ->withSuccess('تم تصنيف اللاعب وتعيينه في مجموعة "' . $result['group_name'] . '" بنجاح');
    }
}
