<?php
declare(strict_types=1);

namespace App\Modules\Academies\Services;

use App\Modules\Academies\Models\Academy;
use App\Modules\Academies\Models\AcademyLevel;
use App\Modules\Academies\Models\AcademySchedule;

class AcademyService
{
    /**
     * Get all active academies.
     */
    public static function getActive(): array
    {
        return Academy::allActive();
    }

    /**
     * Get active academies filtered by discipline.
     */
    public static function getAcademiesForDiscipline(int $disciplineId): array
    {
        return Academy::getByDiscipline($disciplineId);
    }

    /**
     * Get levels for a given academy.
     */
    public static function getLevels(int $academyId): array
    {
        return AcademyLevel::getForAcademy($academyId);
    }

    /**
     * Get schedules for a given academy.
     */
    public static function getSchedule(int $academyId): array
    {
        return AcademySchedule::getForAcademy($academyId);
    }

    /**
     * Check if an age is eligible for any level within an academy.
     */
    public static function checkAgeEligibility(int $academyId, int $age): bool
    {
        $levels = AcademyLevel::getForAcademy($academyId);
        if (empty($levels)) {
            // No levels defined — allow all ages
            return true;
        }

        foreach ($levels as $level) {
            $minAge = (int) ($level['age_min'] ?? 0);
            $maxAge = (int) ($level['age_max'] ?? 999);
            if ($age >= $minAge && $age <= $maxAge) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get all active academies grouped by academy_type.
     */
    public static function getGroupedByType(): array
    {
        $academies = Academy::allActive();
        $grouped = [];

        foreach (Academy::getAcademyTypes() as $key => $label) {
            $grouped[$key] = [];
        }

        foreach ($academies as $a) {
            $type = $a['academy_type'] ?? 'general';
            if (!isset($grouped[$type])) {
                $grouped[$type] = [];
            }
            $grouped[$type][] = $a;
        }

        return $grouped;
    }
}
