<?php
$page_title = "Referral Program";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';


$db = Database::getInstance()->connect();
$user_id = $_SESSION['user_id'];

$user_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user = $user_stmt->fetch();

// Get referral statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_referrals,
        SUM(CASE WHEN account_status = 'active' THEN 1 ELSE 0 END) as active_referrals,
        SUM(CASE WHEN account_status = 'active' THEN balance ELSE 0 END) as referrals_balance,
        (SELECT COUNT(*) FROM transactions WHERE user_id = ? AND type = 'referral_bonus' AND status = 'completed') as bonus_count,
        (SELECT SUM(amount) FROM transactions WHERE user_id = ? AND type = 'referral_bonus' AND status = 'completed') as total_bonus_earned,
        (SELECT COUNT(*) FROM users WHERE referred_by = ? AND DATE(created_at) = CURDATE()) as today_referrals
    FROM users 
    WHERE referred_by = ?
";

$stats_stmt = $db->prepare($stats_sql);
$stats_stmt->execute([$user_id, $user_id, $user_id, $user_id]);
$stats = $stats_stmt->fetch();

// Get referral settings
$settings_stmt = $db->query("SELECT * FROM settings WHERE `key` IN ('referral_bonus', 'referral_commission')");
$referral_settings = [];
while ($row = $settings_stmt->fetch()) {
    $referral_settings[$row['key']] = $row['value'];
}

$referral_bonus = floatval($referral_settings['referral_bonus'] ?? 10.00);
$commission_rate = floatval($referral_settings['referral_commission'] ?? 0.05); // 5%

// Get recent referrals
$referrals_sql = "
    SELECT 
        u.id, u.username, u.email, u.balance, u.account_status, u.created_at,
        (SELECT COUNT(*) FROM users WHERE referred_by = u.id) as level2_referrals,
        (SELECT SUM(balance) FROM users WHERE referred_by = u.id) as level2_balance
    FROM users u
    WHERE u.referred_by = ?
    ORDER BY u.created_at DESC
    LIMIT 10
";

$referrals_stmt = $db->prepare($referrals_sql);
$referrals_stmt->execute([$user_id]);
$recent_referrals = $referrals_stmt->fetchAll();

// Get referral transactions
$transactions_sql = "
    SELECT * FROM transactions 
    WHERE user_id = ? AND type = 'referral_bonus'
    ORDER BY created_at DESC 
    LIMIT 10
";

$transactions_stmt = $db->prepare($transactions_sql);
$transactions_stmt->execute([$user_id]);
$referral_transactions = $transactions_stmt->fetchAll();

// Generate referral link
$site_url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$site_url .= $_SERVER['HTTP_HOST'];
$referral_link = $site_url . '/register.php?ref=' . $user['referral_code'];
?>


