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

$_sup = $conn->query("SELECT key_value FROM settings WHERE key_name='support_url'")->fetch_assoc();
$support_url = $_sup['key_value'] ?? '#';

$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'] ?? '');
$referral_code = $u['referral_code'] ?? ('WFM' . str_pad($uid, 5, '0', STR_PAD_LEFT));

// ── Date filter ──────────────────────────────────────────────
$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to   = $_GET['date_to']   ?? date('Y-m-d');
$date_from = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from) ? $date_from : date('Y-m-d');
$date_to   = preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to)   ? $date_to   : date('Y-m-d');

// ── Active tab ───────────────────────────────────────────────
$tab = $_GET['tab'] ?? 'report';

// ── Helper: get downliner IDs by level ───────────────────────
function getLevel1Ids($conn, $uid) {
    $rows = $conn->query("SELECT id FROM users WHERE referred_by=$uid")->fetch_all(MYSQLI_ASSOC);
    return array_column($rows, 'id');
}
function getLevel2Ids($conn, $l1ids) {
    if (empty($l1ids)) return [];
    $in = implode(',', array_map('intval', $l1ids));
    $rows = $conn->query("SELECT id FROM users WHERE referred_by IN ($in)")->fetch_all(MYSQLI_ASSOC);
    return array_column($rows, 'id');
}
function getLevel3Ids($conn, $l2ids) {
    if (empty($l2ids)) return [];
    $in = implode(',', array_map('intval', $l2ids));
    $rows = $conn->query("SELECT id FROM users WHERE referred_by IN ($in)")->fetch_all(MYSQLI_ASSOC);
    return array_column($rows, 'id');
}

$l1ids = getLevel1Ids($conn, $uid);
$l2ids = getLevel2Ids($conn, $l1ids);
$l3ids = getLevel3Ids($conn, $l2ids);
$all_downliner_ids = array_merge($l1ids, $l2ids, $l3ids);

// ── Team Report stats ─────────────────────────────────────────
$team_size = count($all_downliner_ids);

$new_adds = 0;
if (!empty($all_downliner_ids)) {
    $in = implode(',', array_map('intval', $all_downliner_ids));
    $new_adds = (int)$conn->query("SELECT COUNT(*) as c FROM users WHERE id IN ($in) AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'")->fetch_assoc()['c'];
}

$grade_a = 0;
if (!empty($all_downliner_ids)) {
    $in = implode(',', array_map('intval', $all_downliner_ids));
    $grade_a = (int)$conn->query("SELECT COUNT(DISTINCT up.user_id) as c FROM user_plans up JOIN plans p ON p.id=up.plan_id WHERE up.user_id IN ($in) AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW()) AND p.is_free=0")->fetch_assoc()['c'];
}

$abc_fulltime = $grade_a;

$team_tasks = 0;
if (!empty($all_downliner_ids)) {
    $in = implode(',', array_map('intval', $all_downliner_ids));
    $team_tasks = (int)$conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id IN ($in) AND DATE(completed_at) BETWEEN '$date_from' AND '$date_to'")->fetch_assoc()['c'];
}

$total_withdrawal = 0;

// ── Level tabs stats ──────────────────────────────────────────
$level_tab = $_GET['ltab'] ?? 'abc';

function getLevelStats($conn, $ids, $date_from, $date_to) {
    if (empty($ids)) return ['fulltime'=>0,'total_tasks'=>0,'completed'=>0,'remaining'=>0];
    $in = implode(',', array_map('intval', $ids));
    $fulltime  = (int)$conn->query("SELECT COUNT(DISTINCT up.user_id) as c FROM user_plans up JOIN plans p ON p.id=up.plan_id WHERE up.user_id IN ($in) AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW()) AND p.is_free=0")->fetch_assoc()['c'];
    $completed = (int)$conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id IN ($in) AND DATE(completed_at) BETWEEN '$date_from' AND '$date_to'")->fetch_assoc()['c'];
    $total_tasks_q = $conn->query("SELECT COALESCE(SUM(p.daily_tasks),0) as s FROM user_plans up JOIN plans p ON p.id=up.plan_id WHERE up.user_id IN ($in) AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW())");
    $total_tasks = (int)($total_tasks_q->fetch_assoc()['s'] ?? 0);
    $remaining   = max(0, $total_tasks - $completed);
    return compact('fulltime','total_tasks','completed','remaining');
}

