<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include ('header.php');
$page_title = $site_data['web_name'] . " | Referral Program";

try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM referrals WHERE referrer_id = :user_id");
    $stmt->execute(['user_id' => $user['id']]);
    $total_referrals = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM referrals WHERE referrer_id = :user_id AND status = 'active'");
    $stmt->execute(['user_id' => $user['id']]);
    $active_referrals = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM referrals WHERE referrer_id = :user_id AND status = 'pending'");
    $stmt->execute(['user_id' => $user['id']]);
    $pending_referrals = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

    $stmt = $pdo->prepare("SELECT r.*, u.username, u.email, u.created_at as user_joined, u.first_activation FROM referrals r JOIN users u ON r.referred_user_id = u.id WHERE r.referrer_id = :user_id ORDER BY r.created_at DESC");
    $stmt->execute(['user_id' => $user['id']]);
    $referrals = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT re.*, u.username, t.amount as transaction_amount, t.created_at as transaction_date FROM referral_earnings re JOIN users u ON re.referred_user_id = u.id JOIN transactions t ON re.transaction_id = t.id WHERE re.referrer_id = :user_id ORDER BY re.created_at DESC LIMIT 20");
    $stmt->execute(['user_id' => $user['id']]);
    $earnings = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $total_referrals = $active_referrals = $pending_referrals = 0;
    $referrals = $earnings = [];
}

$referral_link = WEBSITE_URL . '/signup.php?ref=' . $user['referral_code'];
?>
<title><?php echo $page_title; ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}.anim-4{animation-delay:.26s}
.ref-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#6b23c2 100%);border:1px solid rgba(255,102,0,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.ref-hero::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(-45deg,transparent,transparent 35px,rgba(255,102,0,.012) 35px,rgba(255,102,0,.012) 36px);pointer-events:none}
.ref-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:16px;padding:20px;margin-bottom:14px}
.stat-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:13px;padding:14px}
.ref-table-row{display:grid;grid-template-columns:1fr 1fr 80px 90px;gap:10px;padding:11px 14px;border-bottom:1px solid var(--card-border);align-items:center;transition:background .15s}
.ref-table-row:hover{background:rgba(77,20,140,.03)}
.ref-table-row:last-child{border-bottom:none}
</style>

<div class="max-w-4xl mx-auto">

