<?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();

        // Suspend enrollments where medical grace period has expired
        $graceSuspended = 0;
        $graceExpired = $this->db->select("
            SELECT gp.id, gp.player_id, gp.group_id
            FROM sa_group_players gp
            JOIN sa_players p ON p.id = gp.player_id
            WHERE gp.status = 'active'
              AND gp.medical_grace_deadline IS NOT NULL
              AND gp.medical_grace_deadline < ?
              AND p.medical_status NOT IN ('fit', 'conditional')
        ", [$today]);

        foreach ($graceExpired as $enrollment) {
            $this->db->update('sa_group_players', [
                'status'     => 'suspended',
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $enrollment['id']]);

            $group = $this->db->selectOne("SELECT current_count FROM sa_groups WHERE id = ?", [(int) $enrollment['group_id']]);
            if ($group) {
                $newCount = max(0, (int) $group['current_count'] - 1);
                $this->db->update('sa_groups', [
                    'current_count' => $newCount,
                    'is_full'       => 0,
                    'updated_at'    => date('Y-m-d H:i:s'),
                ], 'id = ?', [(int) $enrollment['group_id']]);
            }

            EventBus::dispatch('sa.player.medical_grace_expired', [
                'player_id'     => (int) $enrollment['player_id'],
                'group_id'      => (int) $enrollment['group_id'],
                'enrollment_id' => (int) $enrollment['id'],
            ]);
            $graceSuspended++;
        }

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