<?php
declare(strict_types=1);

namespace App\Modules\PlayerAffairs\Services;

use App\Core\App;
use App\Core\EventBus;

final class PlayerProgressionService
{
    public static function getProgressionTypes(): array
    {
        return [
            'promotion' => 'ترقية',
            'demotion'  => 'تراجع',
            'lateral'   => 'نقل جانبي',
        ];
    }

    public static function getCertificateTypes(): array
    {
        return [
            'recreational'  => ['label' => 'ممارسين', 'validity_months' => 12, 'color' => '#059669'],
            'academy'       => ['label' => 'أكاديمية', 'validity_months' => 6, 'color' => '#2563EB'],
            'international' => ['label' => 'دولية', 'validity_months' => 3, 'color' => '#7C3AED'],
        ];
    }

    public static function recordProgression(
        int $playerId,
        int $disciplineId,
        ?int $fromLevelId,
        int $toLevelId,
        string $type,
        ?float $score,
        ?int $assessedBy,
        ?string $notes,
        ?string $effectiveDate = null
    ): int {
        $db = App::getInstance()->db();

        $id = $db->insert('player_progressions', [
            'player_id'        => $playerId,
            'discipline_id'    => $disciplineId,
            'from_level_id'    => $fromLevelId,
            'to_level_id'      => $toLevelId,
            'progression_type' => $type,
            'assessment_score' => $score,
            'assessed_by'      => $assessedBy,
            'assessment_notes' => $notes,
            'effective_date'   => $effectiveDate ?? date('Y-m-d'),
        ]);

        $db->update('players', [
            'current_level_id' => $toLevelId,
            'overall_rating'   => $score,
        ], 'id = ?', [$playerId]);

        EventBus::dispatch('player.progression.recorded', [
            'player_id'   => $playerId,
            'type'        => $type,
            'to_level_id' => $toLevelId,
            'score'       => $score,
        ]);

        return $id;
    }

    public static function getPlayerProgressions(int $playerId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pp.*, sd.name_ar AS discipline_name,
                    al_from.name_ar AS from_level_name,
                    al_to.name_ar AS to_level_name
             FROM player_progressions pp
             LEFT JOIN sport_disciplines sd ON sd.id = pp.discipline_id
             LEFT JOIN academy_levels al_from ON al_from.id = pp.from_level_id
             LEFT JOIN academy_levels al_to ON al_to.id = pp.to_level_id
             WHERE pp.player_id = ?
             ORDER BY pp.effective_date DESC, pp.created_at DESC",
            [$playerId]
        );
    }

    public static function calculateExpiryDate(string $certificateType, string $issueDate): string
    {
        $types = self::getCertificateTypes();
        $months = $types[$certificateType]['validity_months'] ?? 12;
        return date('Y-m-d', strtotime($issueDate . ' +' . $months . ' months'));
    }

    public static function getExpiringCertificates(int $daysAhead = 30): array
    {
        $db = App::getInstance()->db();
        $targetDate = date('Y-m-d', strtotime('+' . $daysAhead . ' days'));

        return $db->select(
            "SELECT pmr.*, p.full_name AS player_name, p.phone AS player_phone
             FROM player_medical_records pmr
             LEFT JOIN players p ON p.id = pmr.player_id
             WHERE pmr.expiry_date IS NOT NULL
             AND pmr.expiry_date <= ?
             AND pmr.expiry_date >= CURDATE()
             ORDER BY pmr.expiry_date ASC",
            [$targetDate]
        );
    }
}