<!-- Hero -->
<style>
.ref-hero-inner {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column; /* stack on mobile */
    gap: 16px;
}
.ref-hero-left h2 {
    font-size: 1.1rem;
    font-weight: 800;
    color: white;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.ref-hero-left p {
    color: rgba(255,255,255,.55);
    font-size: .78rem;
}
.ref-hero-right {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
}
.ref-earnings-box {
    background: rgba(255,102,0,.15);
    border: 1px solid rgba(255,102,0,.25);
    border-radius: 10px;
    padding: 10px 16px;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
}
.ref-earnings-box p.label {
    font-size: .6rem;
    color: rgba(255,255,255,.6);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .06em;
    margin: 0;
}
.ref-earnings-box p.amount {
    font-weight: 800;
    color: #fbbf24;
    font-size: 1.1rem;
    font-family: monospace;
    margin: 0;
}
.ref-withdraw-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    padding: 11px 16px;
    border-radius: 10px;
    font-weight: 700;
    font-size: .82rem;
    text-decoration: none;
    width: 100%;
    box-sizing: border-box;
    text-align: center;
    transition: all .2s;
}
.ref-withdraw-btn.active {
    background: linear-gradient(135deg,#7c3aed,#a855f7);
    color: white;
    box-shadow: 0 3px 12px rgba(124,58,237,.35);
}
.ref-withdraw-btn.disabled {
    background: rgba(255,255,255,.1);
    color: rgba(255,255,255,.5);
    pointer-events: none;
    border: 1px solid rgba(255,255,255,.1);
    cursor: not-allowed;
}
/* ── Desktop: side by side ── */
@media (min-width: 540px) {
    .ref-hero-inner {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
    .ref-hero-left {
        flex: 1;
    }
    .ref-hero-right {
        width: auto;
        min-width: 180px;
        align-items: flex-end;
    }
    .ref-earnings-box {
        width: auto;
        min-width: 170px;
    }
    .ref-withdraw-btn {
        width: auto;
        min-width: 170px;
    }
}
</style>

<div class="ref-hero anim anim-1">
    <div style="position:absolute;width:160px;height:160px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(255,102,0,.15),transparent);top:-40px;right:-40px;pointer-events:none;"></div>

    <div class="ref-hero-inner">
        <!-- Left: Text -->
        <div class="ref-hero-left">
            <h2>
                <i class="fas fa-gift text-yellow-300 text-base"></i>
                Referral Program
            </h2>
            <p>Earn <strong style="color:#fbbf24;"><?php echo $site_data['refer_percent']; ?>% commission</strong> when your friends make their first deposit!</p>
        </div>

        <!-- Right: Earnings + Withdraw -->
        <div class="ref-hero-right">
            <div class="ref-earnings-box">
                <p class="label">Your Earnings</p>
                <p class="amount">₦<?php echo number_format($user['total_earnings'], 2); ?></p>
            </div>

            <?php
                $min_redeem_val = floatval($site_data['min_redeem'] ?? 10000);
                $ref_bal_val    = floatval($user['referral_balance']);
                $can_wd         = $ref_bal_val >= $min_redeem_val;
            ?>
            <a href="withdraw-referral.php"
               class="ref-withdraw-btn <?php echo $can_wd ? 'active' : 'disabled'; ?>">
                <i class="fas <?php echo $can_wd ? 'fa-money-bill-transfer' : 'fa-lock'; ?>"></i>
                <?php if ($can_wd): ?>
                    Withdraw ₦<?php echo number_format($ref_bal_val, 2); ?>
                <?php else: ?>
                    Need ₦<?php echo number_format($min_redeem_val, 2); ?> to Withdraw
                <?php endif; ?>
            </a>
        </div>
    </div>
</div>

<!-- Stat Cards -->
<div class="anim anim-1" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px;" class="sm:grid-cols-4">
    <div class="stat-card">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
            <div style="width:32px;height:32px;border-radius:8px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-coins text-purple-600 text-sm"></i></div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;">Total Earnings</p>
        </div>
        <p style="font-size:1.3rem;font-weight:800;color:var(--text-primary);font-family:monospace;">₦<?php echo number_format($user['total_earnings'],2); ?></p>
    </div>
    <div class="stat-card">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
            <div style="width:32px;height:32px;border-radius:8px;background:rgba(59,130,246,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-wallet text-blue-600 text-sm"></i></div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;">Available</p>
        </div>
        <p style="font-size:1.3rem;font-weight:800;color:var(--text-primary);font-family:monospace;">₦<?php echo number_format($user['referral_balance'],2); ?></p>
    </div>
    <div class="stat-card">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
            <div style="width:32px;height:32px;border-radius:8px;background:rgba(168,85,247,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-users text-purple-600 text-sm"></i></div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;">Total Referrals</p>
        </div>
        <p style="font-size:1.3rem;font-weight:800;color:var(--text-primary);"><?php echo $total_referrals; ?></p>
    </div>
    <div class="stat-card">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
            <div style="width:32px;height:32px;border-radius:8px;background:rgba(245,158,11,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-user-check text-amber-600 text-sm"></i></div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:600;text-transform:uppercase;">Active</p>
        </div>
        <p style="font-size:1.3rem;font-weight:800;color:var(--text-primary);"><?php echo $active_referrals; ?></p>
    </div>
</div>

<!-- Referral Link -->
<div class="ref-card anim anim-2">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center;"><i class="fas fa-link" style="font-size:.72rem;color:#4D148C;"></i></span>
        Your Referral Link
    </p>
    <div style="background:var(--btn-bg);border:1.5px solid var(--card-border);border-radius:11px;padding:12px 14px;display:flex;align-items:center;gap:10px;margin-bottom:12px;">
        <input type="text" id="referralLink" value="<?php echo $referral_link; ?>" readonly
               style="flex:1;background:transparent;color:var(--text-primary);font-size:.75rem;font-family:monospace;border:none;outline:none;min-width:0;">
        <button onclick="copyReferralLink()" style="background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.75rem;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;display:flex;align-items:center;gap:6px;flex-shrink:0;transition:all .2s;">
            <i class="fas fa-copy text-xs"></i><span id="copyText">Copy</span>
        </button>
    </div>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;" class="sm:grid-cols-4">
        <a href="https://wa.me/?text=<?php echo urlencode('Join '.$site_data['web_name'].' and start earning! '.$referral_link); ?>" target="_blank"
           style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;background:rgba(37,211,102,.1);border:1px solid rgba(37,211,102,.2);color:#16a34a;border-radius:10px;font-weight:700;font-size:.78rem;text-decoration:none;transition:all .2s;">
            <i class="fab fa-whatsapp text-base"></i>WhatsApp
        </a>
        <a href="https://twitter.com/intent/tweet?text=<?php echo urlencode('Join '.$site_data['web_name'].'! '.$referral_link); ?>" target="_blank"
           style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;background:rgba(14,165,233,.08);border:1px solid rgba(14,165,233,.18);color:#0ea5e9;border-radius:10px;font-weight:700;font-size:.78rem;text-decoration:none;transition:all .2s;">
            <i class="fab fa-twitter text-base"></i>Twitter
        </a>
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($referral_link); ?>" target="_blank"
           style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.18);color:#3b82f6;border-radius:10px;font-weight:700;font-size:.78rem;text-decoration:none;transition:all .2s;">
            <i class="fab fa-facebook text-base"></i>Facebook
        </a>
        <a href="https://t.me/share/url?url=<?php echo urlencode($referral_link); ?>&text=<?php echo urlencode('Join '.$site_data['web_name'].'!'); ?>" target="_blank"
           style="display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;background:rgba(14,150,212,.08);border:1px solid rgba(14,150,212,.18);color:#0e96d4;border-radius:10px;font-weight:700;font-size:.78rem;text-decoration:none;transition:all .2s;">
            <i class="fab fa-telegram text-base"></i>Telegram
        </a>
    </div>
</div>

<!-- How It Works -->
<div class="ref-card anim anim-3">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:16px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(245,158,11,.1);display:inline-flex;align-items:center;justify-content:center;"><i class="fas fa-lightbulb" style="font-size:.72rem;color:#d97706;"></i></span>
        How It Works
    </p>
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;text-align:center;">
        <?php foreach([['1','Share Your Link','Copy and share your unique referral link','#4D148C'],['2','They Sign Up','Friend creates account via your link','#1d4ed8'],['3','Earn Commission','Get '.$site_data['refer_percent'].'% of their first deposit','#9333ea']] as [$n,$title,$desc,$c]): ?>
        <div>
            <div style="width:44px;height:44px;border-radius:50%;background:rgba(77,20,140,.08);border:1px solid rgba(77,20,140,.15);display:flex;align-items:center;justify-content:center;margin:0 auto 10px;font-weight:800;font-size:1rem;color:#4D148C;"><?php echo $n; ?></div>
            <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);margin-bottom:4px;"><?php echo $title; ?></p>
            <p style="font-size:.7rem;color:var(--text-muted);line-height:1.4;"><?php echo $desc; ?></p>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Referral List -->
