<?php
require_once 'db.php';
require_once 'auth_check.php';
require_once 'currency.php';

$uid = $user_id;

// ── Fetch user row ────────────────────────────────────────────
$u = $conn->query("SELECT * FROM users WHERE id=$uid LIMIT 1")->fetch_assoc();

// ── Build full invite URL ─────────────────────────────────────
$scheme      = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host        = $_SERVER['HTTP_HOST'] ?? 'localhost';
$dir         = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$base_url    = $scheme . '://' . $host . $dir;
$invite_link = $base_url . '/register?invitecode=' . urlencode($u['referral_code'] ?? '');

// ── Commission summary per level ──────────────────────────────
$level_data = [];
foreach ([1,2,3] as $lvl) {
    $ref  = (float)($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM commission_logs WHERE user_id=$uid AND level=$lvl AND type='referral'")->fetch_assoc()['s'] ?? 0);
    $task = (float)($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM commission_logs WHERE user_id=$uid AND level=$lvl AND type='task'")->fetch_assoc()['s'] ?? 0);
    $level_data[$lvl] = ['referral'=>$ref,'task'=>$task,'total'=>$ref+$task];
}

// ── Fetch members per level ───────────────────────────────────
function fetchMembers($conn, array $parent_ids): array {
    if (empty($parent_ids)) return [];
    $in  = implode(',', array_map('intval', $parent_ids));
    $sql = "SELECT u.id, u.phone, u.created_at,
                   COALESCE(p.name,'No Plan') AS plan_name,
                   COALESCE(p.color_from,'#ddd') AS color_from,
                   COALESCE(p.color_to,'#bbb')   AS color_to
            FROM users u
            LEFT JOIN user_plans up ON up.user_id = u.id AND up.active = 1
            LEFT JOIN plans p ON p.id = up.plan_id
            WHERE u.referred_by IN ($in)
            ORDER BY u.created_at DESC";
    $res = $conn->query($sql);
    $map = [];
    while ($r = $res->fetch_assoc()) {
        $id = $r['id'];
        if (!isset($map[$id]) || ($map[$id]['plan_name'] === 'No Plan' && $r['plan_name'] !== 'No Plan')) {
            $map[$id] = $r;
        }
    }
    return array_values($map);
}

$l1_members = fetchMembers($conn, [$uid]);
$l1_ids     = array_column($l1_members, 'id');
$l2_members = fetchMembers($conn, $l1_ids ?: [0]);
$l2_ids     = array_column($l2_members, 'id');
$l3_members = fetchMembers($conn, $l2_ids ?: [0]);

// ── Commission rates from active plan ────────────────────────
$rates = ['ref_l1'=>10,'ref_l2'=>5,'ref_l3'=>2,'task_l1'=>5,'task_l2'=>3,'task_l3'=>1];
if (!empty($active_plan)) {
    $pid = (int)$active_plan['id'];
    $pr  = $conn->query("SELECT ref_commission_l1,ref_commission_l2,ref_commission_l3,task_commission_l1,task_commission_l2,task_commission_l3 FROM plans WHERE id=$pid")->fetch_assoc();
    if ($pr) $rates = [
        'ref_l1'  => (float)$pr['ref_commission_l1'],
        'ref_l2'  => (float)$pr['ref_commission_l2'],
        'ref_l3'  => (float)$pr['ref_commission_l3'],
        'task_l1' => (float)$pr['task_commission_l1'],
        'task_l2' => (float)$pr['task_commission_l2'],
        'task_l3' => (float)$pr['task_commission_l3'],
    ];
}

$total_all     = $level_data[1]['total'] + $level_data[2]['total'] + $level_data[3]['total'];
$referral_code = htmlspecialchars($u['referral_code'] ?? 'N/A');

function maskPhone(string $p): string {
    return '***' . substr($p, -7);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>WFM - Invite Friends</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{
  font-family:'Segoe UI',sans-serif;
  background:linear-gradient(160deg,#b8cba8 0%,#a8bc96 40%,#8faa7a 100%);
  min-height:100vh;padding-bottom:90px
}
.top-bar{
  background:rgba(255,255,255,.45);backdrop-filter:blur(8px);
  padding:14px 16px;display:flex;align-items:center;gap:10px;
  border-bottom:1px solid rgba(255,255,255,.3)
}
.back-btn{
  width:34px;height:34px;background:rgba(255,255,255,.6);border-radius:50%;
  display:flex;align-items:center;justify-content:center;text-decoration:none;flex-shrink:0
}
.back-btn svg{width:20px;height:20px;fill:#1a2a0a}
.top-bar h1{font-size:17px;font-weight:700;color:#1a2a0a;flex:1;text-align:center}
.top-bar .spacer{width:34px}

.banner{
  margin:12px 12px 0;background:linear-gradient(135deg,#2c7be5,#3ecf8e);
  border-radius:16px;padding:20px 20px 16px;color:#fff;text-align:center;
  position:relative;overflow:hidden
}
.banner::before{content:'';position:absolute;top:-30px;right:-30px;width:120px;height:120px;background:rgba(255,255,255,.1);border-radius:50%}
.banner::after{content:'';position:absolute;bottom:-20px;left:-20px;width:90px;height:90px;background:rgba(255,255,255,.08);border-radius:50%}
.banner-label{font-size:13px;opacity:.88;font-weight:500;position:relative;z-index:1}
.banner-value{font-size:36px;font-weight:900;letter-spacing:-1px;margin:4px 0 2px;position:relative;z-index:1}
.banner-sub{font-size:12px;opacity:.75;position:relative;z-index:1}

.stats-row{margin:8px 12px;display:grid;grid-template-columns:repeat(3,1fr);gap:6px}
.stat-card{background:#fff;border-radius:12px;padding:12px 6px;text-align:center}
.stat-badge{display:inline-block;font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px;margin-bottom:6px;color:#fff}
.lv1-badge{background:linear-gradient(90deg,#f39c12,#e67e22)}
.lv2-badge{background:linear-gradient(90deg,#3eaabb,#2c7be5)}
.lv3-badge{background:linear-gradient(90deg,#8e44ad,#e91e63)}
.stat-val{font-size:22px;font-weight:800;color:#1a2a0a}
.stat-lbl{font-size:10px;color:#666;margin-top:3px}

.section-title{margin:10px 12px 6px;font-size:13px;font-weight:700;color:#1a3a0a}

.level-card{margin:0 12px 8px;background:#fff;border-radius:14px;overflow:hidden}
.lc-header{
  display:flex;align-items:center;gap:10px;padding:12px 16px;
  cursor:pointer;user-select:none;-webkit-user-select:none;
  -webkit-tap-highlight-color:transparent
}
.lc-icon{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:900;color:#fff;flex-shrink:0}
.lc1-icon{background:linear-gradient(135deg,#f39c12,#e67e22)}
.lc2-icon{background:linear-gradient(135deg,#3eaabb,#2c7be5)}
.lc3-icon{background:linear-gradient(135deg,#8e44ad,#e91e63)}
.lc-title{flex:1;min-width:0}
.lc-title strong{font-size:14px;font-weight:700;color:#1a2a0a;display:block}
.lc-title span{font-size:11px;color:#888;margin-top:1px;display:block}
.lc-right{display:flex;flex-direction:column;align-items:flex-end;gap:2px;flex-shrink:0}
.lc-right .amount{font-size:17px;font-weight:800;color:#2c7be5}
.lc-right .lbl{font-size:10px;color:#aaa}
.lc-chevron{width:18px;height:18px;fill:#bbb;transition:transform .25s;flex-shrink:0;margin-left:2px}
.lc-chevron.open{transform:rotate(180deg)}

.collapsible{overflow:hidden;max-height:0;transition:max-height .4s ease}
.collapsible.open{max-height:9999px}
.divider{height:1px;background:#f0f0f0;margin:0 16px}

.lc-body{padding:12px 16px 14px}
.lc-stats-row{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px}
.lc-stat{text-align:center;padding:8px;background:#f7f9fc;border-radius:8px}
.lc-stat .s-val{font-size:14px;font-weight:700;color:#333}
.lc-stat .s-lbl{font-size:10px;color:#888;margin-top:2px}
.lc-rates{display:flex;gap:6px;justify-content:center;flex-wrap:wrap;margin-bottom:14px}
.rate-chip{font-size:10px;font-weight:600;padding:3px 10px;border-radius:20px;background:#f0f4ff;color:#2c7be5}

.members-label{
  font-size:11px;font-weight:700;color:#888;text-transform:uppercase;
  letter-spacing:.5px;margin-bottom:8px;display:flex;align-items:center;gap:6px
}
.member-row{display:flex;align-items:center;gap:10px;padding:9px 0;border-bottom:1px solid #f4f4f4}
.member-row:last-child{border-bottom:none}
.member-avatar{
  width:36px;height:36px;border-radius:50%;
  background:linear-gradient(135deg,#3eaabb,#2c7be5);
  display:flex;align-items:center;justify-content:center;
  color:#fff;font-size:13px;font-weight:700;flex-shrink:0
}
.member-info{flex:1;min-width:0}
.member-phone{font-size:13px;font-weight:600;color:#1a2a0a}
.member-date{font-size:10px;color:#aaa;margin-top:2px}
.plan-pill{font-size:10px;font-weight:700;padding:4px 10px;border-radius:20px;color:#fff;white-space:nowrap;flex-shrink:0}
.plan-pill.no-plan{background:#eee;color:#999}
.no-members{text-align:center;color:#bbb;font-size:12px;padding:16px 0;font-style:italic}

/* Invite box */
.invite-box{margin:0 12px 8px;background:#fff;border-radius:14px;padding:16px}
.invite-box h3{font-size:13px;font-weight:700;color:#1a2a0a;margin-bottom:12px}
.invite-code-row{display:flex;align-items:center;gap:8px;background:#f7f9fc;border-radius:10px;padding:10px 14px;margin-bottom:10px}
.invite-code-row .code-label{font-size:12px;color:#888;white-space:nowrap}
.invite-code-row .code-val{flex:1;font-size:15px;font-weight:800;color:#2c7be5;word-break:break-all}
.copy-code-btn{background:linear-gradient(90deg,#3ecf8e,#2c7be5);color:#fff;border:none;border-radius:8px;padding:7px 14px;font-size:12px;font-weight:700;cursor:pointer;white-space:nowrap;flex-shrink:0;font-family:inherit}
.invite-link-row{background:#f7f9fc;border-radius:10px;padding:10px 14px;margin-bottom:10px;word-break:break-all}
.invite-link-row .link-label{font-size:11px;color:#888;margin-bottom:4px;font-weight:600}
.invite-link-row .link-val{font-size:12px;color:#2c7be5;line-height:1.5;font-weight:600}
.copy-link-btn{
  display:block;width:100%;background:linear-gradient(90deg,#f39c12,#e67e22);color:#fff;border:none;
  border-radius:12px;padding:14px;font-size:15px;font-weight:700;cursor:pointer;text-align:center;
  box-shadow:0 4px 14px rgba(243,156,18,.3);font-family:inherit
}
.copy-link-btn:active{transform:scale(.99);opacity:.92}

.share-row{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:0 12px 8px}
.share-btn{display:flex;align-items:center;justify-content:center;gap:8px;padding:13px;border-radius:12px;font-size:13px;font-weight:700;border:none;cursor:pointer;color:#fff;font-family:inherit}
.share-wa{background:linear-gradient(90deg,#25d366,#128c7e)}
.share-tg{background:linear-gradient(90deg,#0088cc,#006fa6)}

.toast{
  position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(.8);
  background:rgba(0,0,0,.78);color:#fff;padding:10px 22px;border-radius:24px;
  font-size:13px;font-weight:600;z-index:9999;opacity:0;
  transition:all .25s ease;pointer-events:none;white-space:nowrap
}
.toast.show{opacity:1;transform:translate(-50%,-50%) scale(1)}

.bottom-nav{position:fixed;bottom:0;left:0;right:0;height:64px;background:#fff;border-top:1px solid #e0e0e0;display:flex;align-items:center;justify-content:space-around;z-index:1000}
.bn-item{display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;flex:1;padding:6px 0}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span{color:#3eaabb}
.bn-item:not(.active) span{color:#aaa}
</style>
</head>
<body>

<div class="top-bar">
  <a href="javascript:history.back()" class="back-btn">
    <svg viewBox="0 0 24 24"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
  </a>
  <h1>Invite Friends</h1>
  <div class="spacer"></div>
</div>

<!-- Earnings Banner -->
<div class="banner">
  <div class="banner-label">Total Referral &amp; Team Earnings</div>
  <div class="banner-value"><?= number_format($total_all, 2) ?> <span style="font-size:18px"><?= $currency ?></span></div>
  <div class="banner-sub">Across all 3 levels · Referral + Task commissions</div>
</div>

<!-- Level member counts -->
<div class="stats-row">
  <div class="stat-card">
    <div class="stat-badge lv1-badge">Level 1</div>
    <div class="stat-val"><?= count($l1_members) ?></div>
    <div class="stat-lbl">Direct Members</div>
  </div>
  <div class="stat-card">
    <div class="stat-badge lv2-badge">Level 2</div>
    <div class="stat-val"><?= count($l2_members) ?></div>
    <div class="stat-lbl">2nd Level</div>
  </div>
  <div class="stat-card">
    <div class="stat-badge lv3-badge">Level 3</div>
    <div class="stat-val"><?= count($l3_members) ?></div>
    <div class="stat-lbl">3rd Level</div>
  </div>
</div>

<div class="section-title">📊 Team Earnings &amp; Members</div>

<?php
$level_cfg = [
  1 => ['icon'=>'L1','cls'=>'lc1-icon','ref_rate'=>$rates['ref_l1'],'task_rate'=>$rates['task_l1'],'label'=>'Direct Referrals','members'=>$l1_members],
  2 => ['icon'=>'L2','cls'=>'lc2-icon','ref_rate'=>$rates['ref_l2'],'task_rate'=>$rates['task_l2'],'label'=>'2nd Generation','members'=>$l2_members],
  3 => ['icon'=>'L3','cls'=>'lc3-icon','ref_rate'=>$rates['ref_l3'],'task_rate'=>$rates['task_l3'],'label'=>'3rd Generation','members'=>$l3_members],
];
foreach ($level_cfg as $lvl => $cfg):
    $d   = $level_data[$lvl];
    $cnt = count($cfg['members']);
?>
<div class="level-card">
  <div class="lc-header" onclick="toggleLevel(<?= $lvl ?>)">
    <div class="lc-icon <?= $cfg['cls'] ?>"><?= $cfg['icon'] ?></div>
    <div class="lc-title">
      <strong>Level <?= $lvl ?> — <?= $cfg['label'] ?></strong>
      <span><?= $cnt ?> member<?= $cnt!=1?'s':'' ?> · Ref <?= $cfg['ref_rate'] ?>% · Task <?= $cfg['task_rate'] ?>%</span>
    </div>
    <div class="lc-right">
      <div class="amount"><?= number_format($d['total'],2) ?></div>
      <div class="lbl"><?= $currency ?> Total</div>
    </div>
    <svg class="lc-chevron" id="chev<?= $lvl ?>" viewBox="0 0 24 24"><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
  </div>

  <div class="collapsible" id="body<?= $lvl ?>">
    <div class="divider"></div>
    <div class="lc-body">
      <div class="lc-stats-row">
        <div class="lc-stat">
          <div class="s-val"><?= number_format($d['referral'],2) ?></div>
          <div class="s-lbl">Referral Rewards (<?= $currency ?>)</div>
        </div>
        <div class="lc-stat">
          <div class="s-val"><?= number_format($d['task'],2) ?></div>
          <div class="s-lbl">Task Commissions (<?= $currency ?>)</div>
        </div>
      </div>
      <div class="lc-rates">
        <span class="rate-chip">Join Bonus: <?= $cfg['ref_rate'] ?>%</span>
        <span class="rate-chip">Task Bonus: <?= $cfg['task_rate'] ?>%</span>
      </div>

      <div class="members-label">👥 Members (<?= $cnt ?>)</div>
      <?php if (empty($cfg['members'])): ?>
        <div class="no-members">No members at this level yet</div>
      <?php else: ?>
        <?php foreach ($cfg['members'] as $m):
          $initials = strtoupper(substr(preg_replace('/\D/','',$m['phone']), -2));
          $pname    = htmlspecialchars($m['plan_name']);
          $cfrom    = htmlspecialchars($m['color_from']);
          $cto      = htmlspecialchars($m['color_to']);
          $joined   = date('d M Y', strtotime($m['created_at']));
          $hasPlan  = $m['plan_name'] !== 'No Plan';
        ?>
        <div class="member-row">
          <div class="member-avatar"><?= $initials ?></div>
          <div class="member-info">
            <div class="member-phone"><?= maskPhone($m['phone']) ?></div>
            <div class="member-date">Joined <?= $joined ?></div>
          </div>
          <?php if ($hasPlan): ?>
            <div class="plan-pill" style="background:linear-gradient(90deg,<?= $cfrom ?>,<?= $cto ?>)"><?= $pname ?></div>
          <?php else: ?>
            <div class="plan-pill no-plan">No Plan</div>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php endforeach; ?>

<!-- Invite Box -->
<div class="invite-box">
  <h3>🔗 Your Invitation Link</h3>

  <!-- Code row -->
  <div class="invite-code-row">
    <span class="code-label">Code:</span>
    <span class="code-val"><?= $referral_code ?></span>
    <button class="copy-code-btn" onclick="copyText('<?= addslashes($referral_code) ?>', '✅ Code copied!')">Copy</button>
  </div>

  <!-- Full URL display -->
  <div class="invite-link-row">
    <div class="link-label">🌐 Full Registration Link:</div>
    <div class="link-val" id="inviteLink"><?= htmlspecialchars($invite_link) ?></div>
  </div>

  <button class="copy-link-btn" onclick="copyText(document.getElementById('inviteLink').innerText, '✅ Link copied!')">
    📋 Copy Full Invite Link
  </button>
</div>

<!-- Share Buttons -->
<div class="share-row">
  <button class="share-btn share-wa" onclick="shareWhatsApp()">
    <svg viewBox="0 0 24 24" width="18" height="18" fill="#fff"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.570-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.522 3.659 1.427 5.17L2 22l4.948-1.401A9.953 9.953 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2zm0 18a7.952 7.952 0 01-4.042-1.104l-.29-.172-2.938.832.794-2.876-.189-.295A7.965 7.965 0 014 12c0-4.418 3.582-8 8-8s8 3.582 8 8-3.582 8-8 8z"/></svg>
    WhatsApp
  </button>
  <button class="share-btn share-tg" onclick="shareTelegram()">
    <svg viewBox="0 0 24 24" width="18" height="18" fill="#fff"><path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0a12 12 0 00-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>
    Telegram
  </button>
</div>

<div class="toast" id="toast"></div>
<?php include 'navigation_bottom.php'; ?>

<script>
const inviteLink = <?= json_encode($invite_link) ?>;
const refCode    = <?= json_encode($u['referral_code'] ?? '') ?>;

function toggleLevel(lvl) {
  const body = document.getElementById('body' + lvl);
  const chev = document.getElementById('chev' + lvl);
  const isOpen = body.classList.contains('open');
  body.classList.toggle('open', !isOpen);
  chev.classList.toggle('open', !isOpen);
}

function showToast(msg) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 2200);
}

function copyText(text, successMsg) {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(text).then(() => showToast(successMsg || '✅ Copied!'));
  } else {
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0';
    document.body.appendChild(ta);
    ta.select();
    document.execCommand('copy');
    document.body.removeChild(ta);
    showToast(successMsg || '✅ Copied!');
  }
}

function shareWhatsApp() {
  const text = encodeURIComponent('Join me on WFM and start earning!\nUse my invite code: ' + refCode + '\n' + inviteLink);
  window.open('https://wa.me/?text=' + text, '_blank');
}

function shareTelegram() {
  const text = encodeURIComponent('Join me on WFM and start earning!\nUse my invite code: ' + refCode);
  window.open('https://t.me/share/url?url=' + encodeURIComponent(inviteLink) + '&text=' + text, '_blank');
}
</script>
</body>
</html>