<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require_once 'db.php';

$user_id = $_SESSION['user_id'];

// Get user's data
$user_query  = "SELECT * FROM users WHERE id='$user_id'";
$user_result = mysqli_query($conn, $user_query);
$user_data   = mysqli_fetch_assoc($user_result);

// Generate referral code if missing
if (empty($user_data['referral_code'])) {
    do {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        for ($i = 0; $i < 5; $i++) {
            $code .= $characters[rand(0, strlen($characters) - 1)];
        }
        $check  = "SELECT id FROM users WHERE referral_code='$code'";
        $result = mysqli_query($conn, $check);
    } while (mysqli_num_rows($result) > 0);

    mysqli_query($conn, "UPDATE users SET referral_code='$code' WHERE id='$user_id'");
    $user_data['referral_code'] = $code;
}

// ── Commission rates (must match commission_settings table) ───────────────────
$commission_rates = [
    'level1' => 15.00,
    'level2' => 6.00,
    'level3' => 2.00,
];

// ── Level 1 referrals ─────────────────────────────────────────────────────────
$level1_result  = mysqli_query($conn,
    "SELECT * FROM users WHERE referrer_id='$user_id' ORDER BY created_at DESC");
$level1_count   = mysqli_num_rows($level1_result);
$level1_members = [];
while ($member = mysqli_fetch_assoc($level1_result)) {
    $level1_members[] = $member;
}

// ── Level 2 referrals ─────────────────────────────────────────────────────────
$level2_members = [];
$level2_count   = 0;
foreach ($level1_members as $l1) {
    $res = mysqli_query($conn,
        "SELECT * FROM users WHERE referrer_id='{$l1['id']}' ORDER BY created_at DESC");
    while ($member = mysqli_fetch_assoc($res)) {
        $member['referred_by'] = $l1['referral_code'] ?? $l1['phone_number'];
        $level2_members[] = $member;
        $level2_count++;
    }
}

// ── Level 3 referrals ─────────────────────────────────────────────────────────
$level3_members = [];
$level3_count   = 0;
foreach ($level2_members as $l2) {
    $res = mysqli_query($conn,
        "SELECT * FROM users WHERE referrer_id='{$l2['id']}' ORDER BY created_at DESC");
    while ($member = mysqli_fetch_assoc($res)) {
        $member['referred_by'] = $l2['referral_code'] ?? $l2['phone_number'];
        $level3_members[] = $member;
        $level3_count++;
    }
}

$total_team = $level1_count + $level2_count + $level3_count;

