<?php

$conn      = mysqli_connect("localhost","verrifyi_unique","verrifyi_unique","verrifyi_unique");
$bot_token = "7712681015:AAGbAzTvKnOn97pX0SgnGOYbfiP0O_QJuDE";

// ── DISCONNECT USER ──────────────────────────────────────────────
if(isset($_POST['disconnect']) && !empty($_POST['chat_id'])){
    $chat_id = mysqli_real_escape_string($conn, $_POST['chat_id']);

    // Telegram_users se delete karo (disconnect)
    mysqli_query($conn,"DELETE FROM telegram_users WHERE chat_id='$chat_id'");

    // User ko notify karo
    $msg = "⚠️ Aapka Telegram disconnect kar diya gaya hai.\n\nDobara connect karne ke liye website pe jaao aur Telegram Connect karo.";
    @file_get_contents("https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=".urlencode($msg));

    $disconnect_msg = "✅ User disconnect kar diya gaya!";
}

// ── FETCH USERS ──────────────────────────────────────────────────
$search = trim($_GET['search'] ?? '');
$page   = max(1, intval($_GET['page'] ?? 1));
$limit  = 20;
$offset = ($page - 1) * $limit;

$where = '';
if($search != ''){
    $s     = mysqli_real_escape_string($conn, $search);
    $where = "WHERE t.chat_id LIKE '%$s%' OR t.username LIKE '%$s%' OR t.phone LIKE '%$s%' OR u.name LIKE '%$s%'";
}

$total_row  = mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as c FROM telegram_users t LEFT JOIN users u ON t.phone=u.phone $where"));
$total      = (int)$total_row['c'];
$total_pages = ceil($total / $limit);

$users = [];
$q = mysqli_query($conn,"SELECT t.*, u.name, u.balance FROM telegram_users t LEFT JOIN users u ON t.phone=u.phone $where ORDER BY t.id DESC LIMIT $limit OFFSET $offset");
while($row = mysqli_fetch_assoc($q)) $users[] = $row;

