<?php
include_once __DIR__ . "/../db.php";

function getReferralCode($chat_id): string {
    return "ref_{$chat_id}";
}

function processReferral($referred_chat_id, $referral_code): bool {
    global $pdo;

    if (!preg_match('/^ref_(\d+)$/', $referral_code, $m)) return false;
    $referrer_id = (int)$m[1];

    if ($referrer_id === (int)$referred_chat_id) return false;

    // Already referred?
    $check = $pdo->prepare("SELECT id FROM referrals WHERE referred_chat_id = ?");
    $check->execute([$referred_chat_id]);
    if ($check->fetchColumn()) return false;

    // Referrer must exist
    $exists = $pdo->prepare("SELECT chat_id FROM users WHERE chat_id = ?");
    $exists->execute([$referrer_id]);
    if (!$exists->fetchColumn()) return false;

    $bonus = getSettingInt('referral_credits', 10);

    $pdo->prepare("INSERT INTO referrals (referrer_chat_id, referred_chat_id, credits_awarded) VALUES (?, ?, ?)")
        ->execute([$referrer_id, $referred_chat_id, $bonus]);

    addCredits($referrer_id, $bonus, 'manual_topup', "Referral bonus for inviting user #{$referred_chat_id}");
    addCredits($referred_chat_id, $bonus, 'signup_bonus', "Referral welcome bonus");

    $newBal = getUserCredits($referrer_id);
    sendMessage($referrer_id,
        "🎉 Someone joined using your referral link! You earned <b>{$bonus} bonus credits</b>.\n" .
        "💳 Balance: <b>{$newBal} credits</b>"
    );

    return true;
}

function sendReferralInfo($chat_id): void {
    global $pdo, $config;

    $code    = getReferralCode($chat_id);
    $botName = $config['bot_username'] ?? '';
    $link    = $botName ? "https://t.me/{$botName}?start={$code}" : "(Set BOT_USERNAME in .env to activate)";
    $bonus   = getSettingInt('referral_credits', 10);

    $stmt = $pdo->prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(credits_awarded),0) AS earned FROM referrals WHERE referrer_chat_id = ?");
    $stmt->execute([$chat_id]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);

    $msg  = "👥 <b>Refer &amp; Earn</b>\n\n";
    $msg .= "Share your link — when someone joins you <b>both get {$bonus} free credits!</b>\n\n";
    $msg .= "🔗 Your link:\n<code>{$link}</code>\n\n";
    $msg .= "📊 Your stats:\n";
    $msg .= "• People invited: <b>{$stats['cnt']}</b>\n";
    $msg .= "• Credits earned: <b>{$stats['earned']}</b>";

    $shareText = urlencode("Join me on Fit Bot and get {$bonus} free credits! 💪");
    $shareUrl  = $botName ? "https://t.me/share/url?url=" . urlencode($link) . "&text={$shareText}" : null;

    $buttons = [];
    if ($shareUrl) {
        $buttons[] = [["text" => "📤 Share My Link", "url" => $shareUrl]];
    }
    $buttons[] = [["text" => "🏠 Main Menu", "callback_data" => "main_menu"]];

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