<?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
{
    /**
     * Add a medical record for a player and update their medical status.
     */
    public static function addRecord(int $playerId, array $data): PlayerMedicalRecord
    {
        $player = Player::find($playerId);
        if (!$player) {
            throw new \RuntimeException('اللاعب غير موجود');
        }

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

        $record = PlayerMedicalRecord::create([
            'player_id'    => $playerId,
            'record_type'  => $data['record_type'] ?? 'medical_exam',
            'exam_date'    => $data['exam_date'] ?? date('Y-m-d'),
            'expiry_date'  => $data['expiry_date'] ?? null,
            'doctor_name'  => $data['doctor_name'] ?? null,
            'clinic_name'  => $data['clinic_name'] ?? null,
            'result'       => $data['result'] ?? 'pending',
            'restrictions' => $data['restrictions'] ?? null,
            'document_id'  => $data['document_id'] ?? null,
            'notes'        => $data['notes'] ?? null,
            'created_by'   => $employee ? (int) $employee->id : null,
        ]);

        // Update the player's medical status and expiry based on the new record
        $updateData = [];
        if (!empty($data['result'])) {
            $updateData['medical_status'] = $data['result'];
        }
        if (!empty($data['expiry_date'])) {
            $updateData['medical_expiry_date'] = $data['expiry_date'];
        }
        if (!empty($updateData)) {
            $player->update($updateData);
        }

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

        return $record;
    }

    /**
     * Check if a player has valid medical clearance.
     */
    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');
    }

    /**
     * Get players whose medical records expire within the given number of days.
     */
    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]
        );
    }
}