// ── Earnings from referral_commissions ───────────────────────────────────────
$earnings_result = mysqli_query($conn,
    "SELECT
        SUM(CASE WHEN level=1 THEN amount ELSE 0 END) AS level1_earnings,
        SUM(CASE WHEN level=2 THEN amount ELSE 0 END) AS level2_earnings,
        SUM(CASE WHEN level=3 THEN amount ELSE 0 END) AS level3_earnings,
        SUM(amount) AS total_earnings
     FROM referral_commissions
     WHERE user_id='$user_id'");
$earnings_data   = mysqli_fetch_assoc($earnings_result);
$level1_earnings = $earnings_data['level1_earnings'] ?? 0;
$level2_earnings = $earnings_data['level2_earnings'] ?? 0;
$level3_earnings = $earnings_data['level3_earnings'] ?? 0;
$total_earnings  = $earnings_data['total_earnings']  ?? 0;

function getMemberStats($conn, $member_id) {
    $res = mysqli_query($conn,
        "SELECT COUNT(*) AS total_investments, SUM(amount) AS total_invested
         FROM investments WHERE user_id='$member_id'");
    return mysqli_fetch_assoc($res);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Team - MaxTrade</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background-color: #000; color: #fff;
            font-family: Arial, sans-serif;
            padding-bottom: 70px; font-size: 13px;
        }
        .header {
            background: #111; padding: 12px 15px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.5);
        }
        .header h1 { color: #fff; font-size: 18px; }
        .container { padding: 12px; }

        .referral-card {
            background: #111; border-radius: 10px;
            padding: 15px; margin-bottom: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
        }
        .referral-card h3 { color: #FFD700; margin-bottom: 10px; font-size: 14px; }

        .referral-code-display {
            background: #000; padding: 15px;
            border: 2px solid #FFD700; border-radius: 8px;
            margin: 10px 0; text-align: center;
        }
        .code-label { font-size: 11px; color: #888; margin-bottom: 5px; }
        .code-value {
            font-size: 28px; font-weight: bold;
            color: #FFD700; letter-spacing: 3px;
            font-family: 'Courier New', monospace;
        }

        .referral-link-container {
            background: #000; padding: 10px;
            border: 1px solid #333; border-radius: 5px;
            margin: 8px 0; display: flex; align-items: center; gap: 8px;
        }
        .referral-link { flex: 1; font-size: 11px; color: #fff; word-break: break-all; }
        .copy-icon-btn {
            background: #FFD700; border: none;
            padding: 8px 12px; border-radius: 5px;
            cursor: pointer; color: #000; font-size: 14px;
        }
        .copy-icon-btn:hover { background: #FFA500; }

        .earnings-grid {
            display: grid; grid-template-columns: repeat(2, 1fr);
            gap: 10px; margin: 12px 0;
        }
        .earnings-box {
            background: #000; border: 1px solid #333;
            border-radius: 8px; padding: 12px; text-align: center;
        }
        .earnings-box.total { grid-column: 1 / -1; border-color: #FFD700; }
        .earnings-amount { font-size: 18px; font-weight: bold; color: #FFD700; margin: 5px 0; }
        .earnings-label { font-size: 10px; color: #888; }

        .commission-info {
            background: #000; border: 1px solid #333;
            border-radius: 5px; padding: 10px; margin: 10px 0;
        }
        .commission-row {
            display: flex; justify-content: space-between;
            padding: 5px 0; font-size: 11px;
        }
        .commission-row span:first-child { color: #888; }
        .commission-row span:last-child  { color: #FFD700; font-weight: bold; }

        .stats-grid {
            display: grid; grid-template-columns: repeat(3, 1fr);
            gap: 8px; margin: 12px 0;
        }
        .stat-box {
            background: #000; border: 1px solid #333;
            border-radius: 5px; padding: 10px 8px; text-align: center;
        }
        .stat-number { font-size: 20px; font-weight: bold; color: #FFD700; }
        .stat-label  { font-size: 9px; color: #888; margin-top: 3px; }

        .tabs {
            display: flex; gap: 8px; margin: 12px 0; overflow-x: auto;
        }
        .tab {
            flex: 1; min-width: 80px; padding: 10px;
            background: #000; border: 1px solid #333;
            border-radius: 5px; text-align: center;
            cursor: pointer; transition: all 0.3s; font-size: 11px;
        }
        .tab.active { background: #FFD700; color: #000; border-color: #FFD700; }
        .tab-count { font-size: 16px; font-weight: bold; display: block; margin-bottom: 3px; }

        .member-list {
            background: #111; border-radius: 10px;
            padding: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.5);
        }
        .member-list h3 {
            color: #FFD700; margin-bottom: 12px; font-size: 14px;
            display: flex; align-items: center; gap: 8px;
        }
        .member-item {
            background: #000; padding: 12px;
            border: 1px solid #333; border-radius: 5px; margin-bottom: 8px;
        }
        .member-header {
            display: flex; justify-content: space-between;
            align-items: flex-start; margin-bottom: 8px;
        }
        .member-phone { font-weight: bold; color: #FFD700; font-size: 12px; }
        .member-code {
            font-size: 10px; color: #888;
            font-family: 'Courier New', monospace; margin-top: 2px;
        }
        .member-badge {
            background: #FFD700; color: #000;
            padding: 3px 8px; border-radius: 3px;
            font-size: 9px; font-weight: bold;
        }
        .member-email { color: #888; font-size: 11px; margin: 3px 0; }
        .member-stats {
            display: flex; gap: 15px;
            margin-top: 8px; padding-top: 8px;
            border-top: 1px solid #333; font-size: 10px;
        }
        .member-stat { display: flex; align-items: center; gap: 5px; }
        .member-stat i { color: #FFD700; }
        .member-stat-value { color: #fff; font-weight: bold; }
        .referred-by { font-size: 10px; color: #666; margin-top: 3px; }

        .no-members {
            text-align: center; padding: 30px 20px;
            color: #888; font-size: 12px;
        }
        .no-members i { font-size: 40px; margin-bottom: 10px; display: block; opacity: 0.3; }

        .tab-content { display: none; }
        .tab-content.active { display: block; }

        .share-buttons {
            display: grid; grid-template-columns: repeat(2, 1fr);
            gap: 8px; margin-top: 10px;
        }
        .share-btn {
            padding: 8px; border: 1px solid #333;
            border-radius: 5px; background: #000;
            color: #FFD700; text-align: center;
            cursor: pointer; font-size: 11px;
            display: flex; align-items: center;
            justify-content: center; gap: 5px;
            transition: all 0.3s;
        }
        .share-btn:hover { background: #111; border-color: #FFD700; }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-users"></i> My Team & Earnings</h1>
    </div>

    <div class="container">

        <!-- Earnings Summary -->
        <div class="referral-card">
            <h3><i class="fas fa-wallet"></i> Total Earnings</h3>
            <div class="earnings-grid">
                <div class="earnings-box">
                    <div class="earnings-label">Level 1 (<?php echo $commission_rates['level1']; ?>%)</div>
                    <div class="earnings-amount">ZMW <?php echo number_format($level1_earnings, 2); ?></div>
                </div>
                <div class="earnings-box">
                    <div class="earnings-label">Level 2 (<?php echo $commission_rates['level2']; ?>%)</div>
                    <div class="earnings-amount">ZMW <?php echo number_format($level2_earnings, 2); ?></div>
                </div>
                <div class="earnings-box">
                    <div class="earnings-label">Level 3 (<?php echo $commission_rates['level3']; ?>%)</div>
                    <div class="earnings-amount">ZMW <?php echo number_format($level3_earnings, 2); ?></div>
                </div>
                <div class="earnings-box total">
                    <div class="earnings-label">Total Commission Earned</div>
                    <div class="earnings-amount" style="font-size:22px;">ZMW <?php echo number_format($total_earnings, 2); ?></div>
                </div>
            </div>

            <div class="commission-info">
                <div class="commission-row">
                    <span><i class="fas fa-info-circle"></i> Commission Rates</span>
                    <span></span>
                </div>
                <div class="commission-row">
                    <span>Direct Referrals (Level 1)</span>
                    <span><?php echo $commission_rates['level1']; ?>%</span>
                </div>
                <div class="commission-row">
                    <span>2nd Generation (Level 2)</span>
                    <span><?php echo $commission_rates['level2']; ?>%</span>
                </div>
                <div class="commission-row">
                    <span>3rd Generation (Level 3)</span>
                    <span><?php echo $commission_rates['level3']; ?>%</span>
                </div>
            </div>
        </div>

        <!-- Referral Code & Link -->
        <div class="referral-card">
            <h3><i class="fas fa-gift"></i> Your Referral Code</h3>
            <div class="referral-code-display">
                <div class="code-label">Share this code with friends</div>
                <div class="code-value" id="referralCode"><?php echo $user_data['referral_code']; ?></div>
            </div>
            <button class="copy-icon-btn" onclick="copyCode()" style="width:100%;padding:10px;margin-top:5px;">
                <i class="fas fa-copy"></i> Copy Code
            </button>

            <h3 style="margin-top:20px;"><i class="fas fa-link"></i> Your Referral Link</h3>
            <div class="referral-link-container">
                <div class="referral-link" id="referralLink">https://pvp360.us/zambia/register.php?ref=<?php echo $user_data['referral_code']; ?></div>
                <button class="copy-icon-btn" onclick="copyReferral()">
                    <i class="fas fa-copy"></i>
                </button>
            </div>

            <div class="share-buttons">
                <div class="share-btn" onclick="shareWhatsApp()">
                    <i class="fab fa-whatsapp"></i> WhatsApp
                </div>
                <div class="share-btn" onclick="shareSMS()">
                    <i class="fas fa-sms"></i> SMS
                </div>
                <div class="share-btn" onclick="shareEmail()">
                    <i class="fas fa-envelope"></i> Email
                </div>
                <div class="share-btn" onclick="shareOther()">
                    <i class="fas fa-share-alt"></i> More
                </div>
            </div>
        </div>

        <!-- Team Statistics -->
        <div class="referral-card">
            <h3><i class="fas fa-chart-bar"></i> Team Statistics</h3>
            <div class="stats-grid">
                <div class="stat-box">
                    <div class="stat-number"><?php echo $level1_count; ?></div>
                    <div class="stat-label">Level 1</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?php echo $level2_count; ?></div>
                    <div class="stat-label">Level 2</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?php echo $level3_count; ?></div>
                    <div class="stat-label">Level 3</div>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="tabs">
            <div class="tab active" onclick="showTab('all', event)">
                <span class="tab-count"><?php echo $total_team; ?></span>All Team
            </div>
            <div class="tab" onclick="showTab('level1', event)">
                <span class="tab-count"><?php echo $level1_count; ?></span>Level 1
            </div>
            <div class="tab" onclick="showTab('level2', event)">
                <span class="tab-count"><?php echo $level2_count; ?></span>Level 2
            </div>
            <div class="tab" onclick="showTab('level3', event)">
                <span class="tab-count"><?php echo $level3_count; ?></span>Level 3
            </div>
        </div>

        <?php
        // Reusable member card renderer
        function renderMember($conn, $member, $badge_color, $level_label) {
            $stats = getMemberStats($conn, $member['id']);
            $badge_style = $badge_color !== '#FFD700'
                ? 'style="background:' . $badge_color . ';"' : '';
            ?>
            <div class="member-item">
                <div class="member-header">
                    <div>
                        <div class="member-phone">
                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($member['phone_number']); ?>
                        </div>
                        <?php if (!empty($member['referral_code'])): ?>
                            <div class="member-code">Code: <?php echo htmlspecialchars($member['referral_code']); ?></div>
                        <?php endif; ?>
                        <div class="member-email"><?php echo htmlspecialchars($member['email']); ?></div>
                        <?php if (!empty($member['referred_by'])): ?>
                            <div class="referred-by">via <?php echo htmlspecialchars($member['referred_by']); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="member-badge" <?php echo $badge_style; ?>><?php echo $level_label; ?></div>
                </div>
                <div class="member-stats">
                    <div class="member-stat">
                        <i class="fas fa-chart-line"></i>
                        <span class="member-stat-value"><?php echo $stats['total_investments'] ?? 0; ?></span>
                        <span>investments</span>
                    </div>
                    <div class="member-stat">
                        <i class="fas fa-coins"></i>
                        <span class="member-stat-value">ZMW <?php echo number_format($stats['total_invested'] ?? 0, 0); ?></span>
                        <span>invested</span>
                    </div>
                </div>
            </div>
            <?php
        }
        ?>

        <!-- All Members Tab -->
        <div id="all" class="tab-content active">
            <div class="member-list">
                <h3><i class="fas fa-users"></i> All Team Members</h3>
                <?php if ($total_team > 0): ?>
                    <?php foreach ($level1_members as $m) renderMember($conn, $m, '#FFD700',  'L1'); ?>
                    <?php foreach ($level2_members as $m) renderMember($conn, $m, '#FFA500',  'L2'); ?>
                    <?php foreach ($level3_members as $m) renderMember($conn, $m, '#FF6347',  'L3'); ?>
                <?php else: ?>
                    <div class="no-members">
                        <i class="fas fa-user-friends"></i>
                        <div>No team members yet</div>
                        <div style="margin-top:8px;">Share your referral code to start building your team!</div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Level 1 Tab -->
        <div id="level1" class="tab-content">
            <div class="member-list">
                <h3><i class="fas fa-users"></i> Level 1 — Direct Referrals (<?php echo $commission_rates['level1']; ?>%)</h3>
                <?php if ($level1_count > 0): ?>
                    <?php foreach ($level1_members as $m) renderMember($conn, $m, '#FFD700', 'L1'); ?>
                <?php else: ?>
                    <div class="no-members"><i class="fas fa-user-plus"></i><div>No direct referrals yet</div></div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Level 2 Tab -->
        <div id="level2" class="tab-content">
            <div class="member-list">
                <h3><i class="fas fa-users"></i> Level 2 — 2nd Generation (<?php echo $commission_rates['level2']; ?>%)</h3>
                <?php if ($level2_count > 0): ?>
                    <?php foreach ($level2_members as $m) renderMember($conn, $m, '#FFA500', 'L2'); ?>
                <?php else: ?>
                    <div class="no-members"><i class="fas fa-user-friends"></i><div>No level 2 referrals yet</div></div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Level 3 Tab -->
        <div id="level3" class="tab-content">
            <div class="member-list">
                <h3><i class="fas fa-users"></i> Level 3 — 3rd Generation (<?php echo $commission_rates['level3']; ?>%)</h3>
                <?php if ($level3_count > 0): ?>
                    <?php foreach ($level3_members as $m) renderMember($conn, $m, '#FF6347', 'L3'); ?>
                <?php else: ?>
                    <div class="no-members"><i class="fas fa-user-friends"></i><div>No level 3 referrals yet</div></div>
                <?php endif; ?>
            </div>
        </div>

    </div><!-- /.container -->

    <script>
        function showTab(tabName, event) {
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.closest('.tab').classList.add('active');
        }

        function copyCode() {
            const text = document.getElementById('referralCode').innerText;
            navigator.clipboard.writeText(text)
                .then(() => alert('Referral code copied: ' + text))
                .catch(() => fallbackCopy(text, 'Referral code copied: ' + text));
        }

        function copyReferral() {
            const text = document.getElementById('referralLink').innerText;
            navigator.clipboard.writeText(text)
                .then(() => alert('Referral link copied!'))
                .catch(() => fallbackCopy(text, 'Referral link copied!'));
        }

        function fallbackCopy(text, msg) {
            const el = document.createElement('textarea');
            el.value = text;
            document.body.appendChild(el);
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);
            alert(msg);
        }

        function shareWhatsApp() {
            const link = document.getElementById('referralLink').innerText;
            const code = document.getElementById('referralCode').innerText;
            const msg  = encodeURIComponent(
                'Join MaxTrade and start earning!\n\nUse my referral code: ' + code +
                '\n\nOr click this link: ' + link + '\n\nLet\'s grow together!');
            window.open('https://wa.me/?text=' + msg, '_blank');
        }

        function shareSMS() {
            const link = document.getElementById('referralLink').innerText;
            const code = document.getElementById('referralCode').innerText;
            window.location.href = 'sms:?body=' +
                encodeURIComponent('Join MaxTrade! Use code: ' + code + ' or link: ' + link);
        }

        function shareEmail() {
            const link    = document.getElementById('referralLink').innerText;
            const code    = document.getElementById('referralCode').innerText;
            const subject = encodeURIComponent('Join MaxTrade - Invitation');
            const body    = encodeURIComponent(
                'Hi,\n\nI\'d like to invite you to join MaxTrade.\n\n' +
                'Referral code: ' + code + '\n\nDirect link:\n' + link);
            window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
        }

        function shareOther() {
            const link = document.getElementById('referralLink').innerText;
            const code = document.getElementById('referralCode').innerText;
            if (navigator.share) {
                navigator.share({ title: 'Join MaxTrade', text: 'Use code: ' + code, url: link })
                    .catch(() => copyReferral());
            } else {
                copyReferral();
            }
        }

        document.querySelector('.nav-item[href="team.php"]')?.classList.add('active');
    </script>
    <?php include 'bottom-nav.php'; ?>
</body>
</html>