<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\EventBus;
use App\Core\Logger;

/**
 * Sends reminders for expiring medical certificates.
 * Runs daily — checks for medical records expiring within 30 days.
 */
class MedicalExpiryReminderJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Runs daily
    }

    public function run(): array
    {
        $today = date('Y-m-d');
        $thirtyDaysLater = date('Y-m-d', strtotime('+30 days'));
        $notified = 0;
        $expired = 0;

        // Find players with medical certificates expiring within 30 days
        $expiring = $this->db->select("
            SELECT p.id AS player_id, p.full_name_ar, p.phone, p.medical_expiry_date
            FROM players p
            WHERE p.is_archived = 0
              AND p.medical_expiry_date IS NOT NULL
              AND p.medical_expiry_date BETWEEN ? AND ?
              AND p.medical_status IN ('fit', 'conditional')
        ", [$today, $thirtyDaysLater]);

        foreach ($expiring as $player) {
            EventBus::dispatch('player.medical_expiry', [
                'player_id'    => (int) $player['player_id'],
                'player_name'  => $player['full_name_ar'],
                'phone'        => $player['phone'],
                'expiry_date'  => $player['medical_expiry_date'],
            ]);
            $notified++;
        }

        // Update players whose medical has already expired
        $expiredPlayers = $this->db->select("
            SELECT id FROM players
            WHERE is_archived = 0
              AND medical_expiry_date IS NOT NULL
              AND medical_expiry_date < ?
              AND medical_status NOT IN ('expired', 'pending')
        ", [$today]);

        foreach ($expiredPlayers as $ep) {
            $this->db->update('players', [
                'medical_status' => 'expired',
                'updated_at'     => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $ep['id']]);
            $expired++;
        }

        Logger::info("Medical expiry check: {$notified} reminders sent, {$expired} marked expired");
        return ['reminders_sent' => $notified, 'marked_expired' => $expired];
    }
}
