<?php

require_once __DIR__."/conn.php";

/* ================= LOCK (PREVENT DOUBLE CRON 😈🔥) ================= */

$lock = $pdo->query("SELECT GET_LOCK('referral_bonus_lock', 5)")->fetchColumn();

if (!$lock) {
    exit("Cron already running\n");
}

/* ================= BONUS RECALCULATION 😎🔥 ================= */

try {

    $pdo->exec("
        UPDATE user_data u
        LEFT JOIN (
            SELECT 
                r.refer_by,
                SUM(d.amount) * 0.10 AS bonus
            FROM user_data r
            JOIN deposit_history d 
                ON d.user_id = r.user_id
            WHERE d.status = 'success'
            AND r.refer_by IS NOT NULL
            GROUP BY r.refer_by
        ) x ON x.refer_by = u.refer_code
        SET u.referral_balance = COALESCE(x.bonus, 0)
    ");

    echo "✅ Referral bonus recalculated\n";

} catch (Throwable $e) {

    echo "❌ ERROR: ".$e->getMessage()."\n";
}

/* ================= RELEASE LOCK 😎🔥 ================= */

$pdo->query("SELECT RELEASE_LOCK('referral_bonus_lock')");