$stats_a   = getLevelStats($conn, $l1ids,             $date_from, $date_to);
$stats_b   = getLevelStats($conn, $l2ids,             $date_from, $date_to);
$stats_c   = getLevelStats($conn, $l3ids,             $date_from, $date_to);
$stats_abc = getLevelStats($conn, $all_downliner_ids, $date_from, $date_to);

$active_stats = match($level_tab) {
    'a'   => $stats_a,
    'b'   => $stats_b,
    'c'   => $stats_c,
    default => $stats_abc,
};

// ── My Team: direct L1 members ────────────────────────────────
$my_team_members = [];
if ($tab === 'myteam' && !empty($l1ids)) {
    $in = implode(',', array_map('intval', $l1ids));
    $my_team_members = $conn->query("SELECT u.id, u.phone, u.created_at, p.name as plan_name, p.is_free, up.expires_at FROM users u LEFT JOIN user_plans up ON up.user_id=u.id AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW()) LEFT JOIN plans p ON p.id=up.plan_id WHERE u.id IN ($in) ORDER BY u.created_at DESC")->fetch_all(MYSQLI_ASSOC);
}

// ── Plan names for bottom table ───────────────────────────────
$plan_names_map = [];
$all_plans_list = $conn->query("SELECT id,name,sort_order FROM plans WHERE active=1 ORDER BY sort_order ASC")->fetch_all(MYSQLI_ASSOC);
foreach($all_plans_list as $pl) $plan_names_map[$pl['id']] = $pl['name'];

function getPlanLevelStats($conn, $plan_id, $ids, $date_from, $date_to) {
    if (empty($ids)) return ['fulltime'=>0,'completed'=>0];
    $in = implode(',', array_map('intval', $ids));
    $fulltime  = (int)$conn->query("SELECT COUNT(DISTINCT up.user_id) as c FROM user_plans up WHERE up.user_id IN ($in) AND up.plan_id=$plan_id AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW())")->fetch_assoc()['c'];
    $completed = (int)$conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id IN ($in) AND plan_id=$plan_id AND DATE(completed_at) BETWEEN '$date_from' AND '$date_to'")->fetch_assoc()['c'];
    return compact('fulltime','completed');
}

$current_ids = match($level_tab) {
    'a'   => $l1ids,
    'b'   => $l2ids,
    'c'   => $l3ids,
    default => $all_downliner_ids,
};
?>
<!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 - Team</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:80px}

