<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <title>Invite Friends - CV111</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    }

    body {
      background-color: #f4f6f9;
      display: flex;
      justify-content: center;
      min-height: 100vh;
    }

    .app-container {
      width: 100%;
      max-width: 420px;
      background-color: #ffffff;
      min-height: 100vh;
      padding-bottom: 30px;
    }

    /* Header */
    .header {
      background-color: #064038;
      color: #ffb700;
      display: flex;
      align-items: center;
      padding: 16px 20px;
      position: relative;
    }

    .back-btn {
      color: #ffb700;
      font-size: 18px;
      text-decoration: none;
      position: absolute;
      left: 20px;
    }

    .header-title {
      width: 100%;
      text-align: center;
      font-size: 20px;
      font-weight: 700;
      letter-spacing: 0.3px;
    }

    /* Tabs */
    .tabs {
      display: flex;
      justify-content: space-around;
      background-color: #ffffff;
      border-bottom: 1px solid #e2e8f0;
    }

    .tab {
      padding: 12px 0;
      font-size: 15px;
      color: #2c3e50;
      font-weight: 500;
      cursor: pointer;
      position: relative;
      flex: 1;
      text-align: center;
    }

    .tab.active { color: #1a8cff; font-weight: 600; }

    .tab.active::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 3px;
      background-color: #1a8cff;
      border-radius: 2px;
    }

    /* Content Area */
    .content { padding: 16px; }

    /* Stats Grid */
    .stats-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      margin-bottom: 16px;
    }

    .stat-card {
      border-radius: 8px;
      padding: 14px 10px;
      text-align: center;
      color: #ffffff;
    }

    .card-blue { background: linear-gradient(135deg, #74c0ff, #1e88e5); }
    .card-purple { background: linear-gradient(135deg, #b388ff, #7c4dff); }
    .card-purple-light { background: linear-gradient(135deg, #b388ff, #8a53ff); }
    .card-cyan { background: linear-gradient(135deg, #64b5f6, #00b0ff); }

    .stat-title { font-size: 13px; font-weight: 500; opacity: 0.95; margin-bottom: 6px; }
    .stat-value { font-size: 22px; font-weight: 700; }

    /* Share Box */
    .share-box {
      background-color: #eef3fb;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 20px;
    }

    .share-title { color: #3b2c82; font-weight: 700; font-size: 14px; margin-bottom: 10px; }

    .qr-container { display: flex; gap: 10px; margin-bottom: 12px; }
    .qr-left { display: flex; flex-direction: column; align-items: center; }

    .qr-code {
      width: 70px;
      height: 70px;
      background-color: #fff;
      padding: 4px;
      border-radius: 4px;
    }

    .save-btn {
      background-color: #3b2c82;
      color: #ffffff;
      font-size: 8px;
      padding: 4px 6px;
      border-radius: 4px;
      margin-top: 4px;
      text-align: center;
      white-space: nowrap;
      cursor: pointer;
      border: none;
    }

    .link-input-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      background-color: #ffffff;
      border-radius: 20px;
      padding: 6px 8px 6px 14px;
      height: 38px;
      align-self: center;
    }

    .link-text {
      flex: 1;
      font-size: 11px;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-weight: 500;
    }

    .copy-btn {
      background-color: #3b2c82;
      color: #fff;
      width: 26px;
      height: 26px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      cursor: pointer;
      border: none;
      flex-shrink: 0;
    }

    /* Social Icons */
    .social-icons { display: flex; justify-content: space-between; gap: 6px; }

    .social-icon {
      width: 38px;
      height: 38px;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      font-size: 18px;
      text-decoration: none;
    }

    .bg-fb { background-color: #4267B2; }
    .bg-x { background-color: #000000; }
    .bg-tg { background-color: #0088cc; }
    .bg-wa { background-color: #25D366; }
    .bg-chat { background-color: #5cc262; }
    .bg-line { background-color: #00B900; }
    .bg-threads { background-color: #000000; }

    /* Highlights Section */
    .promo-section { text-align: center; margin: 20px 0; }
    .promo-title { color: #1e1b4b; font-size: 18px; font-weight: 800; margin-bottom: 16px; }
    .promo-sub { color: #00c853; font-size: 15px; font-weight: 700; margin-bottom: 12px; }
    .highlight-yellow { color: #ffaa00; font-size: 17px; }

    /* Team / Downline Section (রিয়েল ডাটা) */
    .team-section {
      background: #f4f6f9;
      border-radius: 10px;
      padding: 14px;
      margin: 18px 0;
    }
    .team-section .sec-title { font-size: 13px; font-weight: 700; color: #064038; margin-bottom: 10px; }
    .team-row {
      display: flex; align-items: center; justify-content: space-between;
      padding: 10px 0; border-bottom: 1px solid #e2e8f0; font-size: 12px;
    }
    .team-row:last-child { border-bottom: none; }

    /* Table */
    .table-container { width: 100%; overflow-x: auto; margin-top: 15px; }
    table { width: 100%; border-collapse: collapse; text-align: center; font-size: 12px; }
    th, td { border: 1px solid #111; padding: 10px 4px; color: #111; font-weight: 500; }
    th { font-weight: 600; }
  </style>
</head>
<body>
<?php $pt = __DIR__ . '/page_transition.php'; if (file_exists($pt)) { include $pt; } ?>

  <div class="app-container">
    <!-- Header -->
    <div class="header">
      <a href="/newprofile.php" class="back-btn"><i class="fa-solid fa-chevron-left"></i></a>
      <div class="header-title">Invite Friends</div>
    </div>

    <!-- Tabs -->
    <div class="tabs">
      <div class="tab active">Overview</div>
      <div class="tab" onclick="window.location.href='/newrewardcenter.php'">Rewards</div>
      <div class="tab" onclick="window.location.href='/newcommission.php'">Earnings</div>
      <div class="tab" onclick="window.location.href='/newcommission.php'">Records</div>
    </div>

    <div class="content">
      <!-- Stats Cards (রিয়েল ডাটা) -->
      <div class="stats-grid">
        <div class="stat-card card-blue">
          <div class="stat-title">Today's Income</div>
          <div class="stat-value" id="todayIncome">৳ 0.00</div>
        </div>
        <div class="stat-card card-purple">
          <div class="stat-title">Yesterday's Income</div>
          <div class="stat-value" id="yesterdayIncome">৳ 0.00</div>
        </div>
        <div class="stat-card card-purple-light">
          <div class="stat-title">Registers</div>
          <div class="stat-value" id="totalReferrals">0</div>
        </div>
        <div class="stat-card card-cyan">
          <div class="stat-title">Valid Referral</div>
          <div class="stat-value" id="activeReferrals">0</div>
        </div>
      </div>

      <!-- Share Box -->
      <div class="share-box">
        <div class="share-title">Share with your friends</div>

        <div class="qr-container">
          <div class="qr-left">
            <img class="qr-code" id="qrImage" src="" alt="QR Code">
            <button class="save-btn" onclick="saveQr()">Save invite code</button>
          </div>

          <div class="link-input-wrapper">
            <span class="link-text" id="inviteLink">লোড হচ্ছে...</span>
            <div class="copy-btn" onclick="copyLink()"><i class="fa-regular fa-copy"></i></div>
          </div>
        </div>

        <!-- Social Icons -->
        <div class="social-icons">
          <a href="#" class="social-icon bg-fb" onclick="return shareTo('facebook')"><i class="fa-brands fa-facebook-f"></i></a>
          <a href="#" class="social-icon bg-x" onclick="return shareTo('x')"><i class="fa-brands fa-x-twitter"></i></a>
          <a href="#" class="social-icon bg-tg" onclick="return shareTo('telegram')"><i class="fa-paper-plane"></i></a>
          <a href="#" class="social-icon bg-wa" onclick="return shareTo('whatsapp')"><i class="fa-brands fa-whatsapp"></i></a>
          <a href="#" class="social-icon bg-chat" onclick="return shareTo('native')"><i class="fa-regular fa-comment-dots"></i></a>
          <a href="#" class="social-icon bg-line" onclick="return shareTo('line')"><i class="fa-brands fa-line"></i></a>
          <a href="#" class="social-icon bg-threads" onclick="return shareTo('native')"><i class="fa-brands fa-threads"></i></a>
        </div>
      </div>

      <!-- Promo Text -->
      <div class="promo-section">
        <div class="promo-title">Invite 1 person and earn up to 400TK</div>
        <div class="promo-sub">
          Earn <span class="highlight-yellow">2.2%</span> on lower level deposits
        </div>
        <div class="promo-sub">
          Lower level earns <span class="highlight-yellow">1%</span> on every bet
        </div>
      </div>

      <!-- ✅ Team Overview (রিয়েল ডাটা) -->
      <div class="team-section">
        <div class="sec-title">My Team Overview</div>
        <div class="team-row">
          <span>Total Team Deposit</span>
          <strong id="teamDeposit">৳0</strong>
        </div>
      </div>

      <!-- ✅ Downline List (রিয়েল ডাটা) -->
      <div class="team-section">
        <div class="sec-title">Downline তালিকা</div>
        <div id="downlineList" style="text-align:center; color:#9c9488; padding:14px 0; font-size:12px;">লোড হচ্ছে...</div>
      </div>

      <!-- Table -->
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>Inviter<br>VIP level</th>
              <th>Referral<br>bonus/<br>person</th>
              <th>Recommend<br>a friend<br>request</th>
              <th>How to get it?</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>VIP0</td>
              <td>100TK</td>
              <td>Deposit<br>100TK &<br>Bet 2000TK</td>
              <td></td>
            </tr>
            <tr>
              <td>VIP1</td>
              <td></td>
              <td>Deposit</td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>

    </div>
  </div>

<script>
const token = localStorage.getItem('token');
if (!token) window.location.href = '/newlogin.php';

let currentLink = '';

async function loadReferralInfo() {
    try {
        const res = await fetch('/newreferral_api.php', {
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = await res.json();

        if (data.code === 0) {
            currentLink = window.location.origin + '/newregister.php?code=' + data.owncode;
            document.getElementById('inviteLink').textContent = currentLink;
            document.getElementById('qrImage').src = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' + encodeURIComponent(currentLink);
        } else {
            document.getElementById('inviteLink').textContent = 'Error';
        }
    } catch (e) {
        document.getElementById('inviteLink').textContent = 'Error';
    }
}

async function loadTeamInfo() {
    const listEl = document.getElementById('downlineList');
    try {
        const res = await fetch('/referral_team_api.php', {
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = await res.json();

        if (data.code !== 0) {
            listEl.innerHTML = `<div style="color:#d9534f;">${data.msg}</div>`;
            return;
        }

        document.getElementById('totalReferrals').textContent = data.total_referrals;
        document.getElementById('activeReferrals').textContent = data.active_referrals;
        document.getElementById('teamDeposit').textContent = '৳' + Number(data.total_team_deposit).toLocaleString('en-IN', {maximumFractionDigits: 0});

        if (!data.downline || data.downline.length === 0) {
            listEl.innerHTML = '<div style="color:#9c9488;">এখনো কেউ তোমার Referral-Link দিয়ে Join করেনি।</div>';
            return;
        }

        listEl.innerHTML = '';
        data.downline.forEach(d => {
            const row = document.createElement('div');
            row.className = 'team-row';
            row.innerHTML = `
                <div style="text-align:left;">
                    <div style="font-weight:700; color:#333;">${d.mobile}</div>
                    <div style="font-size:10.5px; color:#9c9488; margin-top:2px;">${d.joined_at}</div>
                </div>
                <div style="text-align:right;">
                    <div style="font-weight:800; color:#333;">৳${d.deposit_total}</div>
                    <div style="font-size:10px; font-weight:700; color:${d.is_active ? '#22a06b' : '#bbb'}; margin-top:2px;">
                        ${d.is_active ? '● Active' : '○ Inactive'}
                    </div>
                </div>
            `;
            listEl.appendChild(row);
        });
    } catch (e) {
        listEl.innerHTML = `<div style="color:#d9534f;">সমস্যা হয়েছে: ${e.message}</div>`;
    }
}

async function loadDailyIncome() {
    const random = () => Math.random().toString(36).substring(2, 15);

    async function fetchIncome(dateStr) {
        const r = random();
        const shonustr = `{"date":"${dateStr}","language":1,"random":"${r}"}`;
        const signature = md5(shonustr).toUpperCase();
        try {
            const res = await fetch('/deepanshu/api/webapi/GetCommissionDetails.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
                body: JSON.stringify({ date: dateStr, language: 1, random: r, signature, timestamp: Date.now() })
            });
            const data = await res.json();
            if (data.code === 0 && data.data && data.data.rebateAmount_Last != null) {
                return Number(data.data.rebateAmount_Last);
            }
        } catch (e) {}
        return 0;
    }

    const today = new Date();
    const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
    const fmt = (d) => d.toISOString().slice(0, 10);

    const [todayAmt, yesterdayAmt] = await Promise.all([fetchIncome(fmt(today)), fetchIncome(fmt(yesterday))]);
    document.getElementById('todayIncome').textContent = '৳ ' + todayAmt.toLocaleString('en-IN', {maximumFractionDigits: 2});
    document.getElementById('yesterdayIncome').textContent = '৳ ' + yesterdayAmt.toLocaleString('en-IN', {maximumFractionDigits: 2});
}

function md5(str) {
    function rotateLeft(n, s) { return (n << s) | (n >>> (32 - s)); }
    function toHex(n) { let s = '', v; for (let i = 0; i < 4; i++) { v = (n >>> (i * 8)) & 255; s += ('0' + v.toString(16)).slice(-2); } return s; }
    function utf8Encode(str) { return unescape(encodeURIComponent(str)); }
    str = utf8Encode(str);
    const msgLen = str.length;
    const numBlocks = (((msgLen + 8) >>> 6) + 1) * 16;
    const M = new Array(numBlocks).fill(0);
    for (let i = 0; i < msgLen; i++) M[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
    M[msgLen >> 2] |= 0x80 << ((msgLen % 4) * 8);
    M[numBlocks - 2] = msgLen * 8;
    let a = 1732584193, b = -271733879, c = -1732584194, d = 271733878;
    const S = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];
    const K = [];
    for (let i = 0; i < 64; i++) K[i] = (Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)) | 0;
    for (let i = 0; i < numBlocks; i += 16) {
        let A = a, B = b, C = c, D = d;
        for (let j = 0; j < 64; j++) {
            let F, g;
            if (j < 16) { F = (B & C) | (~B & D); g = j; }
            else if (j < 32) { F = (D & B) | (~D & C); g = (5 * j + 1) % 16; }
            else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; }
            else { F = C ^ (B | ~D); g = (7 * j) % 16; }
            F = (F + A + K[j] + (M[i + g] | 0)) | 0;
            A = D; D = C; C = B;
            B = (B + rotateLeft(F, S[j])) | 0;
        }
        a = (a + A) | 0; b = (b + B) | 0; c = (c + C) | 0; d = (d + D) | 0;
    }
    return toHex(a) + toHex(b) + toHex(c) + toHex(d);
}

function copyLink() {
    if (!currentLink) return;
    navigator.clipboard.writeText(currentLink);
    alert('✅ Link Copy হয়েছে!');
}

function saveQr() {
    const img = document.getElementById('qrImage');
    const a = document.createElement('a');
    a.href = img.src;
    a.download = 'invite-qr.png';
    a.target = '_blank';
    a.click();
}

function shareTo(platform) {
    if (!currentLink) return false;
    const text = encodeURIComponent('CV111-এ যোগ দাও! ');
    const url = encodeURIComponent(currentLink);
    let shareUrl = '';
    switch (platform) {
        case 'facebook': shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`; break;
        case 'x': shareUrl = `https://twitter.com/intent/tweet?text=${text}&url=${url}`; break;
        case 'telegram': shareUrl = `https://t.me/share/url?url=${url}&text=${text}`; break;
        case 'whatsapp': shareUrl = `https://wa.me/?text=${text}${url}`; break;
        case 'line': shareUrl = `https://social-plugins.line.me/lineit/share?url=${url}`; break;
        case 'native':
            if (navigator.share) { navigator.share({ title: 'CV111', url: currentLink }); return false; }
            copyLink();
            return false;
    }
    if (shareUrl) window.open(shareUrl, '_blank');
    return false;
}

loadReferralInfo();
loadTeamInfo();
loadDailyIncome();
</script>

</body>
</html>
