<?php
require_once 'auth_check.php';
require_once 'config.php';

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$page = isset($_GET['page']) ? max(1,(int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page-1)*$perPage;

$where = '';
if ($search !== '') {
    $s = mysqli_real_escape_string($koneksi, $search);
    $where = "WHERE username LIKE '%$s%' OR email LIKE '%$s%'";
}

$countQ = mysqli_query($koneksi, "SELECT COUNT(*) as c FROM user_id $where");
$totalRows = 0;
if ($countQ) { $r = mysqli_fetch_assoc($countQ); $totalRows = $r['c']; }
$totalPages = max(1, ceil($totalRows / $perPage));

$users = [];
$q = mysqli_query($koneksi, "SELECT ID,username,email,cr,hwid,expired,last,status,info FROM user_id $where ORDER BY ID DESC LIMIT $offset,$perPage");
if ($q) while ($row = mysqli_fetch_assoc($q)) $users[] = $row;
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Users - Admin Panel</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
  <?php include 'topbar.php'; ?>
  <div class="page-body">
    <div class="page-header">
      <h2>User Management</h2>
      <button class="btn btn-primary" onclick="openModal('addUserModal')">+ Add User</button>
    </div>

    <div class="card">
      <div class="card-header">
        <form method="GET" class="search-form">
          <input type="text" name="search" placeholder="Search username or email..." value="<?= htmlspecialchars($search) ?>">
          <button type="submit" class="btn btn-primary">Search</button>
          <?php if($search): ?><a href="users.php" class="btn btn-outline">Clear</a><?php endif; ?>
        </form>
        <span class="text-muted"><?= $totalRows ?> users found</span>
      </div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>ID</th><th>Username</th><th>Email</th><th>Credits</th>
              <th>HWID</th><th>Expires</th><th>Last Login</th><th>Status</th><th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($users as $u): ?>
            <tr>
              <td><?= $u['ID'] ?></td>
              <td><strong><?= htmlspecialchars($u['username']) ?></strong></td>
              <td class="text-muted"><?= htmlspecialchars($u['email']) ?></td>
              <td><span class="badge badge-info"><?= htmlspecialchars($u['cr']) ?></span></td>
              <td class="text-mono text-muted" style="font-size:11px"><?= htmlspecialchars(substr($u['hwid'],0,20)) ?>...</td>
              <td><?= htmlspecialchars($u['expired']) ?></td>
              <td class="text-muted"><?= htmlspecialchars($u['last']) ?></td>
              <td><span class="badge badge-<?= $u['status']==='Active'?'success':($u['status']==='Bloked'?'danger':'warning') ?>"><?= htmlspecialchars($u['status']) ?></span></td>
              <td>
                <div class="action-btns">
                  <button class="btn btn-xs btn-outline" onclick='editUser(<?= json_encode($u) ?>)' title="Edit">✏️</button>
                  <button class="btn btn-xs btn-success" onclick='addCreditModal(<?= $u["ID"] ?>, "<?= htmlspecialchars($u["username"]) ?>")' title="Add Credit">💰</button>
                  <button class="btn btn-xs btn-danger" onclick='banUser(<?= $u["ID"] ?>, "<?= htmlspecialchars($u["username"]) ?>")' title="Ban">🚫</button>
                  <button class="btn btn-xs btn-outline" onclick='resetHwid(<?= $u["ID"] ?>, "<?= htmlspecialchars($u["username"]) ?>")' title="Reset HWID">🔄</button>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if(empty($users)): ?>
            <tr><td colspan="9" class="text-center text-muted" style="padding:30px">No users found</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <?php if($totalPages > 1): ?>
      <div class="pagination">
        <?php for($i=1;$i<=$totalPages;$i++): ?>
        <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="page-btn <?= $i==$page?'active':'' ?>"><?= $i ?></a>
        <?php endfor; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Edit User Modal -->
<div class="modal" id="editUserModal">
  <div class="modal-backdrop" onclick="closeModal('editUserModal')"></div>
  <div class="modal-box">
    <div class="modal-header"><h3>Edit User</h3><button onclick="closeModal('editUserModal')">✕</button></div>
    <form id="editUserForm" onsubmit="submitEditUser(event)">
      <input type="hidden" name="id" id="edit_id">
      <div class="form-grid-2">
        <div class="form-group"><label>Username</label><input type="text" name="username" id="edit_username"></div>
        <div class="form-group"><label>Email</label><input type="email" name="email" id="edit_email"></div>
        <div class="form-group"><label>Password (leave blank to keep)</label><input type="text" name="password" id="edit_password" placeholder="New password..."></div>
        <div class="form-group"><label>Credits</label><input type="number" name="cr" id="edit_cr"></div>
        <div class="form-group"><label>Expiry Date</label><input type="date" name="expired" id="edit_expired"></div>
        <div class="form-group"><label>Status</label>
          <select name="status" id="edit_status">
            <option value="Active">Active</option>
            <option value="Bloked">Blocked</option>
          </select>
        </div>
      </div>
      <div class="form-group"><label>Info / Notes</label><textarea name="info" id="edit_info" rows="2"></textarea></div>
      <div class="modal-footer"><button type="button" class="btn btn-outline" onclick="closeModal('editUserModal')">Cancel</button><button type="submit" class="btn btn-primary">Save Changes</button></div>
    </form>
  </div>
</div>

<!-- Add Credit Modal -->
<div class="modal" id="addCreditModal">
  <div class="modal-backdrop" onclick="closeModal('addCreditModal')"></div>
  <div class="modal-box" style="max-width:400px">
    <div class="modal-header"><h3>Add Credit</h3><button onclick="closeModal('addCreditModal')">✕</button></div>
    <form onsubmit="submitAddCredit(event)">
      <input type="hidden" id="credit_user_id">
      <p id="credit_user_name" class="text-muted" style="margin-bottom:16px"></p>
      <div class="form-group"><label>Amount to Add</label><input type="number" id="credit_amount" placeholder="Enter credit amount" min="1" required></div>
      <div class="modal-footer"><button type="button" class="btn btn-outline" onclick="closeModal('addCreditModal')">Cancel</button><button type="submit" class="btn btn-success">Add Credit</button></div>
    </form>
  </div>
</div>

<!-- Add User Modal -->
<div class="modal" id="addUserModal">
  <div class="modal-backdrop" onclick="closeModal('addUserModal')"></div>
  <div class="modal-box">
    <div class="modal-header"><h3>Add New User</h3><button onclick="closeModal('addUserModal')">✕</button></div>
    <form onsubmit="submitAddUser(event)">
      <div class="form-grid-2">
        <div class="form-group"><label>Username *</label><input type="text" id="new_username" required></div>
        <div class="form-group"><label>Email *</label><input type="email" id="new_email" required></div>
        <div class="form-group"><label>Password *</label><input type="text" id="new_password" required></div>
        <div class="form-group"><label>Credits</label><input type="number" id="new_cr" value="0" min="0"></div>
        <div class="form-group"><label>Expiry Date *</label><input type="date" id="new_expired" required></div>
        <div class="form-group"><label>HWID</label><input type="text" id="new_hwid" placeholder="Optional"></div>
      </div>
      <div class="modal-footer"><button type="button" class="btn btn-outline" onclick="closeModal('addUserModal')">Cancel</button><button type="submit" class="btn btn-primary">Create User</button></div>
    </form>
  </div>
</div>

<div id="toast" class="toast"></div>
<script src="assets/script.js"></script>
<script>
function editUser(u) {
  document.getElementById('edit_id').value = u.ID;
  document.getElementById('edit_username').value = u.username;
  document.getElementById('edit_email').value = u.email;
  document.getElementById('edit_password').value = '';
  document.getElementById('edit_cr').value = u.cr;
  document.getElementById('edit_expired').value = u.expired;
  document.getElementById('edit_status').value = u.status;
  document.getElementById('edit_info').value = u.info||'';
  openModal('editUserModal');
}
function addCreditModal(id, name) {
  document.getElementById('credit_user_id').value = id;
  document.getElementById('credit_user_name').textContent = 'User: ' + name;
  document.getElementById('credit_amount').value = '';
  openModal('addCreditModal');
}
async function submitEditUser(e) {
  e.preventDefault();
  const form = e.target;
  const data = new FormData(form);
  const r = await fetch('api/update_user.php', {method:'POST', body: new URLSearchParams(data)});
  const t = await r.text();
  showToast(t.includes('success') ? 'User updated!' : t, t.includes('success'));
  if(t.includes('success')) { closeModal('editUserModal'); setTimeout(()=>location.reload(),800); }
}
async function submitAddCredit(e) {
  e.preventDefault();
  const id = document.getElementById('credit_user_id').value;
  const amount = document.getElementById('credit_amount').value;
  const r = await fetch('api/add_credit.php', {method:'POST', body: new URLSearchParams({id, amount})});
  const t = await r.text();
  showToast(t.includes('success') ? 'Credit added!' : t, t.includes('success'));
  if(t.includes('success')) { closeModal('addCreditModal'); setTimeout(()=>location.reload(),800); }
}
async function submitAddUser(e) {
  e.preventDefault();
  const body = new URLSearchParams({
    username: document.getElementById('new_username').value,
    email: document.getElementById('new_email').value,
    password: document.getElementById('new_password').value,
    cr: document.getElementById('new_cr').value,
    expired: document.getElementById('new_expired').value,
    hwid: document.getElementById('new_hwid').value,
  });
  const r = await fetch('api/add_user.php', {method:'POST', body});
  const t = await r.text();
  showToast(t.includes('success') ? 'User created!' : t, t.includes('success'));
  if(t.includes('success')) { closeModal('addUserModal'); setTimeout(()=>location.reload(),800); }
}
async function banUser(id, name) {
  if (!confirm('Ban user: ' + name + '?')) return;
  const r = await fetch('api/ban_user.php', {method:'POST', body: new URLSearchParams({id})});
  const t = await r.text();
  showToast(t.includes('success') ? 'User banned.' : t, t.includes('success'));
  if(t.includes('success')) setTimeout(()=>location.reload(),800);
}
async function resetHwid(id, name) {
  if (!confirm('Reset HWID for: ' + name + '?')) return;
  const r = await fetch('api/reset_hwid.php', {method:'POST', body: new URLSearchParams({id})});
  const t = await r.text();
  showToast(t.includes('success') ? 'HWID reset.' : t, t.includes('success'));
  if(t.includes('success')) setTimeout(()=>location.reload(),800);
}
</script>
</body>
</html>
