<?php
require_once __DIR__ . '/auth.php';

$search = trim($_GET['q'] ?? '');
$sort   = $_GET['sort'] ?? 'newest';
$page   = max(1, (int)($_GET['p'] ?? 1));
$limit  = 20; 
$offset = ($page - 1) * $limit;

$where = $search ? "WHERE number LIKE ? OR id LIKE ? OR member_name LIKE ?" : "";
$params = $search ? ["%$search%", "%$search%", "%$search%"] : [];

// Advanced Filtering Logic
$selectCols = "*";
$orderBy = "id DESC";

switch ($sort) {
    case 'balance':
        $orderBy = "balance DESC";
        break;
    case 'deposits':
        $orderBy = "total_deposits DESC";
        break;
    case 'withdrawals':
        $orderBy = "COALESCE(total_withdrawn, 0) DESC";
        break;
    case 'wager':
        $orderBy = "wager DESC";
        break;
    case 'commission':
        $orderBy = "COALESCE(total_commission, 0) DESC";
        break;
    case 'referrers':
        // Subquery to count how many users used this user's refercode
        $selectCols = "*, (SELECT COUNT(*) FROM users u2 WHERE u2.referedby = users.refercode) AS ref_count";
        $orderBy = "ref_count DESC";
        break;
    case 'newest':
    default:
        $orderBy = "id DESC";
        break;
}

// Fetch Total for Pagination
$st = $pdo->prepare("SELECT COUNT(*) FROM users $where"); 
$st->execute($params); 
$total = (int)$st->fetchColumn();

// Fetch Users with Filters
$st2 = $pdo->prepare("SELECT $selectCols FROM users $where ORDER BY $orderBy LIMIT $limit OFFSET $offset"); 
$st2->execute($params); 
$users = $st2->fetchAll();

$pages = max(1, ceil($total / $limit));

// Fetch selected user detail
$viewUser = null;
if (!empty($_GET['uid'])) {
    $st3 = $pdo->prepare("SELECT * FROM users WHERE id=?"); 
    $st3->execute([(int)$_GET['uid']]); 
    $viewUser = $st3->fetch();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Users — 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:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px}