// Total connected (all)
$total_all = mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as c FROM telegram_users"))['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Telegram Users — SAB FIND</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@600;700;800&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#07070e; --surface:#0f0f18; --card:#13131e;
  --border:#ffffff0c; --accent:#6c63ff; --accent2:#ff6584;
  --green:#00e5a0; --yellow:#ffd96a; --text:#eeeef8; --muted:#5f5f7a;
  --red:#ff4d6d; --radius:14px;
}
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;}
body::before{content:'';position:fixed;inset:0;background:radial-gradient(ellipse 70% 40% at 10% 0%,#6c63ff14 0%,transparent 55%),radial-gradient(ellipse 50% 40% at 90% 100%,#ff658410 0%,transparent 55%);pointer-events:none;z-index:0;}

.wrap{position:relative;z-index:1;max-width:1100px;margin:0 auto;padding:32px 20px 60px;}

/* Header */
.header{display:flex;align-items:center;justify-content:space-between;margin-bottom:28px;flex-wrap:wrap;gap:16px;}
.header-left{display:flex;align-items:center;gap:14px;}
.hicon{width:50px;height:50px;background:linear-gradient(135deg,#6c63ff,#ff6584);border-radius:14px;display:grid;place-items:center;font-size:22px;flex-shrink:0;}
.header h1{font-family:'Syne',sans-serif;font-size:24px;font-weight:800;letter-spacing:-0.4px;}
.header p{color:var(--muted);font-size:13px;margin-top:2px;}

/* Stats */
.stats{display:flex;gap:14px;margin-bottom:24px;flex-wrap:wrap;}
.stat-card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:16px 22px;flex:1;min-width:140px;}
.stat-card .val{font-family:'Syne',sans-serif;font-size:28px;font-weight:800;}
.stat-card .lbl{font-size:12px;color:var(--muted);margin-top:3px;text-transform:uppercase;letter-spacing:.6px;}
.stat-card.accent .val{color:var(--accent);}
.stat-card.green .val{color:var(--green);}
.stat-card.yellow .val{color:var(--yellow);}

/* Alert */
.alert{padding:12px 18px;border-radius:10px;margin-bottom:20px;font-size:14px;font-weight:500;animation:fadeIn .3s ease;}
.alert.success{background:#00e5a015;border:1px solid #00e5a035;color:var(--green);}
@keyframes fadeIn{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}}

/* Toolbar */
.toolbar{display:flex;gap:10px;margin-bottom:16px;flex-wrap:wrap;align-items:center;}
.search-wrap{flex:1;min-width:220px;position:relative;}
.search-wrap input{width:100%;background:var(--card);border:1px solid var(--border);border-radius:10px;padding:11px 16px 11px 40px;color:var(--text);font-size:14px;font-family:'DM Sans',sans-serif;outline:none;transition:.2s;}
.search-wrap input:focus{border-color:var(--accent);}
.search-wrap .sico{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:15px;}
.page-info{color:var(--muted);font-size:13px;margin-left:auto;}

/* Table card */
.table-card{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}

table{width:100%;border-collapse:collapse;}
thead tr{background:#0d0d17;}
th{padding:13px 16px;font-family:'Syne',sans-serif;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);text-align:left;border-bottom:1px solid var(--border);}
td{padding:13px 16px;font-size:14px;border-bottom:1px solid var(--border);vertical-align:middle;}
tr:last-child td{border-bottom:none;}
tr:hover td{background:#ffffff03;}

.user-cell{display:flex;align-items:center;gap:10px;}
.avatar{width:34px;height:34px;border-radius:9px;background:linear-gradient(135deg,var(--accent),var(--accent2));display:grid;place-items:center;font-family:'Syne',sans-serif;font-size:13px;font-weight:700;flex-shrink:0;}
.uname{font-weight:500;font-size:14px;}
.uphone{font-size:12px;color:var(--muted);margin-top:1px;}

.chat-id{font-family:monospace;font-size:12px;color:var(--muted);background:#ffffff08;padding:3px 8px;border-radius:6px;}
.balance{font-weight:600;color:var(--green);font-size:13px;}
.date{font-size:12px;color:var(--muted);}

/* Status badge */
.status{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;padding:3px 10px;border-radius:99px;}
.status.connected{background:#00e5a015;color:var(--green);}
.status.connected::before{content:'';width:6px;height:6px;border-radius:50%;background:var(--green);}

/* Disconnect btn */
.disc-btn{background:transparent;border:1px solid #ff4d6d30;color:var(--red);font-size:12px;font-family:'DM Sans',sans-serif;font-weight:600;padding:6px 12px;border-radius:8px;cursor:pointer;transition:.15s;display:flex;align-items:center;gap:5px;}
.disc-btn:hover{background:#ff4d6d15;border-color:var(--red);}

/* Modal */
.modal-overlay{display:none;position:fixed;inset:0;background:#00000080;z-index:100;backdrop-filter:blur(4px);place-items:center;}
.modal-overlay.open{display:grid;}
.modal{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);padding:28px;max-width:380px;width:90%;animation:fadeIn .25s ease;}
.modal h3{font-family:'Syne',sans-serif;font-size:18px;font-weight:700;margin-bottom:8px;}
.modal p{color:var(--muted);font-size:14px;line-height:1.6;margin-bottom:20px;}
.modal-info{background:#ff4d6d10;border:1px solid #ff4d6d25;border-radius:10px;padding:12px 14px;margin-bottom:20px;font-size:13px;color:#ff8fa3;}
.modal-btns{display:flex;gap:10px;}
.mbtn{flex:1;padding:12px;border-radius:10px;font-size:14px;font-weight:600;font-family:'Syne',sans-serif;cursor:pointer;border:none;transition:.15s;}
.mbtn.cancel{background:#ffffff0a;color:var(--text);}
.mbtn.cancel:hover{background:#ffffff15;}
.mbtn.confirm{background:var(--red);color:#fff;}
.mbtn.confirm:hover{opacity:.9;}

/* Pagination */
.pagination{display:flex;gap:6px;justify-content:center;margin-top:20px;flex-wrap:wrap;}
.plink{padding:8px 14px;background:var(--card);border:1px solid var(--border);border-radius:8px;color:var(--muted);font-size:13px;text-decoration:none;transition:.15s;}
.plink:hover,.plink.active{background:var(--accent);border-color:var(--accent);color:#fff;}
.plink.disabled{opacity:.3;pointer-events:none;}

/* Empty */
.empty{text-align:center;padding:50px 20px;color:var(--muted);}
.empty .eicon{font-size:40px;margin-bottom:12px;}
</style>
</head>
<body>
<div class="wrap">

  <!-- Header -->
  <div class="header">
    <div class="header-left">
      <div class="hicon">📱</div>
      <div>
        <h1>Telegram Users</h1>
        <p>SAB FIND — Connected Accounts</p>
      </div>
    </div>
    <a href="https://insta.sab-find.info/telegram_panel1.php" style="background:var(--accent);color:#fff;padding:10px 20px;border-radius:10px;text-decoration:none;font-size:13px;font-weight:600;font-family:'Syne',sans-serif;">📢 Broadcast</a>
  </div>

  <?php if(isset($disconnect_msg)): ?>
  <div class="alert success"><?= htmlspecialchars($disconnect_msg) ?></div>
  <?php endif; ?>

  <!-- Stats -->
  <div class="stats">
    <div class="stat-card accent">
      <div class="val"><?= $total_all ?></div>
      <div class="lbl">Total Connected</div>
    </div>
    <div class="stat-card green">
      <div class="val"><?= $total ?></div>
      <div class="lbl"><?= $search ? 'Search Results' : 'Showing Now' ?></div>
    </div>
    <div class="stat-card yellow">
      <div class="val"><?= $total_pages ?></div>
      <div class="lbl">Total Pages</div>
    </div>
  </div>

  <!-- Toolbar -->
  <div class="toolbar">
    <form method="GET" style="display:contents">
      <div class="search-wrap">
        <span class="sico">🔍</span>
        <input type="text" name="search" placeholder="Search name / phone / chat ID…" value="<?= htmlspecialchars($search) ?>">
      </div>
      <button type="submit" style="background:var(--accent);color:#fff;border:none;padding:11px 20px;border-radius:10px;font-size:13px;font-weight:600;font-family:'DM Sans',sans-serif;cursor:pointer;">Search</button>
      <?php if($search): ?>
      <a href="?" style="background:#ffffff0a;color:var(--muted);padding:11px 16px;border-radius:10px;font-size:13px;text-decoration:none;">✕ Clear</a>
      <?php endif; ?>
    </form>
    <span class="page-info">Page <?= $page ?> / <?= max(1,$total_pages) ?> &nbsp;|&nbsp; <?= $total ?> users</span>
  </div>

  <!-- Table -->
  <div class="table-card">
    <?php if(empty($users)): ?>
    <div class="empty">
      <div class="eicon">📭</div>
      <p>Koi user nahi mila</p>
    </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>User</th>
          <th>Chat ID</th>
          <th>Balance</th>
          <th>Status</th>
          <th>Joined</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $sr = $offset + 1;
        foreach($users as $u):
          $name    = $u['name'] ?: $u['username'] ?: 'Unknown';
          $initial = strtoupper(substr($name,0,1));
          $bal     = number_format((float)($u['balance']??0), 2);
          $date    = $u['created_at'] ? date('d M Y', strtotime($u['created_at'])) : '—';
        ?>
        <tr>
          <td style="color:var(--muted);font-size:13px;"><?= $sr++ ?></td>
          <td>
            <div class="user-cell">
              <div class="avatar"><?= $initial ?></div>
              <div>
                <div class="uname"><?= htmlspecialchars($name) ?></div>
                <div class="uphone"><?= htmlspecialchars($u['phone'] ?? '—') ?></div>
              </div>
            </div>
          </td>
          <td><span class="chat-id"><?= $u['chat_id'] ?></span></td>
          <td><span class="balance">₹<?= $bal ?></span></td>
          <td><span class="status connected">Connected</span></td>
          <td><span class="date"><?= $date ?></span></td>
          <td>
            <button class="disc-btn"
              onclick="openModal('<?= htmlspecialchars($u['chat_id']) ?>','<?= htmlspecialchars($name) ?>','<?= htmlspecialchars($u['phone']??'') ?>')">
              🔌 Disconnect
            </button>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <!-- Pagination -->
  <?php if($total_pages > 1): ?>
  <div class="pagination">
    <?php
    $base = '?page=';
    if($search) $base .= '1&search='.urlencode($search).'&page=';
    ?>
    <a href="<?= $base.max(1,$page-1) ?>" class="plink <?= $page<=1?'disabled':'' ?>">← Prev</a>
    <?php
    $start = max(1, $page-2); $end = min($total_pages, $page+2);
    for($i=$start;$i<=$end;$i++):
    ?>
    <a href="<?= $base.$i ?>" class="plink <?= $i==$page?'active':'' ?>"><?= $i ?></a>
    <?php endfor; ?>
    <a href="<?= $base.min($total_pages,$page+1) ?>" class="plink <?= $page>=$total_pages?'disabled':'' ?>">Next →</a>
  </div>
  <?php endif; ?>

</div>

<!-- Disconnect Modal -->
<div class="modal-overlay" id="modal">
  <div class="modal">
    <h3>🔌 Telegram Disconnect?</h3>
    <p>Kya aap is user ka Telegram disconnect karna chahte ho?</p>
    <div class="modal-info" id="modal-info"></div>
    <p style="font-size:13px;color:var(--muted);margin-bottom:20px;">
      ⚠️ User suspend <b>nahi</b> hoga.<br>
      Woh dobara apni website link se Telegram connect kar sakta hai.
    </p>
    <form method="POST" id="disc-form">
      <input type="hidden" name="disconnect" value="1">
      <input type="hidden" name="chat_id" id="modal-chat-id">
      <?php if($search): ?><input type="hidden" name="search_back" value="<?= htmlspecialchars($search) ?>"><?php endif; ?>
      <div class="modal-btns">
        <button type="button" class="mbtn cancel" onclick="closeModal()">Cancel</button>
        <button type="submit" class="mbtn confirm">Haan, Disconnect karo</button>
      </div>
    </form>
  </div>
</div>

<script>
function openModal(chatId, name, phone){
  document.getElementById('modal-chat-id').value = chatId;
  document.getElementById('modal-info').innerHTML =
    '<b>👤 ' + name + '</b><br>📱 ' + (phone||'—') + '<br>🆔 ' + chatId;
  document.getElementById('modal').classList.add('open');
}
function closeModal(){
  document.getElementById('modal').classList.remove('open');
}
document.getElementById('modal').addEventListener('click', function(e){
  if(e.target === this) closeModal();
});
</script>
</body>
</html>