<?php
session_start();

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header("Location: admin-login.php");
    exit();
}

require_once("auth/db.php");

// Fetch active users
$users = [];
$result = $conn->query("
    SELECT id, first_name, middle_name, surname, email, country,
           dob, referred_by, created_at,
           mining_balance, task_balance, referral_balance, kyc_status, status
    FROM users
    ORDER BY id DESC
");

while ($row = $result->fetch_assoc()) {
    $fullName = trim($row['first_name'] . ' ' . $row['middle_name'] . ' ' . $row['surname']);
    $users[] = [
        'id' => $row['id'],
        'name' => $fullName,
        'email' => $row['email'],
        'country' => $row['country'],
        'dob' => $row['dob'],
        'referred_by' => $row['referred_by'],
        'created_at' => $row['created_at'],
        'mining_balance' => $row['mining_balance'],
        'task_balance' => $row['task_balance'],
        'referral_balance' => $row['referral_balance'],
        'status' => $row['kyc_status'] ?? "Not Submitted",
        'hasKYC' => !in_array(strtolower($row['kyc_status']), ['not submitted', '', null]),
        'account_status' => $row['status'] ?? 'active'
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Dashboard - Gobolcoin</title>
  <link rel="icon" type="image/png" href="/favicon.png">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', sans-serif;
      background: linear-gradient(to top right, #ffffff 70%, #8B0000 130%);
      padding: 2em;
    }
    h1 {
      text-align: center;
      color: #8B0000;
      margin-bottom: 1em;
    }
    input[type="search"] {
      width: 100%;
      padding: 0.8em;
      font-size: 1em;
      border-radius: 10px;
      border: 1px solid #ccc;
      margin-bottom: 1.5em;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      background-color: #fff;
      border-radius: 10px;
      overflow: hidden;
    }
    th, td {
      padding: 1em;
      text-align: left;
      border-bottom: 1px solid #eee;
      vertical-align: middle;
    }
    th {
      background-color: #8B0000;
      color: white;
    }
    tr:hover {
      background-color: #f9f9f9;
    }
    .status-approved { color: green; font-weight: bold; }
    .status-rejected { color: red; font-weight: bold; }
    .status-pending { color: orange; font-weight: bold; }
    .status-none { color: gray; font-weight: bold; }
    .frozen { background-color: #ffe0e0; }
    a.button {
      background: #8B0000;
      color: white;
      padding: 5px 10px;
      border-radius: 5px;
      text-decoration: none;
      font-size: 0.9em;
    }
    a.button:hover { background: #a30000; }
    .top-links {
      text-align: right;
      margin-bottom: 10px;
    }
    .top-links a {
      color: #8B0000;
      text-decoration: none;
      margin-left: 15px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>Admin Dashboard</h1>

  <div class="top-links">
    <a href="archived-users.php">View Archived Users</a>
    <a href="admin-logout.php">Logout</a>
  </div>

  <input type="search" placeholder="Search users by name or email..." oninput="filterTable(this.value)">

  <table id="userTable">
    <thead>
  <tr>
    <th>S/N</th> <!-- Added -->
    <th>ID</th>
    <th>Full Name</th>
    <th>Email</th>
    <th>Country</th>
    <th>Date of Birth</th>
    <th>Referred By</th>
    <th>Created At</th>
    <th>Mining Balance</th>
    <th>Task Balance</th>
    <th>Referral Balance</th>
    <th>KYC Status</th>
    <th>Account</th>
    <th>Actions</th>
  </tr>
</thead>
<tbody>
  <?php 
    $sn = 1; // start serial number
    foreach ($users as $u): 
  ?>
    <tr class="<?= $u['account_status'] === 'frozen' ? 'frozen' : '' ?>">
      <td><?= $sn++ ?></td> <!-- Serial Number -->
      <td><?= htmlspecialchars($u['id']) ?></td>
      <td><?= htmlspecialchars($u['name']) ?></td>
      <td><?= htmlspecialchars($u['email']) ?></td>
      <td><?= htmlspecialchars($u['country']) ?></td>
      <td><?= htmlspecialchars($u['dob']) ?></td>
      <td><?= htmlspecialchars($u['referred_by']) ?></td>
      <td><?= htmlspecialchars($u['created_at']) ?></td>
      <td><?= number_format($u['mining_balance'], 4) ?> GBL</td>
      <td><?= number_format($u['task_balance'], 4) ?> GBL</td>
      <td><?= number_format($u['referral_balance'], 4) ?> GBL</td>
      <td class="<?php
        echo ($u['status'] === 'Approved') ? 'status-approved' :
             (($u['status'] === 'Rejected') ? 'status-rejected' :
             (($u['status'] === 'Pending') ? 'status-pending' : 'status-none'));
      ?>">
        <?= htmlspecialchars($u['status']) ?>
      </td>
      <td><?= htmlspecialchars($u['account_status']) ?></td>
      <td>
  <?php if ($u['hasKYC']): ?>
    <a class="button" href="view-kyc.php?email=<?= urlencode($u['email']) ?>">Review</a>
  <?php endif; ?>

  <a class="button" href="admin-user-actions.php?action=delete&id=<?= $u['id'] ?>"
     onclick="return confirm('Are you sure you want to delete this user? It will be archived.');">Delete</a>

  <?php if ($u['account_status'] !== 'frozen'): ?>
    <a class="button" href="admin-user-actions.php?action=freeze&id=<?= $u['id'] ?>"
       onclick="return confirm('Freeze this account? User will not be able to login.');">Freeze</a>
  <?php else: ?>
    <a class="button" href="admin-user-actions.php?action=unfreeze&id=<?= $u['id'] ?>"
       onclick="return confirm('Unfreeze this account?');">Unfreeze</a>
  <?php endif; ?>
</td>
    </tr>
  <?php endforeach; ?>
</tbody>
  </table>

  <script>
    function filterTable(query) {
      const rows = document.querySelectorAll("#userTable tbody tr");
      query = query.toLowerCase();
      rows.forEach(row => {
        const text = row.innerText.toLowerCase();
        row.style.display = text.includes(query) ? '' : 'none';
      });
    }
  </script>
</body>
</html>