<div class="ref-card anim anim-4">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(168,85,247,.1);display:inline-flex;align-items:center;justify-content:center;"><i class="fas fa-users" style="font-size:.72rem;color:#9333ea;"></i></span>
        Your Referrals
    </p>
    <?php if (empty($referrals)): ?>
    <div style="text-align:center;padding:32px 0;">
        <div style="width:52px;height:52px;border-radius:50%;background:rgba(77,20,140,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;">
            <i class="fas fa-user-plus" style="font-size:1.2rem;color:var(--text-muted);"></i>
        </div>
        <p style="color:var(--text-muted);font-size:.82rem;">No referrals yet</p>
        <p style="font-size:.72rem;color:var(--text-muted);margin-top:4px;">Share your referral link to start earning</p>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;">
        <!-- Header -->
        <div style="display:grid;grid-template-columns:1fr 1fr 80px 90px;gap:10px;padding:8px 14px;border-bottom:1.5px solid var(--card-border);">
            <?php foreach(['User','Joined','Status','Earnings'] as $h): ?>
            <p style="font-size:.65rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.08em;"><?php echo $h; ?></p>
            <?php endforeach; ?>
        </div>
        <?php foreach ($referrals as $ref): ?>
        <div class="ref-table-row">
            <div style="display:flex;align-items:center;gap:8px;min-width:0;">
                <div style="width:30px;height:30px;border-radius:50%;background:rgba(77,20,140,.1);color:#4D148C;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.78rem;flex-shrink:0;"><?php echo strtoupper(substr($ref['username'],0,1)); ?></div>
                <div style="min-width:0;">
                    <p style="font-weight:600;font-size:.78rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($ref['username']); ?></p>
                    <p style="font-size:.65rem;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($ref['email']); ?></p>
                </div>
            </div>
            <p style="font-size:.75rem;color:var(--text-muted);"><?php echo date('M d, Y', strtotime($ref['user_joined'])); ?></p>
            <div>
                <span style="font-size:.65rem;font-weight:700;padding:3px 9px;border-radius:99px;<?php echo $ref['status']=='active'?'background:rgba(77,20,140,.1);color:#4D148C;':'background:rgba(245,158,11,.1);color:#d97706;'; ?>">
                    <?php echo ucfirst($ref['status']); ?>
                </span>
            </div>
            <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);font-family:monospace;">₦<?php echo number_format($ref['earnings'],2); ?></p>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Earnings History -->
