<?php
require_once __DIR__ . '/auth.php';
$uid = (int)($_GET['uid'] ?? 0);
$data = null; $error = '';

if ($uid) {
    $u = $pdo->prepare("SELECT * FROM users WHERE id=?"); $u->execute([$uid]); $user=$u->fetch();
    if (!$user) { $error="No user found with UID #$uid"; }
    else {
        $rc = $user['refercode'];
        // Direct (L1) refers
        $dir = $pdo->prepare("SELECT COUNT(*) as cnt, SUM(total_deposits) as dep_amt, SUM(CASE WHEN total_deposits>0 THEN 1 ELSE 0 END) as dep_users FROM users WHERE referedby=?");
        $dir->execute([$rc]); $dir=$dir->fetch();
        // Team (L2+L3) refers
        $team = $pdo->query("SELECT COUNT(*) as cnt, SUM(total_deposits) as dep_amt, SUM(CASE WHEN total_deposits>0 THEN 1 ELSE 0 END) as dep_users FROM users WHERE referedby IN (SELECT refercode FROM users WHERE referedby='$rc') OR referedby IN (SELECT refercode FROM users WHERE referedby IN (SELECT refercode FROM users WHERE referedby='$rc'))")->fetch();
        // Yesterday refers
        $yday_ref = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE referedby='$rc' AND DATE(created_at)=DATE_SUB(CURDATE(),INTERVAL 1 DAY)")->fetchColumn();
        // Yesterday deposits from direct
        $yday_dep = (float)$pdo->query("SELECT COALESCE(SUM(d.amount),0) FROM deposits d JOIN users u ON d.user_id=u.id WHERE u.referedby='$rc' AND d.status='approved' AND DATE(d.created_at)=DATE_SUB(CURDATE(),INTERVAL 1 DAY)")->fetchColumn();
        // Commission breakdown
        $comm_l1 = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM referral_commissions WHERE user_id={$user['id']} AND level=1")->fetchColumn();
        $comm_l2 = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM referral_commissions WHERE user_id={$user['id']} AND level=2")->fetchColumn();
        $comm_l3 = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM referral_commissions WHERE user_id={$user['id']} AND level=3")->fetchColumn();
        $first_dep_comm = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM referral_commissions WHERE user_id={$user['id']} AND is_first_deposit=1")->fetchColumn();
        // Recent commission activity
        $recent_comms = $pdo->query("SELECT rc.*,u.number as from_number FROM referral_commissions rc JOIN users u ON rc.from_user_id=u.id WHERE rc.user_id={$user['id']} ORDER BY rc.id DESC LIMIT 15")->fetchAll();
        // Direct refers list
        $dir_list = $pdo->prepare("SELECT id,number,member_name,total_deposits,created_at FROM users WHERE referedby=? ORDER BY id DESC LIMIT 20"); $dir_list->execute([$rc]); $dir_list=$dir_list->fetchAll();
        $data=compact('user','dir','team','yday_ref','yday_dep','comm_l1','comm_l2','comm_l3','first_dep_comm','recent_comms','dir_list');
    }
}
?><!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Referrals — PakClub Admin</title>
<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}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:auto}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;gap:20px}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px}
.search-form{display:flex;gap:12px;margin-bottom:24px;max-width:480px}
.search-form input{flex:1;background:#1e2130;border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:11px 16px;color:#fff;font-size:14px;outline:none}
.search-form input:focus{border-color:#f26d0f}
.btn{padding:10px 18px;border-radius:10px;border:none;cursor:pointer;font-size:13px;font-weight:600;display:inline-flex;align-items:center;gap:7px;transition:opacity .2s}
.btn:hover{opacity:.85}
.btn-orange{background:#f26d0f;color:#fff}
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px}
.grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:20px}
.stat-card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;padding:20px}
.sc-label{font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:.7px;margin-bottom:8px;font-weight:600}
.sc-val{font-size:24px;font-weight:800;color:#fff}
.sc-val.orange{color:#f26d0f}
.sc-val.green{color:#22c55e}
.sc-val.blue{color:#3b82f6}
.section-title{font-size:14px;font-weight:700;color:#f26d0f;text-transform:uppercase;letter-spacing:.8px;margin:20px 0 12px;display:flex;align-items:center;gap:8px}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;margin-bottom:16px}
table{width:100%;border-collapse:collapse;font-size:13px}
th{padding:10px 16px;color:#4b5563;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.06);text-align:left;font-weight:600}
td{padding:11px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}
.pill{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.pill-1{background:rgba(242,109,15,.15);color:#f26d0f}
.pill-2{background:rgba(59,130,246,.15);color:#3b82f6}
.pill-3{background:rgba(168,85,247,.15);color:#a855f7}
.err{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:10px;padding:16px 20px;color:#f87171;font-size:14px;margin-bottom:20px}
.user-info-bar{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:12px;padding:14px 20px;margin-bottom:20px;display:flex;align-items:center;gap:20px;flex-wrap:wrap}
.uib-item label{font-size:11px;color:#6b7280;display:block;margin-bottom:3px}
.uib-item span{font-size:14px;font-weight:600;color:#fff}
@media(max-width:900px){.grid-2,.grid-3{grid-template-columns:1fr}}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-people-group" style="color:#f26d0f;margin-right:10px"></i>Referral Lookup</h2>
  </div>
  <div class="content">
    <form class="search-form" method="GET">
      <input type="number" name="uid" value="<?= $uid ?: '' ?>" placeholder="Enter User UID…" min="1">
      <button type="submit" class="btn btn-orange"><i class="fa-solid fa-magnifying-glass"></i> Lookup</button>
    </form>

    <?php if($error): ?><div class="err"><i class="fa-solid fa-circle-exclamation"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

    <?php if($data): extract($data); ?>
    <div class="user-info-bar">
      <div class="uib-item"><label>UID</label><span>#<?= $user['id'] ?></span></div>
      <div class="uib-item"><label>Phone</label><span><?= htmlspecialchars($user['number']) ?></span></div>
      <div class="uib-item"><label>Name</label><span><?= htmlspecialchars($user['member_name']??'-') ?></span></div>
      <div class="uib-item"><label>Referral Code</label><span style="color:#f26d0f;font-family:monospace"><?= $user['refercode'] ?></span></div>
      <div class="uib-item"><label>Referred By</label><span><?= $user['referedby']??'—' ?></span></div>
    </div>

    <div class="section-title"><i class="fa-solid fa-users"></i> Team Overview</div>
    <div class="grid-3">
      <div class="stat-card"><div class="sc-label">Direct Refers (L1)</div><div class="sc-val orange"><?= $dir['cnt'] ?></div></div>
      <div class="stat-card"><div class="sc-label">Team Refers (L2+L3)</div><div class="sc-val blue"><?= $team['cnt'] ?></div></div>
      <div class="stat-card"><div class="sc-label">Yesterday New Refers</div><div class="sc-val"><?= $yday_ref ?></div></div>
    </div>

    <div class="section-title"><i class="fa-solid fa-money-bill-wave"></i> Deposit Stats</div>
    <div class="grid-2">
      <div class="stat-card"><div class="sc-label">Direct Deposit Users</div><div class="sc-val green"><?= $dir['dep_users'] ?></div></div>
      <div class="stat-card"><div class="sc-label">Direct Deposit Total</div><div class="sc-val green">Rs<?= number_format($dir['dep_amt']??0,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">Team Deposit Users</div><div class="sc-val"><?= $team['dep_users'] ?></div></div>
      <div class="stat-card"><div class="sc-label">Team Deposit Total</div><div class="sc-val">Rs<?= number_format($team['dep_amt']??0,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">Yesterday's Deposits</div><div class="sc-val orange">Rs<?= number_format($yday_dep,2) ?></div></div>
    </div>

    <div class="section-title"><i class="fa-solid fa-coins"></i> Commission Earned</div>
    <div class="grid-3">
      <div class="stat-card"><div class="sc-label">L1 Commission</div><div class="sc-val orange">Rs<?= number_format($comm_l1,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">L2 Commission</div><div class="sc-val blue">Rs<?= number_format($comm_l2,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">L3 Commission</div><div class="sc-val" style="color:#a855f7">Rs<?= number_format($comm_l3,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">First Dep. Commission</div><div class="sc-val green">Rs<?= number_format($first_dep_comm,2) ?></div></div>
      <div class="stat-card"><div class="sc-label">Total Commission</div><div class="sc-val orange">Rs<?= number_format($comm_l1+$comm_l2+$comm_l3,2) ?></div></div>
    </div>

    <?php if($dir_list): ?>
    <div class="section-title"><i class="fa-solid fa-list"></i> Direct Referrals</div>
    <div class="card">
      <table>
        <tr><th>UID</th><th>Phone</th><th>Name</th><th>Total Deposits</th><th>Joined</th></tr>
        <?php foreach($dir_list as $r): ?>
        <tr>
          <td>#<?= $r['id'] ?></td>
          <td><?= htmlspecialchars($r['number']) ?></td>
          <td><?= htmlspecialchars($r['member_name']??'-') ?></td>
          <td style="color:<?= $r['total_deposits']>0?'#22c55e':'#4b5563' ?>"><?= $r['total_deposits']>0?'Rs'.number_format($r['total_deposits'],2):'—' ?></td>
          <td style="font-size:12px"><?= date('M d Y',strtotime($r['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php endif; ?>

    <?php if($recent_comms): ?>
    <div class="section-title"><i class="fa-solid fa-clock-rotate-left"></i> Recent Commission Activity</div>
    <div class="card">
      <table>
        <tr><th>From User</th><th>Level</th><th>Type</th><th>Amount</th><th>Date</th></tr>
        <?php foreach($recent_comms as $c): ?>
        <tr>
          <td><?= htmlspecialchars($c['from_number']) ?></td>
          <td><span class="pill pill-<?= $c['level'] ?>">L<?= $c['level'] ?></span></td>
          <td><?= $c['is_first_deposit']?'<span style="color:#f59e0b">First Dep.</span>':'Regular' ?></td>
          <td style="color:#22c55e;font-weight:600">+Rs<?= number_format($c['amount'],2) ?></td>
          <td style="font-size:12px"><?= date('M d H:i',strtotime($c['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php endif; ?>
    <?php endif; ?>
  </div>
</div>
</body></html>
