<?php
require_once("auth.php");
include("header.php");

/* ══════════════════════════════════════════════════════════
   REMOVED — Agent আর কোনো User-এর Coin সরাসরি বাড়াতে/কমাতে
   পারবে না। এই পেজ এখন শুধু দেখার জন্য (Balance, Bet, আর
   এই User থেকে Agent কত Commission পেয়েছে সেই হিসাব সহ)।
   ══════════════════════════════════════════════════════════ */

// এই Agent-এর নিজের Commission Rate
$rateRow = $conn->query("SELECT commission_rate FROM tb_agent WHERE userid = '".$agent_uid."'")->fetch_assoc();
$MY_RATE = $rateRow && $rateRow['commission_rate'] !== null ? floatval($rateRow['commission_rate']) : 30.0;

// এই Agent-এর owncode যেসব User signup-এর সময় ব্যবহার করেছে, তারাই তার downline
$downline = [];
$stmt = $conn->prepare("
    SELECT id, mobile, status, createdate,
           COALESCE((SELECT motta FROM shonu_kaichila WHERE balakedara = shonu_subjects.id), 0) AS balance
    FROM shonu_subjects
    WHERE code = ?
    ORDER BY createdate DESC
");
$stmt->bind_param("s", $agent_owncode);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $downline[] = $row;
}
$stmt->close();

// প্রতিটা User-এর জন্য আলাদা করে Bet/Win/GGR/Commission বের করা
foreach ($downline as &$u) {
    $betRow = $conn->query("SELECT COALESCE(SUM(bet_amount),0) as tb, COALESCE(SUM(win_amount),0) as tw FROM game_bet_logs WHERE user_id = '".$u['id']."'")->fetch_assoc();
    $totalBet = floatval($betRow['tb']);
    $totalWin = floatval($betRow['tw']);
    $ggr = max(0, $totalBet - $totalWin);
    $u['total_bet'] = $totalBet;
    $u['ggr'] = $ggr;
    $u['commission_earned'] = round($ggr * ($MY_RATE / 100), 2);
}
unset($u);

$total_users = count($downline);
$active_users = count(array_filter($downline, fn($u) => intval($u['status']) === 1));
$total_commission_from_all = array_sum(array_column($downline, 'commission_earned'));
?>

<div class="al-wrap">
  <div class="al-page-title">আমার Downline Users</div>
  <div class="al-page-sub">তোমার Invitation Code দিয়ে যত জন Join করেছে</div>

  <?php if ($total_commission_from_all > 0): ?>
    <div class="al-card" style="border-left:3px solid var(--cyan); margin-bottom:14px; padding:12px 16px; font-size:13px;">
      💰 সব User মিলিয়ে তোমার মোট Commission: <b class="mono">৳<?php echo number_format($total_commission_from_all, 2); ?></b>
      (Commission Rate: <?php echo $MY_RATE; ?>% of GGR)
    </div>
  <?php endif; ?>

  <div style="display:flex; gap:12px; margin-bottom:16px;">
    <div class="al-card" style="flex:1; text-align:center; padding:14px;">
      <div style="font-size:11px; color:var(--text-dim);">মোট User</div>
      <div style="font-size:22px; font-weight:700; color:var(--gold);"><?php echo $total_users; ?></div>
    </div>
    <div class="al-card" style="flex:1; text-align:center; padding:14px;">
      <div style="font-size:11px; color:var(--text-dim);">Active User</div>
      <div style="font-size:22px; font-weight:700; color:#1FB979;"><?php echo $active_users; ?></div>
    </div>
  </div>

  <?php if (empty($downline)): ?>
    <div class="al-card" style="text-align:center; color:var(--text-dim); padding:30px;">
      এখনো কোনো User তোমার Code দিয়ে Join করেনি।<br>
      উপরের Dashboard থেকে তোমার Invitation Link Share করো।
    </div>
  <?php else: ?>
    <?php foreach ($downline as $user): ?>
      <?php $isActive = intval($user['status']) === 1; ?>
      <div class="al-card" style="margin-bottom:10px; padding:12px 16px; <?php echo $isActive ? '' : 'opacity:.55;'; ?>">
        <div style="display:flex; justify-content:space-between; align-items:center;">
          <div>
            <div style="font-weight:700; color:var(--text); font-size:14px;">
              <?php echo htmlspecialchars($user['mobile']); ?>
            </div>
            <div style="font-size:11.5px; color:var(--text-dim); margin-top:2px;">
              যোগদান: <?php echo htmlspecialchars($user['createdate']); ?>
              &nbsp;|&nbsp;
              <?php echo $isActive ? '<span style="color:#1FB979;">Active</span>' : '<span style="color:#E8544A;">Inactive</span>'; ?>
            </div>
          </div>
          <div style="text-align:right;">
            <div class="mono" style="font-size:13px; color:var(--gold); font-weight:600;">
              ৳<?php echo number_format((float)$user['balance'], 2); ?>
            </div>
            <div style="font-size:10px; color:var(--text-dim);">Balance</div>
          </div>
        </div>
        <div style="display:flex; gap:10px; margin-top:10px; padding-top:10px; border-top:1px solid var(--border);">
          <div style="flex:1; text-align:center;">
            <div class="mono" style="font-size:12.5px; color:var(--text);">৳<?php echo number_format($user['total_bet'], 2); ?></div>
            <div style="font-size:10px; color:var(--text-dim);">মোট Bet</div>
          </div>
          <div style="flex:1; text-align:center;">
            <div class="mono" style="font-size:12.5px; color:var(--text);">৳<?php echo number_format($user['ggr'], 2); ?></div>
            <div style="font-size:10px; color:var(--text-dim);">GGR</div>
          </div>
          <div style="flex:1; text-align:center;">
            <div class="mono" style="font-size:12.5px; color:var(--cyan); font-weight:700;">৳<?php echo number_format($user['commission_earned'], 2); ?></div>
            <div style="font-size:10px; color:var(--text-dim);">আমার Commission</div>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
</body>
</html>
