<?php

/* ================= REFER CODE GENERATOR ================= */

function generateReferCode(PDO $pdo): string
{
    do {
        $code = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM user_data WHERE refer_code=?");
        $stmt->execute([$code]);

    } while ($stmt->fetchColumn() > 0);

    return $code;
}

/* ================= ASK COUPON QUESTION ================= */

function ask_coupon_question($chat_id)
{
    $buttons = [
        [
            ['text' => '✅ Yes', 'callback_data' => 'HAS_COUPON'],
            ['text' => '❌ No',  'callback_data' => 'NO_COUPON']
        ]
    ];

   sendMessage(
    $chat_id,
    "🎁 *Aɢᴀʀ Aᴀᴘᴋᴇ Pᴀs Rᴇғᴇʀʀᴀʟ / Cᴏᴜᴘᴏɴ Cᴏᴅᴇ Hᴀɪ*  

Aᴀᴘ Yᴀʜᴀ Dᴀʟ Sᴀᴋᴛᴇ Hᴏ 😎  

🚀* Fᴜᴛᴜʀᴇ Mᴇ Bᴇɴɪғɪᴛ Mɪʟᴇɢᴀ* 🔥",
    ['inline_keyboard' => $buttons],
    "Markdown"
);
}

/* ================= ASK CODE INPUT ================= */

function ask_coupon_code($chat_id)
{
    $lockFile = __DIR__."/user_lock_".$chat_id.".txt";

    sendMessage(
    $chat_id,
    "🔑 *Eɴᴛᴇʀ Yᴏᴜʀ Rᴇғᴇʀʀᴀʟ Cᴏᴅᴇ*  

👇 Rᴇғᴇʀ Cᴏᴅᴇ Dᴀʟᴏ",
    null,
    "Markdown"
);

    file_put_contents($lockFile, "REFERRAL"); 
}


