<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once 'db.php';

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

$user_id = $_SESSION['user_id'];
$invite_code = "";

// Get invite_code from users table
$stmt = $conn->prepare("SELECT invite_code, referral_earnings FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($invite_code, $my_referral_earnings);
$stmt->fetch();
$stmt->close();

// Initialize stats
$team_size = 0;
$new_team = 0;

$lev1_register = 0; $lev1_valid = 0;
$lev2_register = 0; $lev2_valid = 0;
$lev3_register = 0; $lev3_valid = 0;

$level1 = [];
$level2 = [];
$level3 = [];

$today = date('Y-m-d');

// -------- LEVEL 1 (Direct) ----------
$stmt = $conn->prepare("SELECT id, created_at FROM users WHERE referred_by = ?");
$stmt->bind_param("s", $invite_code);
$stmt->execute();
$res1 = $stmt->get_result();
while ($row = $res1->fetch_assoc()) {
    $lev1_register++;
    $team_size++;
    if (substr($row['created_at'], 0, 10) === $today) $new_team++;
    $level1[] = $row['id'];

    $stmt2 = $conn->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ?");
    $stmt2->bind_param("i", $row['id']);
    $stmt2->execute();
    $stmt2->bind_result($count);
    $stmt2->fetch();
    $stmt2->close();
    if ($count > 0) $lev1_valid++;
}
$stmt->close();

// -------- LEVEL 2 ----------
foreach ($level1 as $lev1_id) {
    $stmt = $conn->prepare("SELECT id, created_at FROM users WHERE referred_by = (SELECT invite_code FROM users WHERE id = ?)");
    $stmt->bind_param("i", $lev1_id);
    $stmt->execute();
    $res2 = $stmt->get_result();
    while ($row = $res2->fetch_assoc()) {
        $lev2_register++;
        $team_size++;
        if (substr($row['created_at'], 0, 10) === $today) $new_team++;
        $level2[] = $row['id'];

        $stmt2 = $conn->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ?");
        $stmt2->bind_param("i", $row['id']);
        $stmt2->execute();
        $stmt2->bind_result($count);
        $stmt2->fetch();
        $stmt2->close();
        if ($count > 0) $lev2_valid++;
    }
    $stmt->close();
}

// -------- LEVEL 3 ----------
foreach ($level2 as $lev2_id) {
    $stmt = $conn->prepare("SELECT id, created_at FROM users WHERE referred_by = (SELECT invite_code FROM users WHERE id = ?)");
    $stmt->bind_param("i", $lev2_id);
    $stmt->execute();
    $res3 = $stmt->get_result();
    while ($row = $res3->fetch_assoc()) {
        $lev3_register++;
        $team_size++;
        if (substr($row['created_at'], 0, 10) === $today) $new_team++;
        $level3[] = $row['id'];

        $stmt2 = $conn->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ?");
        $stmt2->bind_param("i", $row['id']);
        $stmt2->execute();
        $stmt2->bind_result($count);
        $stmt2->fetch();
        $stmt2->close();
        if ($count > 0) $lev3_valid++;
    }
    $stmt->close();
}

function getReferralBonus($conn, $user_ids) {
    if (empty($user_ids)) return 0;
    $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
    $types = str_repeat('i', count($user_ids));
    $stmt = $conn->prepare("SELECT SUM(referral_earnings) FROM users WHERE id IN ($placeholders)");
    $stmt->bind_param($types, ...$user_ids);
    $stmt->execute();
    $stmt->bind_result($sum);
    $stmt->fetch();
    $stmt->close();
    return $sum ?? 0;
}

$lev1_bonus = getReferralBonus($conn, $level1);
$lev2_bonus = getReferralBonus($conn, $level2);
$lev3_bonus = getReferralBonus($conn, $level3);

function getTeamTotal($conn, $user_ids, $table) {
    if (empty($user_ids)) return 0;
    $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
    $types = str_repeat('i', count($user_ids));
    $query = "SELECT SUM(amount) FROM $table WHERE status = 'approved' AND user_id IN ($placeholders)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$user_ids);
    $stmt->execute();
    $stmt->bind_result($sum);
    $stmt->fetch();
    $stmt->close();
    return $sum ?? 0;
}

$team_recharge = getTeamTotal($conn, array_merge($level1, $level2, $level3), 'mpesa_recharges');
$team_withdrawal = getTeamTotal($conn, array_merge($level1, $level2, $level3), 'withdrawals');

// -------- Get first withdrawals count --------
$first_withdrawals = 0;
$all_users = array_merge($level1, $level2, $level3);
foreach ($all_users as $uid) {
    $stmt = $conn->prepare("SELECT COUNT(*) FROM withdrawals WHERE user_id = ? AND status = 'approved'");
    $stmt->bind_param("i", $uid);
    $stmt->execute();
    $stmt->bind_result($wcount);
    $stmt->fetch();
    $stmt->close();
    if ($wcount === 1) {
        $first_withdrawals++;
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>    
  <meta charset="UTF-8" />    
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>    
  <title>Team</title>    
  <style>
    body {
      margin: 0;
      background-color: #0f1a24;
      color: #fff;
      font-family: Arial, sans-serif;
      padding-bottom: 80px;
    }
    .header {
      padding: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: linear-gradient(45deg, #1e3c72, #2a5298);
      color: #fff;
    }
    .header h1 {
      font-size: 18px;
    }
    .language {
      background-color: #1e3c72;
      padding: 5px 10px;
      border-radius: 5px;
      font-size: 14px;
    }
    .card {
      margin: 15px;
      background-color: #16222a;
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 8px rgba(0, 191, 255, 0.4);
    }
    .invitation {
      font-size: 16px;
      margin-bottom: 10px;
    }
    .copy-btn {
      background-color: #00bfff;
      color: white;
      border-radius: 10px;
      padding: 3px 10px;
      margin-left: 10px;
      cursor: pointer;
      border: none;
    }
    .section-title {
      margin: 15px;
      font-size: 15px;
      color: #add8e6;
    }
    .stats {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
      background-color: #16222a;
      margin: 0 15px;
      padding: 15px;
      border-radius: 10px;
      text-align: center;
    }
    .stats div {
      width: 30%;
      margin-bottom: 10px;
    }
    .level-card {
      margin: 15px;
      border-radius: 10px;
      padding: 15px;
      color: #fff;
    }
    .level-1 {
      background: linear-gradient(to right, #1e3c72, #2a5298);
    }
    .level-2 {
      background: linear-gradient(to right, #2a5298, #1ca7ec);
    }
    .level-3 {
      background: linear-gradient(to right, #1ca7ec, #7bd5f5);
      color: #000;
    }
    .details-btn {
      background-color: #00bfff;
      color: white;
      padding: 3px 10px;
      border-radius: 8px;
      float: right;
      border: none;
    }
    .icons {
      display: flex;
      gap: 20px;
      justify-content: center;
      align-items: center;
      font-size: 32px;
      color: #00bfff;
      margin-top: 10px;
    }
    .icons i {
      cursor: pointer;
      transition: transform 0.2s, color 0.2s;
    }
    .icons i:hover {
      color: #1ca7ec;
      transform: scale(1.2);
    }
    .bottom-nav {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      background: #16222a;
      display: flex;
      justify-content: space-around;
      padding: 10px 0;
      border-top: 1px solid #1ca7ec;
    }
    .bottom-nav div {
      text-align: center;
      font-size: 13px;
      color: #ccc;
    }
    .bottom-nav div.active {
      color: #00bfff;
    }
    .bottom-nav i {
      display: block;
      font-size: 18px;
      margin-bottom: 4px;
    }
    a {
      text-decoration: none;
      color: inherit;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>BlackRock</h1>
    <div class="language">🌐 English</div>
  </div>

  <div class="card">
    <div class="invitation">
      Invitation code: <b id="inviteCode"><?= htmlspecialchars($invite_code) ?></b>
      <button class="copy-btn" onclick="copyText('inviteCode')">Copy</button>
    </div>
    <div class="invitation">
      <span id="inviteLink">https://blk-rckhs.xyz/rock/register?code=<?= urlencode($invite_code) ?></span>
      <button class="copy-btn" onclick="copyText('inviteLink')">Copy</button>
    </div>
    <div class="icons">
      <i class="fab fa-x-twitter" onclick="window.open('https://twitter.com/', '_blank')"></i>
      <i class="fab fa-facebook" onclick="window.open('https://facebook.com/', '_blank')"></i>
      <i class="fab fa-telegram" onclick="window.open('https://t.me/', '_blank')"></i>
      <i class="fab fa-linkedin" onclick="window.open('https://linkedin.com/', '_blank')"></i>
      <i class="fab fa-instagram" onclick="window.open('https://instagram.com/', '_blank')"></i>
      <i class="fab fa-tiktok" onclick="window.open('https://www.tiktok.com/', '_blank')"></i>
      <i class="fab fa-whatsapp" onclick="window.open('intent://send/#Intent;scheme=whatsapp;package=com.whatsapp;end')"></i>
    </div>
  </div>

  <div class="section-title">📅 Selection period</div>
  <div class="stats">
    <div><div>Team size</div><div><?= $team_size ?></div></div>
    <div><div>Team recharge</div><div><?= number_format($team_recharge, 2) ?></div></div>
    <div><div>Team Withdrawal</div><div><?= number_format($team_withdrawal, 2) ?></div></div>
    <div><div>New team</div><div><?= $new_team ?></div></div>
    <div><div>Referral Earnings</div><div><?= number_format($my_referral_earnings, 2) ?></div></div>
    <div><div>First withdrawal</div><div><?= $first_withdrawals ?></div></div>
  </div>

  <div class="level-card level-1">
    <strong>LEV 1</strong>
    <div style="margin-top: 5px;">Register/Valid: <?= $lev1_register ?>/<?= $lev1_valid ?></div>
    <div>Commission Percentage: 15%</div> 
    <div>Total Bonus: <?= number_format($lev1_bonus, 2) ?> <button class="details-btn">Details</button></div>
  </div>
  <div class="level-card level-2">
    <strong>LEV 2</strong>
    <div style="margin-top: 5px;">Register/Valid: <?= $lev2_register ?>/<?= $lev2_valid ?></div>
    <div>Commission Percentage: 1%</div>
    <div>Total Bonus: <?= number_format($lev2_bonus, 2) ?> <button class="details-btn">Details</button></div>
  </div>
  <div class="level-card level-3">
    <strong>LEV 3</strong>
    <div style="margin-top: 5px;">Register/Valid: <?= $lev3_register ?>/<?= $lev3_valid ?></div>
    <div>Commission Percentage: 1%</div>
    <div>Total Bonus: <?= number_format($lev3_bonus, 2) ?> <button class="details-btn">Details</button></div>
  </div>

  <div class="bottom-nav">
    <a href="home.php"><div><i class="fas fa-home"></i>Home</div></a>
    <a href="task.php"><div><i class="fas fa-tasks"></i>Task</div></a>
    <a href="team.php"><div class="active"><i class="fas fa-users"></i>Team</div></a>
    <a href="vip.php"><div><i class="fas fa-crown"></i>VIP</div></a>
    <a href="me.php"><div><i class="fas fa-user"></i>Me</div></a>
  </div>

  <script>
    function copyText(elementId) {
      const text = document.getElementById(elementId).innerText;
      navigator.clipboard.writeText(text).then(() => {
        alert("Copied!");
      }).catch(err => {
        alert("Failed to copy");
      });
    }
  </script>
</body>
</html>