<?php require_once '../includes/header_user.php'; ?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Referral Program</h1>
        <p class="text-gray-600">Earn bonuses by inviting friends to join <?php echo SITE_NAME; ?></p>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Referrals</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total_referrals'] ?? 0); ?></h3>
                </div>
                <i class="fas fa-users text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Referrals</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['active_referrals'] ?? 0); ?></h3>
                </div>
                <i class="fas fa-user-check text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Bonus Earned</p>
                    <h3 class="text-2xl font-bold text-yellow-600">$<?php echo number_format($stats['total_bonus_earned'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-yellow-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Available Bonus</p>
                    <h3 class="text-2xl font-bold text-blue-600">$<?php echo number_format($user['referral_balance'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-wallet text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Referral Link Section -->
    <div class="bg-gradient-to-r from-purple-500 to-blue-500 text-white rounded-xl p-6 mb-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
            <div>
                <h3 class="text-xl font-bold mb-2">Your Referral Link</h3>
                <p class="opacity-90 mb-4">Share this link with friends and earn bonuses</p>
                <div class="flex">
                    <input type="text" id="referralLink" value="<?php echo htmlspecialchars($referral_link); ?>" 
                           class="flex-1 px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-l-lg text-white"
                           readonly>
                    <button onclick="copyReferralLink()" class="bg-white text-purple-600 font-bold px-6 py-3 rounded-r-lg hover:bg-gray-100">
                        <i class="fas fa-copy mr-2"></i>Copy
                    </button>
                </div>
                <p class="text-sm opacity-90 mt-3">
                    <i class="fas fa-gift mr-1"></i> 
                    Earn $<?php echo number_format($referral_bonus, 2); ?> for each successful referral
                </p>
            </div>
            <div class="text-center">
                <div class="text-4xl font-bold mb-2"><?php echo ($commission_rate * 100); ?>%</div>
                <p class="text-sm opacity-90">Commission on referrals' deposits</p>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Referral Stats & Sharing -->
        <div class="lg:col-span-2">
            <!-- Sharing Options -->
            <div class="bg-white rounded-xl shadow p-6 mb-6">
                <h3 class="text-lg font-bold mb-4">Share & Earn</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <button onclick="shareOnFacebook()" class="bg-blue-600 text-white p-4 rounded-lg hover:bg-blue-700">
                        <i class="fab fa-facebook-f text-2xl mb-2"></i>
                        <p class="font-semibold">Facebook</p>
                    </button>
                    
                    <button onclick="shareOnTwitter()" class="bg-blue-400 text-white p-4 rounded-lg hover:bg-blue-500">
                        <i class="fab fa-twitter text-2xl mb-2"></i>
                        <p class="font-semibold">Twitter</p>
                    </button>
                    
                    <button onclick="shareOnWhatsApp()" class="bg-green-500 text-white p-4 rounded-lg hover:bg-green-600">
                        <i class="fab fa-whatsapp text-2xl mb-2"></i>
                        <p class="font-semibold">WhatsApp</p>
                    </button>
                    
                    <button onclick="copyEmailTemplate()" class="bg-red-500 text-white p-4 rounded-lg hover:bg-red-600">
                        <i class="fas fa-envelope text-2xl mb-2"></i>
                        <p class="font-semibold">Email</p>
                    </button>
                    
                    <button onclick="shareOnTelegram()" class="bg-blue-300 text-white p-4 rounded-lg hover:bg-blue-400">
                        <i class="fab fa-telegram text-2xl mb-2"></i>
                        <p class="font-semibold">Telegram</p>
                    </button>
                    
                    <button onclick="showQRCode()" class="bg-gray-700 text-white p-4 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-qrcode text-2xl mb-2"></i>
                        <p class="font-semibold">QR Code</p>
                    </button>
                </div>
            </div>

            <!-- Referral Commission Structure -->
            <div class="bg-white rounded-xl shadow p-6 mb-6">
                <h3 class="text-lg font-bold mb-4">Commission Structure</h3>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="p-3 text-left">Level</th>
                                <th class="p-3 text-left">Commission Rate</th>
                                <th class="p-3 text-left">Description</th>
                                <th class="p-3 text-left">Example</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <tr>
                                <td class="p-3 font-medium">Level 1 (Direct)</td>
                                <td class="p-3">
                                    <span class="px-2 py-1 bg-green-100 text-green-800 rounded text-sm">
                                        <?php echo ($commission_rate * 100); ?>%
                                    </span>
                                </td>
                                <td class="p-3 text-sm text-gray-600">Direct referrals you invite</td>
                                <td class="p-3">
                                    <p class="text-sm">$100 deposit = $<?php echo number_format($commission_rate * 100, 2); ?> bonus</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="p-3 font-medium">Level 2 (Indirect)</td>
                                <td class="p-3">
                                    <span class="px-2 py-1 bg-blue-100 text-blue-800 rounded text-sm">
                                        <?php echo ($commission_rate * 50); ?>%
                                    </span>
                                </td>
                                <td class="p-3 text-sm text-gray-600">Referrals of your referrals</td>
                                <td class="p-3">
                                    <p class="text-sm">$100 deposit = $<?php echo number_format($commission_rate * 50, 2); ?> bonus</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="p-3 font-medium">Signup Bonus</td>
                                <td class="p-3">
                                    <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-sm">
                                        $<?php echo number_format($referral_bonus, 2); ?>
                                    </span>
                                </td>
                                <td class="p-3 text-sm text-gray-600">One-time bonus per successful referral</td>
                                <td class="p-3">
                                    <p class="text-sm">New user signs up = $<?php echo number_format($referral_bonus, 2); ?> bonus</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Recent Referrals -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Recent Referrals</h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="p-4 text-left">User</th>
                                <th class="p-4 text-left">Status</th>
                                <th class="p-4 text-left">Balance</th>
                                <th class="p-4 text-left">Joined</th>
                                <th class="p-4 text-left">Level 2</th>
                                <th class="p-4 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <?php if (count($recent_referrals) > 0): ?>
                                <?php foreach ($recent_referrals as $referral): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="p-4">
                                        <p class="font-medium"><?php echo htmlspecialchars($referral['username']); ?></p>
                                        <p class="text-sm text-gray-500"><?php echo htmlspecialchars($referral['email']); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <span class="px-2 py-1 rounded-full text-xs font-semibold <?php
                                            echo $referral['account_status'] == 'active' ? 'bg-green-100 text-green-800' :
                                                ($referral['account_status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                                'bg-red-100 text-red-800');
                                        ?>">
                                            <?php echo ucfirst($referral['account_status']); ?>
                                        </span>
                                    </td>
                                    <td class="p-4">
                                        <p class="font-bold">$<?php echo number_format($referral['balance'], 2); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <p><?php echo date('M d, Y', strtotime($referral['created_at'])); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <p class="text-sm">
                                            <?php echo number_format($referral['level2_referrals']); ?> users
                                            <br>
                                            <span class="text-gray-500">$<?php echo number_format($referral['level2_balance'], 2); ?></span>
                                        </p>
                                    </td>
                                    <td class="p-4">
                                        <button onclick="sendInvitation(<?php echo $referral['id']; ?>)" 
                                                class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                            <i class="fas fa-envelope mr-1"></i> Invite
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="p-8 text-center text-gray-500">
                                        <i class="fas fa-users text-4xl mb-4 text-gray-300"></i>
                                        <p class="text-lg">No referrals yet</p>
                                        <p class="text-sm mt-2">Start sharing your referral link to earn bonuses</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="space-y-6">
            <!-- Referral Code -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Your Referral Code</h3>
                <div class="text-center">
                    <div class="text-4xl font-bold text-purple-600 mb-4 tracking-wider">
                        <?php echo $user['referral_code']; ?>
                    </div>
                    <button onclick="copyReferralCode()" class="w-full bg-purple-600 text-white py-3 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-copy mr-2"></i>Copy Code
                    </button>
                    <p class="text-sm text-gray-500 mt-3">Share this code during registration</p>
                </div>
            </div>

            <!-- Bonus Withdrawal -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Withdraw Bonus</h3>
                <div class="space-y-4">
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <p class="text-sm text-gray-600">Available Bonus</p>
                        <p class="text-2xl font-bold text-green-600">$<?php echo number_format($user['referral_balance'], 2); ?></p>
                    </div>
                    
                    <button onclick="withdrawBonus()" 
                            class="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                            <?php echo $user['referral_balance'] <= 0 ? 'disabled' : ''; ?>>
                        <i class="fas fa-hand-holding-usd mr-2"></i>Withdraw Bonus
                    </button>
                    
                    <p class="text-sm text-gray-500 text-center">
                        Minimum withdrawal: $10.00
                    </p>
                </div>
            </div>

            <!-- Referral Transactions -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Recent Bonus Earnings</h3>
                <div class="space-y-4">
                    <?php if (count($referral_transactions) > 0): ?>
                        <?php foreach ($referral_transactions as $tx): ?>
                        <div class="border-b pb-4 last:border-0 last:pb-0">
                            <div class="flex justify-between items-start">
                                <div>
                                    <p class="font-medium text-green-600">+$<?php echo number_format($tx['amount'], 2); ?></p>
                                    <p class="text-sm text-gray-500"><?php echo date('M d', strtotime($tx['created_at'])); ?></p>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm"><?php echo htmlspecialchars($tx['description']); ?></p>
                                    <span class="text-xs px-2 py-1 rounded-full <?php echo $tx['status'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                        <?php echo ucfirst($tx['status']); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-gray-500 text-center py-4">No bonus earnings yet</p>
                    <?php endif; ?>
                </div>
                <?php if (count($referral_transactions) > 0): ?>
                <div class="mt-4 text-center">
                    <a href="transactions.php?type=referral_bonus" class="text-blue-600 hover:text-blue-800 text-sm">
                        View All Bonuses →
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <!-- Tips & Guidelines -->
            <div class="bg-blue-50 border border-blue-200 rounded-xl p-6">
                <h4 class="font-bold text-blue-800 mb-3">
                    <i class="fas fa-lightbulb mr-2"></i>Tips for Success
                </h4>
                <ul class="space-y-2 text-sm text-blue-700">
                    <li>• Share on social media platforms</li>
                    <li>• Send personalized invitations</li>
                    <li>• Explain the benefits clearly</li>
                    <li>• Follow up with your referrals</li>
                    <li>• Create tutorial videos</li>
                    <li>• Join investment forums</li>
                    <li>• Use email marketing</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Performance Metrics -->
    <div class="mt-6 bg-white rounded-xl shadow p-6">
        <h3 class="text-lg font-bold mb-4">Referral Performance</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="text-center p-4 border rounded-lg">
                <p class="text-sm text-gray-600">Conversion Rate</p>
                <p class="text-2xl font-bold">
                    <?php 
                    $conversion_rate = $stats['total_referrals'] > 0 ? ($stats['active_referrals'] / $stats['total_referrals'] * 100) : 0;
                    echo number_format($conversion_rate, 1); 
                    ?>%
                </p>
            </div>
            
            <div class="text-center p-4 border rounded-lg">
                <p class="text-sm text-gray-600">Avg. Referral Balance</p>
                <p class="text-2xl font-bold text-green-600">
                    $<?php echo $stats['total_referrals'] > 0 ? number_format($stats['referrals_balance'] / $stats['total_referrals'], 2) : '0.00'; ?>
                </p>
            </div>
            
            <div class="text-center p-4 border rounded-lg">
                <p class="text-sm text-gray-600">Today's Referrals</p>
                <p class="text-2xl font-bold"><?php echo number_format($stats['today_referrals'] ?? 0); ?></p>
            </div>
            
            <div class="text-center p-4 border rounded-lg">
                <p class="text-sm text-gray-600">Monthly Goal</p>
                <div class="w-full bg-gray-200 rounded-full h-2 mt-2">
                    <div class="bg-green-600 h-2 rounded-full" style="width: <?php echo min(100, ($stats['today_referrals'] / 10 * 100)); ?>%"></div>
                </div>
                <p class="text-sm mt-2"><?php echo $stats['today_referrals']; ?> / 10 referrals</p>
            </div>
        </div>
    </div>
</div>

<!-- QR Code Modal -->
<div id="qrModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div class="p-6 border-b">
                <h3 class="text-xl font-bold">Referral QR Code</h3>
            </div>
            <div class="p-6 text-center">
                <div id="qrcode" class="mb-4 flex justify-center"></div>
                <p class="text-sm text-gray-600">Scan to visit registration page</p>
                <p class="text-xs text-gray-500 mt-2"><?php echo htmlspecialchars($referral_link); ?></p>
            </div>
            <div class="p-6 border-t">
                <button onclick="closeQRModal()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<!-- QR Code Library -->
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
const referralLink = '<?php echo htmlspecialchars($referral_link); ?>';
const referralCode = '<?php echo htmlspecialchars($user['referral_code']); ?>';
const referralBonus = <?php echo $referral_bonus; ?>;
const commissionRate = <?php echo $commission_rate; ?>;
const availableBonus = <?php echo $user['referral_balance']; ?>;

// Copy referral link
function copyReferralLink() {
    navigator.clipboard.writeText(referralLink).then(() => {
        showNotification('Referral link copied to clipboard!', 'success');
    }).catch(err => {
        console.error('Failed to copy: ', err);
        // Fallback method
        const textArea = document.createElement('textarea');
        textArea.value = referralLink;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showNotification('Referral link copied to clipboard!', 'success');
    });
}

// Copy referral code
function copyReferralCode() {
    navigator.clipboard.writeText(referralCode).then(() => {
        showNotification('Referral code copied to clipboard!', 'success');
    });
}

// Share functions
function shareOnFacebook() {
    const url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(referralLink)}`;
    window.open(url, '_blank', 'width=600,height=400');
}

function shareOnTwitter() {
    const text = `Join me on <?php echo SITE_NAME; ?> and earn amazing returns! Use my referral code: ${referralCode}`;
    const url = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(referralLink)}`;
    window.open(url, '_blank', 'width=600,height=400');
}

function shareOnWhatsApp() {
    const text = `Join me on <?php echo SITE_NAME; ?>! Use my referral link: ${referralLink}`;
    const url = `https://wa.me/?text=${encodeURIComponent(text)}`;
    window.open(url, '_blank');
}

function shareOnTelegram() {
    const text = `Join me on <?php echo SITE_NAME; ?>! Use my referral link: ${referralLink}`;
    const url = `https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=${encodeURIComponent(text)}`;
    window.open(url, '_blank');
}

function copyEmailTemplate() {
    const subject = `Join me on <?php echo SITE_NAME; ?>!`;
    const body = `
Hi,

I wanted to invite you to join <?php echo SITE_NAME; ?>. It's an amazing platform where you can grow your wealth through smart investments.

Here's why you should join:
• High returns on investments
• Daily profit payments
• Secure and reliable platform
• Excellent customer support

Use my referral link to get started:
${referralLink}

Or use my referral code during registration: ${referralCode}

You'll get a special bonus when you sign up using my link!

Best regards,
${'<?php echo htmlspecialchars($user["username"]); ?>'}
    `.trim();
    
    const mailtoLink = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = mailtoLink;
}

// Show QR Code
function showQRCode() {
    document.getElementById('qrModal').classList.remove('hidden');
    
    // Generate QR code if not already generated
    if (!document.getElementById('qrcode').hasChildNodes()) {
        new QRCode(document.getElementById('qrcode'), {
            text: referralLink,
            width: 200,
            height: 200,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });
    }
}

function closeQRModal() {
    document.getElementById('qrModal').classList.add('hidden');
}

// Send invitation
function sendInvitation(userId) {
    const email = prompt('Enter email address to send invitation:');
    if (email && email.includes('@')) {
        $.ajax({
            url: '../api/send-invitation.php',
            method: 'POST',
            data: { 
                user_id: userId,
                email: email,
                referral_link: referralLink
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
            }
        });
    }
}

// Withdraw bonus
function withdrawBonus() {
    if (availableBonus < 10) {
        showNotification('Minimum withdrawal amount is $10.00', 'error');
        return;
    }
    
    const amount = prompt(`Enter amount to withdraw (Available: $${availableBonus.toFixed(2)}):`, availableBonus.toFixed(2));
    
    if (amount && amount >= 10) {
        if (parseFloat(amount) > availableBonus) {
            showNotification('Amount exceeds available bonus balance', 'error');
            return;
        }
        
        $.ajax({
            url: '../api/withdraw-bonus.php',
            method: 'POST',
            data: { amount: amount },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

// Notification function (Tailwind style)
function showNotification(message, type = 'info') {
    const container = document.getElementById('notification-container');
    const notification = document.createElement('div');
    
    // Tailwind classes for styling
    const baseClasses = 'transform transition-all duration-300 ease-in-out translate-x-full rounded-lg shadow-lg p-4 flex items-center space-x-3 min-w-[300px] text-white';
    
    let typeClasses;
    let iconClass;
    
    if (type === 'success') {
        typeClasses = 'bg-gradient-to-r from-green-500 to-green-600';
        iconClass = 'fa-check-circle';
    } else if (type === 'error') {
        typeClasses = 'bg-gradient-to-r from-red-500 to-red-600';
        iconClass = 'fa-exclamation-circle';
    } else {
        typeClasses = 'bg-gradient-to-r from-blue-500 to-blue-600';
        iconClass = 'fa-info-circle';
    }
    
    notification.className = `${baseClasses} ${typeClasses}`;
    notification.innerHTML = `
        <i class="fas ${iconClass} text-xl"></i>
        <div class="flex-1">
            <p class="text-sm font-medium">${message}</p>
        </div>
        <button onclick="this.parentElement.remove()" class="text-white hover:text-gray-100">
            <i class="fas fa-times"></i>
        </button>
    `;

    container.appendChild(notification);

    // Animate in
    requestAnimationFrame(() => {
        notification.classList.remove('translate-x-full');
    });

    // Auto dismiss
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// Calculate potential earnings
function calculateEarnings() {
    const referrals = parseInt(prompt('How many referrals do you expect to get this month?', '5')) || 0;
    const avgDeposit = parseInt(prompt('Average deposit amount per referral? ($)', '100')) || 0;
    
    const signupBonus = referrals * referralBonus;
    const commissionEarnings = referrals * avgDeposit * commissionRate;
    const totalEarnings = signupBonus + commissionEarnings;
    
    const result = `
        Potential Earnings This Month:
        
        Expected Referrals: ${referrals}
        Average Deposit: $${avgDeposit}
        
        Signup Bonuses: $${signupBonus.toFixed(2)}
        Commission (${commissionRate * 100}%): $${commissionEarnings.toFixed(2)}
        
        Total Potential: $${totalEarnings.toFixed(2)}
        
        Start inviting friends now!
    `;
    
    alert(result);
}

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    // Add calculate earnings button
    const calculateBtn = document.createElement('button');
    calculateBtn.className = 'fixed bottom-4 left-4 bg-purple-600 text-white p-3 rounded-full shadow-lg hover:bg-purple-700 z-10';
    calculateBtn.innerHTML = '<i class="fas fa-calculator"></i>';
    calculateBtn.title = 'Calculate Potential Earnings';
    calculateBtn.onclick = calculateEarnings;
    document.body.appendChild(calculateBtn);
});

// Track referral clicks (for analytics)
function trackReferralClick(source) {
    $.ajax({
        url: '../api/track-referral-click.php',
        method: 'POST',
        data: {
            source: source,
            referral_code: referralCode
        }
    });
}

// Auto-track clicks on sharing buttons
document.querySelectorAll('[onclick*="shareOn"]').forEach(button => {
    const originalOnclick = button.getAttribute('onclick');
    const source = originalOnclick.match(/shareOn(\w+)/)[1];
    button.setAttribute('onclick', `trackReferralClick('${source}'); ${originalOnclick}`);
});
</script>

<style>
.qrcode canvas {
    border: 10px solid white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>

<?php require_once '../includes/footer.php'; ?>