function generate_user_referral_code(PDO $pdo, $chat_id)
{
    $stmt = $pdo->prepare("
        SELECT refer_code FROM user_data WHERE user_id=?
    ");
    $stmt->execute([$chat_id]);
    $existing = $stmt->fetchColumn();

    if ($existing) {
        sendMessage($chat_id, "⚠️ Referral code already generated 😎");
        return;
    }

    do {
        $code = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);

        $check = $pdo->prepare("
            SELECT COUNT(*) FROM user_data WHERE refer_code=?
        ");
        $check->execute([$code]);

    } while ($check->fetchColumn() > 0);

    $pdo->prepare("
        UPDATE user_data SET refer_code=? WHERE user_id=?
    ")->execute([$code, $chat_id]);

    sendMessage(
        $chat_id,
        "✅ *Referral Code Generated!*\n\n🔑 `{$code}`",
        null,
        "Markdown"
    );
}

function show_referral_dashboard(PDO $pdo, $chat_id)
{
    $stmt = $pdo->prepare("
        SELECT refer_code, referral_balance
        FROM user_data
        WHERE user_id=?
    ");
    $stmt->execute([$chat_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    $refer_code = $user['refer_code'];
    $balance    = (float)($user['referral_balance'] ?? 0);

    /* ================= TOTAL REFERRALS ================= */

    if ($refer_code) {
        $total_refs = $pdo->prepare("
            SELECT COUNT(*) FROM user_data WHERE refer_by=?
        ");
        $total_refs->execute([$refer_code]);
        $total_refs = (int)$total_refs->fetchColumn();
    } else {
        $total_refs = 0;
    }

    $msg  = "🎁 *REFER & EARN DIRECT UPI ME*\n\n";

    if ($refer_code) {
        $msg .= "🔑 *Your Referral Code:* `{$refer_code}`\n";
    } else {
        $msg .= "🔑 *Referral Code:* Not Generated\n";
    }

    $msg .= "💰 *Referral Balance(10% On Recharge)* : ₹{$balance}\n";
    $msg .= "👥 *Total Referrals:* {$total_refs}\n\n";

    $buttons = [
        [
            ['text' => '🛡️Condition', 'callback_data' => 'REF_TERMS'],
            
        ],
        [
            ['text' => '💰 Withdraw Balance', 'callback_data' => 'REF_WITHDRAW'],
        ],
        [
            ['text' => '👥 My Referrals', 'callback_data' => 'MY_REFER_USERS'],
        ],
         [
            ['text' => '🔄 Generate Code', 'callback_data' => 'GEN_REFER'],
        ]
    ];

    sendMessage($chat_id, $msg, ['inline_keyboard'=>$buttons], "Markdown");
}

function show_my_referrals(PDO $pdo, $chat_id)
{
    /* ================= GET USER REFER CODE ================= */

    $stmt = $pdo->prepare("
        SELECT refer_code FROM user_data WHERE user_id=?
    ");
    $stmt->execute([$chat_id]);
    $refer_code = $stmt->fetchColumn();

    if (!$refer_code) {
        sendMessage($chat_id, "❌ Generate referral code first 😎");
        return;
    }

    /* ================= FETCH REFERRALS + 30 DAY DEPOSIT ================= */

    $stmt = $pdo->prepare("
        SELECT 
            u.user_id,
            u.name,
            u.status,
            COALESCE(SUM(d.amount),0) deposit_30days
        FROM user_data u
        LEFT JOIN deposit_history d 
            ON d.user_id = u.user_id
            AND d.status = 'success'
            AND d.created_at >= (NOW() - INTERVAL 30 DAY)
        WHERE u.refer_by=?
        GROUP BY u.user_id
        ORDER BY deposit_30days DESC
    ");
    $stmt->execute([$refer_code]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$rows) {
        sendMessage($chat_id, "👥 *No referrals yet* 😎", null, "Markdown");
        return;
    }

    /* ================= TOTAL STATS ================= */

    $total_users = count($rows);
    $total_deposit = 0;

    foreach ($rows as $r) {
        $total_deposit += (float)$r['deposit_30days'];
    }

    $msg  = "👥 *MY REFERRALS DASHBOARD*\n\n";
    $msg .= "📊 *Total Referrals:* {$total_users}\n";
    $msg .= "💰 *30 Days Deposit:* ₹{$total_deposit}\n";
    $msg .= "🎁 *Your Earnings (10%):* ₹".round($total_deposit * 0.10, 2)."\n\n";

    $msg .= "━━━━━━━━━━━━━━━\n\n";

    /* ================= USER LIST ================= */

    $i = 1;

    foreach ($rows as $r) {

        $deposit = (float)$r['deposit_30days'];

        $msg .= "{$i}. *{$r['name']}*\n";
        $msg .= "   🆔 `{$r['user_id']}`\n";
        $msg .= "   📌 Status: {$r['status']}\n";
        $msg .= "   💰 30D Deposit: ₹{$deposit}\n\n";

        $i++;
    }

    sendMessage($chat_id, $msg, null, "Markdown");
}

function referral_withdraw_request(PDO $pdo, $chat_id)
{
    $stmt = $pdo->prepare("
        SELECT referral_balance FROM user_data WHERE user_id=?
    ");
    $stmt->execute([$chat_id]);
    $balance = (float)$stmt->fetchColumn();

    if ($balance < 1500) {

        sendMessage(
            $chat_id,
            "❌ *Minimum Withdrawal:* ₹1500\n".
            "💰 *Your Balance:* ₹{$balance}",
            null,
            "Markdown"
        );
        return;
    }

    sendMessage(
        $chat_id,
        "💰 *Done Aab Aap Withdrawl Ke Liye Eligible Ho Admin Ko Message Karek Aap Withdrwal Karlo*\n\n".
        "⏳ Processing...",
        null,
        "Markdown"
    );

    /* OPTIONAL → DB entry / admin notify */
}
/* ================= APPLY REFERRAL ================= */
function show_referral_terms($chat_id)
{
    $msg = 
"📜 *Referral Terms & Conditions*\n\n".

"🎁 *Referral System Kaise Kaam Karta Hai*\n".
"━━━━━━━━━━━━━━━\n".
"• Apko *10% bonus* milega apke referred user ke *successful deposit* par direct upi withdrwal 💰\n".
"• Sirf *success deposit* count hoga\n\n".

"💰 *Bonus Samjho Simple Language Me*\n".
"━━━━━━━━━━━━━━━\n".
"• Jitna apka user deposit karega → Uska 10% apka profit 😈\n".
"• Jyada activity = Jyada earning 😎\n\n".

"💳 *Withdrawal Policy*\n".
"━━━━━━━━━━━━━━━\n".
"• Minimum withdrawal: *₹1500* hai\n".
"• Agar ₹1500 se kam balance hai → Withdrawal work nahi karega ⏳\n\n".

"🚫 *Important Rules*\n".
"━━━━━━━━━━━━━━━\n".
"• Self referral allowed nahi hai 😈\n".
"• Fake / duplicate accounts → Bonus cancel ho sakta hai\n".
"• Suspicious activity → Account action 🚫\n\n".

"🔥 *Refer Smart. Earn More.* 😈💰";

    sendMessage($chat_id, $msg, null, "Markdown");
}
function apply_referral_code(PDO $pdo, $chat_id, $user_id, $code)
{
    debug_log("REFERRAL_APPLY_START");

    $stmt = $pdo->prepare("
        SELECT user_id FROM user_data WHERE refer_code=?
        LIMIT 1
    ");
    $stmt->execute([$code]);

    $referrer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$referrer) {

        sendMessage($chat_id, "❌ Invalid referral code 😈");
        return;
    }

    /* ================= SELF REFERRAL BLOCK ================= */

    if ($referrer['user_id'] == $user_id) {

        sendMessage($chat_id, "❌ You cannot use your own code 😈🔥");
        return;
    }

    /* ================= APPLY ONLY ONCE ================= */

    $stmt = $pdo->prepare("
        UPDATE user_data
        SET refer_by=?
        WHERE user_id=? 
        AND refer_by IS NULL
    ");
    $stmt->execute([$code, $user_id]);

    if ($stmt->rowCount() > 0) {

       sendMessage(
    $chat_id,
    "🎉 *Yᴇ Rᴇғᴇʀʀᴀʟ Aᴘᴘʟʏ Hᴏ Gᴀʏᴀ Hᴀɪ* 😎🔥  

🤝 Tᴜᴍʜᴀʀᴀ Dᴏsᴛ Aʙ Pᴀɪsᴇ Kᴀᴍᴀʏᴇɢᴀ 💰  

🚀 Tᴜᴍ Bʜɪ Rᴇғᴇʀ Kᴀʀᴋᴇ Kᴀᴍᴀ Sᴀᴋᴛᴇ Hᴏ 🔥",
    null,
    "Markdown"
);

        /* ================= AUTO START 😎🔥 ================= */

        start($pdo, $chat_id, "User");

    } else {

        sendMessage($chat_id, "⚠️ Referral already used 😎");
    }
}