.top-bar{background:rgba(255,255,255,.45);backdrop-filter:blur(8px);padding:14px 16px;display:flex;align-items:center;gap:12px;border-bottom:1px solid rgba(255,255,255,.3)}
.top-bar a{color:#1a2a0a;text-decoration:none;display:flex;align-items:center}
.top-bar h1{font-size:17px;font-weight:700;color:#1a2a0a;flex:1;text-align:center}

.main-tabs{display:flex;background:#1a2a3a;margin:0}
.main-tab{flex:1;text-align:center;padding:13px;font-size:14px;font-weight:600;color:rgba(255,255,255,.55);cursor:pointer;text-decoration:none;position:relative;transition:color .2s}
.main-tab.active{color:#fff}
.main-tab.active::after{content:'';position:absolute;bottom:0;left:20%;right:20%;height:3px;background:#2c7be5;border-radius:3px 3px 0 0}

.date-filter{background:#1a2a3a;padding:10px 14px;display:flex;align-items:center;gap:8px}
.date-filter input[type=date]{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);color:#fff;padding:6px 10px;border-radius:8px;font-size:13px;font-family:inherit;outline:none}
.date-filter input[type=date]::-webkit-calendar-picker-indicator{filter:invert(1)}
.date-filter span{color:rgba(255,255,255,.5);font-size:13px}
.date-filter button{margin-left:auto;background:#2c7be5;color:#fff;border:none;border-radius:8px;padding:7px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit}

.summary-grid{display:grid;grid-template-columns:repeat(3,1fr);background:#fff;border-bottom:1px solid #e0e0e0}
.sg-cell{padding:14px 8px;text-align:center;border-right:1px solid #e0e0e0;border-bottom:1px solid #e0e0e0}
.sg-cell:nth-child(3n){border-right:none}
.sg-cell .sv{font-size:17px;font-weight:800;color:#2c7be5}
.sg-cell .sl{font-size:10px;color:#888;margin-top:3px;line-height:1.3}

.level-tabs{display:flex;background:#fff;border-bottom:2px solid #eee}
.level-tab{flex:1;text-align:center;padding:11px 4px;font-size:13px;font-weight:600;color:#888;cursor:pointer;text-decoration:none;border-bottom:3px solid transparent;margin-bottom:-2px;transition:all .2s}
.level-tab.active{color:#2c7be5;border-bottom-color:#2c7be5}

.stats-cards{background:#fff;padding:14px;display:grid;grid-template-columns:1fr 1fr;gap:10px;border-bottom:1px solid #eee}
.stat-card{background:#f7f9fc;border-radius:10px;padding:12px 14px}
.stat-card .sv{font-size:20px;font-weight:800;color:#1a2a0a}
.stat-card .sl{font-size:11px;color:#888;margin-top:3px}

.plan-table{background:#fff;margin-top:8px}
.plan-table-head{display:grid;grid-template-columns:2fr 1fr 1fr;background:#f7f9fc;padding:10px 14px;border-bottom:1px solid #eee}
.plan-table-head span{font-size:11px;font-weight:700;text-transform:uppercase;color:#aaa;letter-spacing:.3px}
.plan-table-head span:not(:first-child){text-align:center}
.plan-row{display:grid;grid-template-columns:2fr 1fr 1fr;padding:12px 14px;border-bottom:1px solid #f0f0f0;align-items:center}
.plan-row:last-child{border-bottom:none}
.plan-row .plan-name{font-size:13px;font-weight:500;color:#1a2a0a}
.plan-row .plan-val{text-align:center;font-size:14px;font-weight:700;color:#2c7be5}

/* Referral box in my team tab */
.ref-box{background:#1a2a3a;padding:16px 14px}
.ref-box .ref-code-label{color:rgba(255,255,255,.6);font-size:12px;margin-bottom:4px}
.ref-box .ref-code{color:#f9e04b;font-size:20px;font-weight:800;letter-spacing:2px;margin-bottom:8px}
.ref-box .ref-url-label{color:rgba(255,255,255,.5);font-size:11px;margin-bottom:4px}
.ref-box .ref-url{color:#7dd3f5;font-size:12px;word-break:break-all;line-height:1.5;margin-bottom:10px}
.ref-box .ref-copy-btn{background:#f9e04b;color:#1a2a0a;border:none;border-radius:8px;padding:8px 20px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
.ref-box .ref-note{color:rgba(255,255,255,.38);font-size:11px;margin-top:8px}

.member-list{padding:10px 12px}
.member-card{background:#fff;border-radius:12px;padding:14px;margin-bottom:8px;display:flex;align-items:center;gap:12px;box-shadow:0 1px 6px rgba(0,0,0,.07)}
.member-avatar{width:42px;height:42px;border-radius:50%;background:linear-gradient(135deg,#3eaabb,#2c7be5);display:flex;align-items:center;justify-content:center;flex-shrink:0}
.member-avatar svg{width:22px;height:22px;fill:#fff}
.member-info{flex:1}
.member-phone{font-size:14px;font-weight:600;color:#1a2a0a}
.member-plan{font-size:11px;color:#888;margin-top:2px}
.member-date{font-size:11px;color:#aaa;margin-top:1px}
.member-badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px}
.badge-active{background:#e6f9f0;color:#1a7a4a}
.badge-free{background:#fff3e0;color:#b7680a}

.float-service{position:fixed;bottom:80px;right:10px;display:flex;flex-direction:column;align-items:center;z-index:999;text-decoration:none}
.float-service img{width:52px;height:52px;border-radius:50%;object-fit:cover}
.float-service span{font-size:10px;color:#3a5a2a;font-weight:600;text-align:center;margin-top:2px}

.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 svg{width:22px;height:22px}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span,.bn-item.active svg{color:#3eaabb}
.bn-item:not(.active) span,.bn-item:not(.active) svg{color:#aaa}

.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)}
</style>
</head>
<body>

<!-- Top Bar -->
<div class="top-bar">
  <a href="home.php">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>
  </a>
  <h1>Team Report</h1>
  <div style="width:22px"></div>
</div>

<!-- Main Tabs -->
<div class="main-tabs">
  <a href="?tab=report&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&ltab=<?= $level_tab ?>"
     class="main-tab <?= $tab==='report' ? 'active' : '' ?>">Team Report</a>
  <a href="?tab=myteam&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&ltab=<?= $level_tab ?>"
     class="main-tab <?= $tab==='myteam' ? 'active' : '' ?>">My Team</a>
</div>

<?php if ($tab === 'report'): ?>

<!-- Date Filter -->
<form method="GET" action="">
  <input type="hidden" name="tab" value="report">
  <input type="hidden" name="ltab" value="<?= htmlspecialchars($level_tab) ?>">
  <div class="date-filter">
    <input type="date" name="date_from" value="<?= $date_from ?>">
    <span>-</span>
    <input type="date" name="date_to" value="<?= $date_to ?>">
    <button type="submit">Search</button>
  </div>
</form>

<!-- Summary Grid -->
<div class="summary-grid">
  <div class="sg-cell">
    <div class="sv"><?= $team_size ?></div>
    <div class="sl">Team Size<br>(People)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= $new_adds ?></div>
    <div class="sl">New Additions<br>(People)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= $grade_a ?></div>
    <div class="sl">Grade A<br>(People)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= $abc_fulltime ?></div>
    <div class="sl">ABC Full-time<br>Employees(People)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= $team_tasks ?></div>
    <div class="sl">Tasks Completed<br>by ABC</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= number_format($total_withdrawal,3) ?></div>
    <div class="sl">Total Withdrawal<br>by ABC (<?= $currency ?>)</div>
  </div>
</div>

<!-- Level Tabs -->
<div class="level-tabs">
  <?php foreach(['a'=>'Level A','b'=>'Level B','c'=>'Level C','abc'=>'ABC Total'] as $k=>$label): ?>
  <a href="?tab=report&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&ltab=<?= $k ?>"
     class="level-tab <?= $level_tab===$k ? 'active' : '' ?>"><?= $label ?></a>
  <?php endforeach; ?>
</div>

<!-- Stats Cards -->
<div class="stats-cards">
  <div class="stat-card">
    <div class="sv"><?= $active_stats['fulltime'] ?></div>
    <div class="sl">Full-time Employee (People)</div>
  </div>
  <div class="stat-card">
    <div class="sv"><?= $active_stats['total_tasks'] ?></div>
    <div class="sl">Total Number of Tasks</div>
  </div>
  <div class="stat-card">
    <div class="sv"><?= $active_stats['completed'] ?></div>
    <div class="sl">Completed Tasks</div>
  </div>
  <div class="stat-card">
    <div class="sv"><?= $active_stats['remaining'] ?></div>
    <div class="sl">Remaining Task Quantity</div>
  </div>
</div>

<!-- Per-Plan Table -->
<div class="plan-table">
  <div class="plan-table-head">
    <span>Level</span>
    <span>Full-time Employee</span>
    <span>Completed Tasks</span>
  </div>
  <?php foreach($all_plans_list as $pl):
    $ps = getPlanLevelStats($conn, $pl['id'], $current_ids, $date_from, $date_to);
  ?>
  <div class="plan-row">
    <div class="plan-name"><?= htmlspecialchars($pl['name']) ?></div>
    <div class="plan-val"><?= $ps['fulltime'] ?></div>
    <div class="plan-val"><?= $ps['completed'] ?></div>
  </div>
  <?php endforeach; ?>
</div>

<?php else: /* My Team tab */ ?>

<!-- Referral Code + Full Invite Link -->
<div class="ref-box">
  <div class="ref-code-label">Your Referral Code</div>
  <div class="ref-code"><?= htmlspecialchars($referral_code) ?></div>
  <div class="ref-url-label">🌐 Full Invitation Link:</div>
  <div class="ref-url" id="teamInviteLink"><?= htmlspecialchars($invite_link) ?></div>
  <button class="ref-copy-btn" onclick="copyInviteLink()">📋 Copy Invite Link</button>
  <div class="ref-note">Share this link to earn referral commissions</div>
</div>

<!-- Team Level Summary -->
<div class="summary-grid" style="grid-template-columns:repeat(3,1fr)">
  <div class="sg-cell">
    <div class="sv"><?= count($l1ids) ?></div>
    <div class="sl">Level A<br>(Direct)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= count($l2ids) ?></div>
    <div class="sl">Level B<br>(2nd tier)</div>
  </div>
  <div class="sg-cell">
    <div class="sv"><?= count($l3ids) ?></div>
    <div class="sl">Level C<br>(3rd tier)</div>
  </div>
</div>

<?php if (empty($my_team_members)): ?>
  <div style="text-align:center;padding:40px 20px;color:#666;font-size:14px;background:#fff;margin-top:8px">
    <div style="font-size:32px;margin-bottom:10px">👥</div>
    No team members yet.<br>Share your invite link to invite friends!
  </div>
<?php else: ?>
<div class="member-list">
  <?php foreach($my_team_members as $m):
    $mphone = '***'.substr($m['phone'],-7);
    $isPaid = !empty($m['plan_name']) && !$m['is_free'];
  ?>
  <div class="member-card">
    <div class="member-avatar">
      <svg viewBox="0 0 24 24"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z"/></svg>
    </div>
    <div class="member-info">
      <div class="member-phone"><?= htmlspecialchars($mphone) ?></div>
      <div class="member-plan"><?= htmlspecialchars($m['plan_name'] ?? 'No plan') ?></div>
      <div class="member-date">Joined: <?= date('Y-m-d', strtotime($m['created_at'])) ?></div>
    </div>
    <span class="member-badge <?= $isPaid ? 'badge-active' : 'badge-free' ?>">
      <?= $isPaid ? 'Active' : 'Free' ?>
    </span>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<?php endif; ?>

<!-- Float Service -->
<a href="<?= htmlspecialchars($support_url) ?>" target="_blank" class="float-service">
  <img src="care.png" alt="" onerror="this.style.display='none'">
  <span>Online Service</span>
</a>

<div class="toast" id="toast"></div>

<!-- Bottom Nav -->
<?php include 'navigation_bottom.php'; ?>

<script>
const teamInviteLink = <?= json_encode($invite_link) ?>;

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

function copyInviteLink() {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(teamInviteLink).then(() => showToast('✅ Invite link copied!'));
  } else {
    const ta = document.createElement('textarea');
    ta.value = teamInviteLink;
    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('✅ Invite link copied!');
  }
}
</script>
</body>
</html>