<?php
declare(strict_types=1);

namespace CronJobs;

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

/**
 * Revokes overdue activity subscriptions and suspends player cards.
 * Runs on the 8th of each month (7 days after the due date on the 1st).
 */
class ActivitySubRevokeJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        // Read revoke day from business rules, default to 7
        $rule = $this->db->selectOne(
            "SELECT current_value_json FROM business_rules WHERE rule_code = 'SPORTS_SUB_REVOKE_DAY' AND is_active = 1 AND branch_id IS NULL"
        );
        $revokeDay = 7;
        if ($rule) {
            $decoded = json_decode($rule['current_value_json'], true);
            $revokeDay = (int) ($decoded['day'] ?? 7);
        }

        // Run when current day > due_date(7th) + revoke_day
        return (int) date('j') >= (7 + $revokeDay);
    }

    public function run(): array
    {
        $ts = date('Y-m-d H:i:s');
        $today = date('Y-m-d');
        $revoked = 0;

        // Find overdue subscriptions: status is pending/overdue AND due_date has passed
        $overdue = $this->db->select("
            SELECT as2.id, as2.player_id, as2.subscription_month, as2.total_amount
            FROM activity_subscriptions as2
            WHERE as2.status IN ('pending', 'overdue')
              AND as2.due_date IS NOT NULL
              AND as2.due_date < ?
        ", [$today]);

        foreach ($overdue as $sub) {
            // Revoke the subscription
            $this->db->update('activity_subscriptions', [
                'status'     => 'revoked',
                'revoked_at' => $ts,
                'updated_at' => $ts,
            ], 'id = ?', [(int) $sub['id']]);

            // Revoke the player's card
            $this->db->update('players', [
                'card_status' => 'revoked',
                'updated_at'  => $ts,
            ], 'id = ? AND card_status != ?', [(int) $sub['player_id'], 'revoked']);

            EventBus::dispatch('activity_sub.revoked', [
                'subscription_id' => (int) $sub['id'],
                'player_id'       => (int) $sub['player_id'],
                'month'           => $sub['subscription_month'],
                'amount'          => $sub['total_amount'],
            ]);

            EventBus::dispatch('player.card_revoked', [
                'player_id' => (int) $sub['player_id'],
                'reason'    => 'عدم سداد اشتراك شهر ' . $sub['subscription_month'],
            ]);

            $revoked++;
        }

        Logger::info("Activity subscription revoke: {$revoked} subscriptions revoked");
        return ['revoked' => $revoked];
    }
}
