<?php
declare(strict_types=1);

namespace CronJobs;

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

class SaMedicalExpiryJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

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

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

        $expiring = $this->db->select("
            SELECT id, full_name_ar, phone, medical_expiry_date
            FROM sa_players
            WHERE is_archived = 0
              AND medical_expiry_date IS NOT NULL
              AND medical_expiry_date BETWEEN ? AND ?
              AND medical_status IN ('fit', 'conditional')
        ", [$today, $thirtyDaysLater]);

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

        $expiredPlayers = $this->db->select("
            SELECT id FROM sa_players
            WHERE is_archived = 0
              AND medical_expiry_date IS NOT NULL
              AND medical_expiry_date < ?
              AND medical_status IN ('fit', 'conditional')
        ", [$today]);

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

        $stmt = $this->db->query("
            UPDATE sa_player_documents
            SET approval_status = 'expired', updated_at = ?
            WHERE document_type = 'medical_cert'
              AND approval_status = 'approved'
              AND expiry_date IS NOT NULL
              AND expiry_date < ?
        ", [date('Y-m-d H:i:s'), $today]);
        $docsExpired = $stmt->rowCount();

        Logger::info("SA Medical expiry: {$notified} reminders, {$expired} players expired, {$docsExpired} docs expired");
        return ['reminders_sent' => $notified, 'players_expired' => $expired, 'docs_expired' => $docsExpired];
    }
}
