<?php
/**
 * User Referral Page
 */
$pageTitle = 'Referral Program';
require_once 'includes/header.php';

$referralPercent = (float)getSetting('referral_commission_percent', 10);
$referralLink = SITE_URL . '/user/register.php?ref=' . $user['referral_code'];

// Get referral stats
$referrals = dbFetchAll(
    "SELECT u.user_id, u.first_name, u.last_name, u.email, u.created_at,
            (SELECT SUM(amount) FROM transactions WHERE user_id = :uid AND type = 'referral_commission' AND description LIKE CONCAT('%', u.user_id, '%')) as earned
     FROM users u 
     WHERE u.referred_by = :code
     ORDER BY u.created_at DESC",
    ['uid' => $user['id'], 'code' => $user['referral_code']]
);

$totalReferrals = count($referrals);
$totalEarnedResult = dbFetch(
    "SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE user_id = :id AND type = 'referral_commission'",
    ['id' => $user['id']]
);
$totalEarned = $totalEarnedResult ? $totalEarnedResult['total'] : 0;

// Check if referral_commissions table exists
$pendingCommission = 0;
try {
    $tableCheck = db()->query("SHOW TABLES LIKE 'referral_commissions'")->fetch();
    if ($tableCheck) {
        $pendingCommissionResult = dbFetch(
            "SELECT COALESCE(SUM(amount), 0) as total FROM referral_commissions WHERE referrer_id = :id AND status = 'pending'",
            ['id' => $user['id']]
        );
        $pendingCommission = $pendingCommissionResult ? $pendingCommissionResult['total'] : 0;
    }
} catch (Exception $e) {
    // Table doesn't exist, use 0
}
?>

<style>
.referral-banner {
    background: linear-gradient(135deg, rgba(0, 208, 156, 0.15) 0%, rgba(59, 130, 246, 0.15) 100%);
    border: 1px solid rgba(0, 208, 156, 0.3);
    border-radius: var(--radius-lg);
    padding: 2rem;
    text-align: center;
    margin-bottom: 1.5rem;
}
.referral-banner h2 { margin-bottom: 0.5rem; }
.referral-banner p { color: var(--text-muted); margin-bottom: 1.5rem; }
.referral-link-box {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    padding: 1rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    max-width: 600px;
    margin: 0 auto;
}
.referral-link-box input {
    flex: 1;
    background: transparent;
    border: none;
    color: var(--text-primary);
    font-family: var(--font-mono);
    font-size: 0.9rem;
}
.share-buttons { display: flex; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
.share-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.125rem;
    cursor: pointer;
    border: none;
}
.share-btn.whatsapp { background: #25D366; }
.share-btn.telegram { background: #0088cc; }
.share-btn.twitter { background: #1DA1F2; }
.share-btn.facebook { background: #1877F2; }
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 1.5rem; }
@media (max-width: 768px) { .stats-grid { grid-template-columns: 1fr; } }
.how-it-works { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem; margin: 2rem 0; }
@media (max-width: 768px) { .how-it-works { grid-template-columns: 1fr; } }
.step-card { text-align: center; padding: 1.5rem; }
.step-number {
    width: 50px;
    height: 50px;
    background: var(--accent-green);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    font-weight: 700;
    margin: 0 auto 1rem;
}
.step-card h4 { margin-bottom: 0.5rem; }
.step-card p { color: var(--text-muted); font-size: 0.9rem; }
</style>

<div class="referral-banner">
    <h2><i class="fas fa-gift"></i> Earn <?= $referralPercent ?>% Commission</h2>
    <p>Invite friends and earn commission on their trading losses. Unlimited referrals!</p>
    
    <div class="referral-link-box">
        <input type="text" id="referralLink" value="<?= $referralLink ?>" readonly>
        <button class="btn btn-primary" onclick="copyReferralLink()">
            <i class="fas fa-copy"></i> Copy
        </button>
    </div>
    
    <div class="share-buttons">
        <button class="share-btn whatsapp" onclick="shareWhatsApp()"><i class="fab fa-whatsapp"></i></button>
        <button class="share-btn telegram" onclick="shareTelegram()"><i class="fab fa-telegram-plane"></i></button>
        <button class="share-btn twitter" onclick="shareTwitter()"><i class="fab fa-twitter"></i></button>
        <button class="share-btn facebook" onclick="shareFacebook()"><i class="fab fa-facebook-f"></i></button>
    </div>
</div>

<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-users"></i></div>
        <div class="stat-value"><?= $totalReferrals ?></div>
        <div class="stat-label">Total Referrals</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-coins"></i></div>
        <div class="stat-value text-green"><?= formatCurrency($totalEarned) ?></div>
        <div class="stat-label">Total Earned</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon yellow"><i class="fas fa-clock"></i></div>
        <div class="stat-value"><?= formatCurrency($pendingCommission) ?></div>
        <div class="stat-label">Pending Commission</div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h3 class="card-title">How It Works</h3>
    </div>
    <div class="card-body">
        <div class="how-it-works">
            <div class="step-card">
                <div class="step-number">1</div>
                <h4>Share Your Link</h4>
                <p>Share your unique referral link with friends, family, or on social media.</p>
            </div>
            <div class="step-card">
                <div class="step-number">2</div>
                <h4>Friends Sign Up</h4>
                <p>When someone registers using your link, they become your referral.</p>
            </div>
            <div class="step-card">
                <div class="step-number">3</div>
                <h4>Earn Commission</h4>
                <p>Earn <?= $referralPercent ?>% commission whenever your referrals lose trades.</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Your Referrals</h3>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Joined</th>
                        <th>Your Earnings</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($referrals as $ref): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="stat-icon blue" style="width: 36px; height: 36px; font-size: 0.8rem;">
                                    <?= strtoupper(substr($ref['first_name'] ?? $ref['email'], 0, 1)) ?>
                                </div>
                                <div>
                                    <div class="font-semibold"><?= htmlspecialchars(($ref['first_name'] ?? '') . ' ' . ($ref['last_name'] ?? '')) ?: 'User' ?></div>
                                    <div class="text-muted" style="font-size: 0.75rem;"><?= $ref['user_id'] ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="text-muted"><?= formatDateTime($ref['created_at'], 'd M Y') ?></td>
                        <td class="font-mono text-green"><?= formatCurrency($ref['earned'] ?? 0) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($referrals)): ?>
                    <tr>
                        <td colspan="3" class="text-center text-muted py-4">
                            No referrals yet. Share your link to start earning!
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
const referralLink = '<?= $referralLink ?>';
const shareText = 'Join <?= APP_NAME ?> and start trading! Use my referral link to sign up:';

function copyReferralLink() {
    document.getElementById('referralLink').select();
    navigator.clipboard.writeText(referralLink);
    showToast('Referral link copied!', 'success');
}

function shareWhatsApp() {
    window.open(`https://wa.me/?text=${encodeURIComponent(shareText + ' ' + referralLink)}`, '_blank');
}

function shareTelegram() {
    window.open(`https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=${encodeURIComponent(shareText)}`, '_blank');
}

function shareTwitter() {
    window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(referralLink)}`, '_blank');
}

function shareFacebook() {
    window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(referralLink)}`, '_blank');
}
</script>

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