.search-bar{display:flex;gap:12px;margin-bottom:20px;flex-wrap:wrap;}
.search-bar input, .search-bar select{
  background:#1e2130;border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:10px 16px;color:#fff;font-size:14px;outline:none;
}
.search-bar input{flex:1;}
.search-bar input:focus, .search-bar select: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}
.btn-blue{background:#3b82f6;color:#fff}
.btn-green{background:#22c55e;color:#000}
.btn-red{background:#ef4444;color:#fff}
.btn-gray{background:#374151;color:#e5e7eb}
.btn-sm{padding:6px 12px;font-size:12px;border-radius:7px}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;overflow-x:auto;}
table{width:100%;border-collapse:collapse;font-size:13px;min-width:800px;}
th{padding:11px 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:12px 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-ok{background:rgba(34,197,94,.15);color:#22c55e}
.pill-ban{background:rgba(239,68,68,.15);color:#ef4444}
.actions{display:flex;gap:6px;flex-wrap:wrap}
.pagination{display:flex;gap:6px;margin-top:20px;justify-content:flex-end;flex-wrap:wrap;}
.pagination a{padding:7px 13px;border-radius:8px;background:#1e2130;border:1px solid rgba(255,255,255,.08);color:#9ca3af;text-decoration:none;font-size:13px}
.pagination a.cur{background:#f26d0f;color:#fff;border-color:#f26d0f}
/* Modal */
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:999;display:none;align-items:center;justify-content:center;padding:20px}
.modal-bg.open{display:flex}
.modal{background:#1a1f2e;border:1px solid rgba(255,255,255,.1);border-radius:16px;width:100%;max-width:520px;max-height:90vh;overflow-y:auto}
.modal-head{padding:20px 24px;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}
.modal-head h3{font-size:17px;font-weight:700;color:#fff}
.modal-close{background:none;border:none;color:#9ca3af;font-size:20px;cursor:pointer;padding:0}
.modal-body{padding:24px}
.info-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px}
.info-item label{display:block;font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;margin-bottom:4px}
.info-item .val{font-size:15px;font-weight:600;color:#fff}
.info-item .val.orange{color:#f26d0f}
.edit-row{display:flex;gap:10px;align-items:center;margin-bottom:12px}
.edit-row label{font-size:13px;color:#9ca3af;width:90px}
.edit-row input{flex:1;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:8px 12px;color:#fff;font-size:14px;outline:none}
.edit-row input:focus{border-color:#f26d0f}
.sec-title{font-size:13px;font-weight:700;color:#f26d0f;text-transform:uppercase;letter-spacing:.8px;margin:20px 0 12px}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-users" style="color:#f26d0f;margin-right:10px"></i>Users</h2>
    <span style="color:#8892a4;font-size:13px"><?= number_format($total) ?> total</span>
  </div>
  <div class="content">
    <form class="search-bar" method="GET">
      <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Search by phone, UID or name…">
      
      <select name="sort" onchange="this.form.submit()">
        <option value="newest" <?= $sort == 'newest' ? 'selected' : '' ?>>Date: Newest First</option>
        <option value="balance" <?= $sort == 'balance' ? 'selected' : '' ?>>Biggest Balance</option>
        <option value="deposits" <?= $sort == 'deposits' ? 'selected' : '' ?>>Biggest Depositor</option>
        <option value="withdrawals" <?= $sort == 'withdrawals' ? 'selected' : '' ?>>Biggest Withdrawer</option>
        <option value="wager" <?= $sort == 'wager' ? 'selected' : '' ?>>Highest Wager</option>
        <option value="commission" <?= $sort == 'commission' ? 'selected' : '' ?>>Highest Commission</option>
        <option value="referrers" <?= $sort == 'referrers' ? 'selected' : '' ?>>Top Referrers (Network)</option>
      </select>

      <button type="submit" class="btn btn-orange"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
      <?php if ($search || $sort != 'newest'): ?>
        <a href="users.php" class="btn btn-gray"><i class="fa-solid fa-xmark"></i> Clear</a>
      <?php endif; ?>
    </form>

    <div class="card">
      <table>
        <tr>
          <th>ID</th>
          <th>Phone</th>
          <th>Name</th>
          <th>Balance</th>
          <th>Wager</th>
          <th>Deposits</th>
          <?php if($sort === 'referrers'): ?><th>Refs</th><?php endif; ?>
          <th>Status</th>
          <th>Joined</th>
          <th>Actions</th>
        </tr>
        <?php foreach($users as $u): ?>
        <tr>
          <td>
            #<?= $u['id'] ?>
            <?php if(isset($u['is_demo']) && $u['is_demo']): ?>
              <span class="pill" style="background:rgba(168,85,247,.15);color:#a855f7;padding:2px 6px;font-size:10px;font-weight:bold;margin-left:4px">Demo</span>
            <?php endif; ?>
          </td>
          <td><?= htmlspecialchars($u['number']) ?></td>
          <td><?= htmlspecialchars($u['member_name']??'-') ?></td>
          <td style="color:#22c55e;font-weight:600">Rs<?= number_format($u['balance'], 2) ?></td>
          <td style="color:#f59e0b">Rs<?= number_format($u['wager'], 2) ?></td>
          <td>Rs<?= number_format($u['total_deposits'], 2) ?></td>
          <?php if($sort === 'referrers'): ?><td style="color:#3b82f6;font-weight:bold;"><?= $u['ref_count'] ?></td><?php endif; ?>
          <td><span class="pill <?= $u['isbanned']?'pill-ban':'pill-ok' ?>"><?= $u['isbanned']?'Banned':'Active' ?></span></td>
          <td><?= date('M d Y', strtotime($u['created_at'])) ?></td>
          <td>
            <div class="actions">
              <a href="?<?= http_build_query(array_merge($_GET, ['uid'=>$u['id']])) ?>" class="btn btn-blue btn-sm"><i class="fa-solid fa-eye"></i></a>
              <button class="btn btn-orange btn-sm" onclick="loginAs(<?= $u['id'] ?>)"><i class="fa-solid fa-right-to-bracket"></i></button>
              <button class="btn btn-<?= $u['isbanned']?'green':'red' ?> btn-sm" onclick="toggleBan(<?= $u['id'] ?>,this)"><?= $u['isbanned']?'Unban':'Ban' ?></button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$users): ?><tr><td colspan="<?= $sort === 'referrers' ? '10' : '9' ?>" style="text-align:center;padding:30px;color:#4b5563">No users found</td></tr><?php endif; ?>
      </table>
    </div>
    
    <?php if($pages > 1): ?>
    <div class="pagination">
      <?php for($i=1; $i<=$pages; $i++): ?>
      <a href="?<?= http_build_query(array_merge($_GET, ['p'=>$i, 'uid'=>null])) ?>" class="<?= $i === $page ? 'cur' : '' ?>"><?= $i ?></a>
      <?php endfor; ?>
    </div>
    <?php endif; ?>
  </div>
</div>

<?php if($viewUser): $u=$viewUser; ?>
<div class="modal-bg open" id="userModal">
  <div class="modal">
    <div class="modal-head">
      <h3>User #<?= $u['id'] ?> — <?= htmlspecialchars($u['number']) ?></h3>
      <button class="modal-close" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <div class="modal-body">
      <div class="info-grid">
        <div class="info-item"><label>UID</label><div class="val"><?= $u['id'] ?></div></div>
        <div class="info-item"><label>Phone</label><div class="val"><?= htmlspecialchars($u['number']) ?></div></div>
        <div class="info-item"><label>Name</label><div class="val"><?= htmlspecialchars($u['member_name']??'-') ?></div></div>
        <div class="info-item"><label>Password</label><div class="val" style="font-size:13px;word-break:break-all"><?= htmlspecialchars($u['password']) ?></div></div>
        <div class="info-item"><label>Balance</label><div class="val orange">Rs<?= number_format($u['balance'],2) ?></div></div>
        <div class="info-item"><label>Wager</label><div class="val" style="color:#f59e0b">Rs<?= number_format($u['wager'],2) ?></div></div>
        <div class="info-item"><label>Total Deposits</label><div class="val">Rs<?= number_format($u['total_deposits'],2) ?></div></div>
        <div class="info-item"><label>Total Withdrawn</label><div class="val">Rs<?= number_format($u['total_withdrawn']??0,2) ?></div></div>
        <div class="info-item"><label>Referral Code</label><div class="val"><?= htmlspecialchars($u['refercode']) ?></div></div>
        <div class="info-item"><label>Referred By</label><div class="val"><?= htmlspecialchars($u['referedby']??'-') ?></div></div>
        <div class="info-item"><label>Total Commission</label><div class="val">Rs<?= number_format($u['total_commission']??0,2) ?></div></div>
        <?php $refs=(int)$pdo->query("SELECT COUNT(*) FROM users WHERE referedby='{$u['refercode']}'")->fetchColumn(); ?>
        <div class="info-item"><label>Total Refers</label><div class="val"><?= $refs ?></div></div>
        <div class="info-item"><label>Status</label><div class="val <?= $u['isbanned']?'':'orange' ?>"><?= $u['isbanned']?'<span style="color:#ef4444">Banned</span>':'Active' ?></div></div>
        <div class="info-item"><label>Joined</label><div class="val" style="font-size:13px"><?= $u['created_at'] ?></div></div>
        <div class="info-item"><label>Account Type</label><div class="val" id="drawerDemoState" style="color:<?= $u['is_demo']?'#a855f7':'#22c55e' ?>"><?= $u['is_demo']?'Demo':'Normal' ?></div></div>
      </div>

      <div class="sec-title">Edit Balance</div>
      <div class="edit-row"><label>Amount</label><input type="number" id="balAmt" placeholder="0.00" min="0" step="0.01"></div>
      <div style="display:flex;gap:8px;margin-bottom:16px">
        <button class="btn btn-green btn-sm" onclick="editBal('add')"><i class="fa-solid fa-plus"></i> Add</button>
        <button class="btn btn-red btn-sm" onclick="editBal('remove')"><i class="fa-solid fa-minus"></i> Remove</button>
      </div>

      <div class="sec-title">Edit Wager</div>
      <div class="edit-row"><label>Amount</label><input type="number" id="wagAmt" placeholder="0.00" min="0" step="0.01"></div>
      <div style="display:flex;gap:8px;margin-bottom:16px">
        <button class="btn btn-green btn-sm" onclick="editWag('add')"><i class="fa-solid fa-plus"></i> Add</button>
        <button class="btn btn-red btn-sm" onclick="editWag('remove')"><i class="fa-solid fa-minus"></i> Remove</button>
      </div>

      <div style="display:flex;gap:10px;margin-top:8px;flex-wrap:wrap">
        <button class="btn btn-orange" onclick="loginAs(<?= $u['id'] ?>)"><i class="fa-solid fa-right-to-bracket"></i> Login As</button>
        <button class="btn btn-purple" id="btnToggleDemo" style="background:#a855f7;color:#fff" onclick="toggleDemo(<?= $u['id'] ?>,this)"><i class="fa-solid fa-user-gear"></i> <?= $u['is_demo']?'Remove Demo':'Make Demo' ?></button>
        <button class="btn btn-<?= $u['isbanned']?'green':'red' ?>" onclick="toggleBan(<?= $u['id'] ?>,this)"><?= $u['isbanned']?'Unban User':'Ban User' ?></button>
        <a href="referrals.php?uid=<?= $u['id'] ?>" class="btn btn-blue"><i class="fa-solid fa-people-group"></i> Referral Data</a>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<div id="toast" style="position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:rgba(20,20,20,.9);backdrop-filter:blur(10px);color:#fff;padding:12px 24px;border-radius:30px;font-size:13px;display:none;z-index:9999"></div>

<script>
function closeModal(){
    // Preserve existing sort and search params when closing modal
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.delete('uid');
    window.location.href = 'users.php?' + urlParams.toString();
}
function toast(m,ok=true){const t=document.getElementById('toast');t.style.display='block';t.style.borderLeft='3px solid '+(ok?'#22c55e':'#ef4444');t.innerText=m;setTimeout(()=>t.style.display='none',2500);}
function api(data,cb){
  const fd=new FormData();for(const[k,v]of Object.entries(data))fd.append(k,v);
  fetch('actions.php',{method:'POST',body:fd}).then(r=>r.json()).then(cb).catch(()=>toast('Network error',false));
}
function loginAs(uid){if(!confirm('Login as this user? You will be redirected to the main site.'))return;api({action:'login_as',uid},r=>r.ok?window.open(r.redirect,'_blank'):toast(r.msg,false));}
function toggleBan(uid,btn){api({action:'ban_user',uid},r=>{if(r.ok){toast(r.banned?'User banned':'User unbanned');btn.textContent=r.banned?'Unban':'Ban';btn.className=btn.className.replace(r.banned?'btn-red':'btn-green',r.banned?'btn-green':'btn-red');}else toast(r.msg,false);});}
function toggleDemo(uid,btn){if(!confirm('Change this user\'s account type?'))return;api({action:'toggle_demo',uid},r=>{if(r.ok){toast(r.is_demo?'Account set to Demo':'Account set to Normal');btn.innerHTML='<i class="fa-solid fa-user-gear"></i> '+(r.is_demo?'Remove Demo':'Make Demo');document.getElementById('drawerDemoState').innerText=r.is_demo?'Demo':'Normal';document.getElementById('drawerDemoState').style.color=r.is_demo?'#a855f7':'#22c55e';}else toast(r.msg,false);});}
function editBal(op){const amt=document.getElementById('balAmt').value;if(!amt||amt<=0)return toast('Enter a valid amount',false);api({action:'edit_balance',uid:<?= ($viewUser['id']??0) ?>,amount:amt,op},r=>r.ok?toast('Balance updated ✓'):toast(r.msg,false));}
function editWag(op){const amt=document.getElementById('wagAmt').value;if(!amt||amt<=0)return toast('Enter a valid amount',false);api({action:'edit_wager',uid:<?= ($viewUser['id']??0) ?>,amount:amt,op},r=>r.ok?toast('Wager updated ✓'):toast(r.msg,false));}
</script>
</body></html>