<?php
declare(strict_types=1);

namespace App\Modules\PlayerAffairs\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\PlayerAffairs\Models\Player;
use App\Modules\PlayerAffairs\Models\PlayerMedicalRecord;

final class MedicalRecordService
{
    public static function getCertificateTypes(): array
    {
        return [
            'recreational'  => ['label' => 'ممارس', 'validity_months' => 12],
            'academy'       => ['label' => 'أكاديمي', 'validity_months' => 6],
            'international' => ['label' => 'دولي', 'validity_months' => 3],
        ];
    }

    public static function addRecord(int $playerId, array $data): PlayerMedicalRecord
    {
        $player = Player::find($playerId);
        if (!$player) {
            throw new \RuntimeException('اللاعب غير موجود');
        }

        $employee = App::getInstance()->currentEmployee();

        $certType = $data['certificate_type'] ?? 'recreational';
        $types = self::getCertificateTypes();
        $validityMonths = $types[$certType]['validity_months'] ?? 12;

        $examDate = $data['exam_date'] ?? date('Y-m-d');
        $expiryDate = $data['expiry_date'] ?? date('Y-m-d', strtotime($examDate . ' +' . $validityMonths . ' months'));

        $record = PlayerMedicalRecord::create([
            'player_id'        => $playerId,
            'record_type'      => $data['record_type'] ?? 'fitness_cert',
            'certificate_type' => $certType,
            'validity_months'  => $validityMonths,
            'exam_date'        => $examDate,
            'expiry_date'      => $expiryDate,
            'doctor_name'      => $data['doctor_name'] ?? null,
            'clinic_name'      => $data['clinic_name'] ?? null,
            'issuing_authority' => $data['issuing_authority'] ?? null,
            'cert_number'      => $data['cert_number'] ?? null,
            'result'           => 'pending',
            'approval_status'  => 'pending',
            'restrictions'     => $data['restrictions'] ?? null,
            'document_id'      => $data['document_id'] ?? null,
            'notes'            => $data['notes'] ?? null,
            'created_by'       => $employee ? (int) $employee->id : null,
        ]);

        EventBus::dispatch('player.medical_uploaded', [
            'player_id'        => $playerId,
            'record_id'        => $record->id,
            'certificate_type' => $certType,
        ]);

        return $record;
    }

    public static function approveRecord(int $recordId, int $approvedBy, int $medicalLevel = 1): void
    {
        $db = App::getInstance()->db();

        $record = $db->selectOne("SELECT * FROM player_medical_records WHERE id = ?", [$recordId]);
        if (!$record) {
            throw new \RuntimeException('السجل غير موجود');
        }

        $db->update('player_medical_records', [
            'approval_status' => 'approved',
            'approved_by'     => $approvedBy,
            'approved_at'     => date('Y-m-d H:i:s'),
            'result'          => 'fit',
            'medical_level'   => $medicalLevel,
        ], 'id = ?', [$recordId]);

        $player = Player::find((int) $record['player_id']);
        if ($player) {
            $player->update([
                'medical_status'      => 'fit',
                'medical_expiry_date' => $record['expiry_date'],
                'medical_level'       => $medicalLevel,
            ]);
        }

        // Also update sa_players if the player exists there
        $saPlayer = $db->selectOne("SELECT id FROM sa_players WHERE player_id = ?", [(int) $record['player_id']]);
        if ($saPlayer) {
            $db->update('sa_players', [
                'medical_level' => $medicalLevel,
            ], 'player_id = ?', [(int) $record['player_id']]);
        }

        EventBus::dispatch('player.medical_approved', [
            'player_id'     => (int) $record['player_id'],
            'record_id'     => $recordId,
            'medical_level' => $medicalLevel,
        ]);
    }

    public static function rejectRecord(int $recordId, int $rejectedBy, string $reason): void
    {
        $db = App::getInstance()->db();

        $record = $db->selectOne("SELECT * FROM player_medical_records WHERE id = ?", [$recordId]);
        if (!$record) {
            throw new \RuntimeException('السجل غير موجود');
        }

        $db->update('player_medical_records', [
            'approval_status'  => 'rejected',
            'approved_by'      => $rejectedBy,
            'approved_at'      => date('Y-m-d H:i:s'),
            'rejection_reason' => $reason,
            'result'           => 'unfit',
        ], 'id = ?', [$recordId]);

        EventBus::dispatch('player.medical_rejected', [
            'player_id' => (int) $record['player_id'],
            'record_id' => $recordId,
            'reason'    => $reason,
        ]);
    }

    public static function getPendingApprovals(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT pmr.*, p.full_name_ar AS player_name, p.id AS player_id
             FROM player_medical_records pmr
             LEFT JOIN players p ON p.id = pmr.player_id
             WHERE pmr.approval_status = 'pending'
             ORDER BY pmr.created_at DESC"
        );
    }

    public static function checkClearance(int $playerId): bool
    {
        $player = Player::find($playerId);
        if (!$player) {
            return false;
        }

        $validStatuses = ['fit', 'conditional'];
        if (!in_array($player->medical_status, $validStatuses, true)) {
            return false;
        }

        if (empty($player->medical_expiry_date)) {
            return false;
        }

        return $player->medical_expiry_date > date('Y-m-d');
    }

    public static function getExpiringRecords(int $daysAhead = 30): array
    {
        $db = App::getInstance()->db();
        $today = date('Y-m-d');
        $futureDate = date('Y-m-d', strtotime("+{$daysAhead} days"));

        return $db->select(
            "SELECT * FROM players
             WHERE is_archived = 0
               AND medical_expiry_date IS NOT NULL
               AND medical_expiry_date BETWEEN ? AND ?
             ORDER BY medical_expiry_date ASC",
            [$today, $futureDate]
        );
    }
}
