<?php
/**
 * Cron: أول كل شهر في الساعة 1 صباحاً
 * 0 1 1 * * php /var/www/sudanna/cron/renew_subscription_credits.php
 */
require_once dirname(__DIR__).'/config.php';

$plans = ['plus' => 15000, 'pro' => 50000, 'corp' => 100000];
$month = (int)date('n');
$year  = (int)date('Y');
$count = 0;

foreach ($plans as $planKey => $creditSdg) {
    try {
        // أنشئ أو حدِّث رصيد الوثائق لكل مستخدم نشط
        $users = db()->prepare(
            "SELECT id FROM users WHERE plan_key=? AND account_status='active'"
        );
        $users->execute([$planKey]);
        foreach ($users->fetchAll(PDO::FETCH_COLUMN) as $uid) {
            db()->prepare(
                "INSERT INTO subscription_credits
                 (user_id, period_month, period_year, monthly_sdg, used_sdg, remaining_sdg)
                 VALUES (?, ?, ?, ?, 0, ?)
                 ON DUPLICATE KEY UPDATE
                   monthly_sdg=VALUES(monthly_sdg),
                   used_sdg=0,
                   remaining_sdg=VALUES(remaining_sdg)"
            )->execute([$uid, $month, $year, $creditSdg, $creditSdg]);
            $count++;
        }
    } catch (Throwable $e) {
        error_log("[renew_credits] $planKey: " . $e->getMessage());
    }
}

echo "[renew_subscription_credits] " . date('Y-m-d H:i:s') . " — Renewed: {$count} users\n";