<?php if (!empty($earnings)): ?>
<div class="ref-card anim anim-4">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center;"><i class="fas fa-money-bill-trend-up" style="font-size:.72rem;color:#4D148C;"></i></span>
        Earnings History
    </p>
    <div style="display:flex;flex-direction:column;gap:8px;">
        <?php foreach ($earnings as $earning): ?>
        <div style="border:1px solid var(--card-border);border-radius:11px;padding:12px;display:flex;align-items:center;justify-content:space-between;gap:10px;transition:border-color .2s;" onmouseover="this.style.borderColor='rgba(77,20,140,.25)'" onmouseout="this.style.borderColor=''">
            <div style="display:flex;align-items:center;gap:10px;">
                <div style="width:36px;height:36px;border-radius:9px;background:rgba(77,20,140,.08);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i class="fas fa-arrow-trend-up text-emerald-600 text-sm"></i>
                </div>
                <div>
                    <p style="font-weight:600;font-size:.8rem;color:var(--text-primary);">Commission from <?php echo htmlspecialchars($earning['username']); ?></p>
                    <p style="font-size:.68rem;color:var(--text-muted);margin-top:1px;"><?php echo date('M d, Y — h:i A', strtotime($earning['transaction_date'])); ?></p>
                </div>
            </div>
            <div style="text-align:right;flex-shrink:0;">
                <p style="font-weight:700;font-size:.85rem;color:#4D148C;">+₦<?php echo number_format($earning['commission_amount'],2); ?></p>
                <p style="font-size:.65rem;color:var(--text-muted);"><?php echo $earning['commission_percent']; ?>% of ₦<?php echo number_format($earning['deposit_amount'],2); ?></p>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

</div><!-- /max-w -->

<script>
function copyReferralLink(){
    const input=document.getElementById('referralLink');
    const txt=document.getElementById('copyText');
    navigator.clipboard.writeText(input.value).then(()=>{
        txt.textContent='Copied!';
        setTimeout(()=>txt.textContent='Copy',2000);
    }).catch(()=>{input.select();document.execCommand('copy');txt.textContent='Copied!';setTimeout(()=>txt.textContent='Copy',2000);});
}
</script>

<?php include ('footer.php'); ?>