<?php
session_start();
require '../user/db.php';
include "back.php";
// require 'header.php';

/* ================= ADMIN PROTECTION ================= */
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

/* ================= FLASH MESSAGE ================= */
function flash($name) {
    if (isset($_SESSION[$name])) {
        echo '<div class="alert">'.$_SESSION[$name].'</div>';
        unset($_SESSION[$name]);
    }
}

/* ================= UPDATE ROLE ================= */
if (isset($_POST['update_role'])) {
    $id = intval($_POST['id']);
    $role = $_POST['role'];

    $stmt = $conn->prepare("UPDATE users SET role=? WHERE id=?");
    $stmt->bind_param("si", $role, $id);
    $_SESSION[$stmt->execute() ? 'success' : 'error'] =
        $stmt->execute() ? "User role updated" : "Failed to update role";

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= VERIFY USER ================= */
if (isset($_POST['verify_user'])) {
    $id = intval($_POST['id']);

    $stmt = $conn->prepare("UPDATE users SET is_verified=1 WHERE id=?");
    $stmt->bind_param("i", $id);
    $_SESSION[$stmt->execute() ? 'success' : 'error'] =
        $stmt->execute() ? "User verified" : "Verification failed";

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= DELETE USER ================= */
if (isset($_POST['delete_user'])) {
    $id = intval($_POST['id']);

    $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
    $stmt->bind_param("i", $id);
    $_SESSION[$stmt->execute() ? 'success' : 'error'] =
        $stmt->execute() ? "User deleted" : "Delete failed";

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= PAGINATION ================= */
$limit = 8;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

$total = $conn->query("SELECT COUNT(*) AS total FROM users")->fetch_assoc()['total'];
$pages = ceil($total / $limit);

$users = $conn->query("SELECT * FROM users ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin – Manage Users</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
/* ================= PAGE SCOPE ================= */
.admin-users-page {
  padding: 20px;
  background: var(--bg);
  color: var(--text);
  min-height: calc(100vh - 140px);
  transition: .3s;
}

/* ================= THEME ================= */
:root {
  --bg: #f4f6f8;
  --card: #ffffff;
  --text: #0f172a;
  --primary: #0f172a;
  --accent: #309992;
}

.dark-theme {
  --bg: #020617;
  --card: #0f172a;
  --text: #e5e7eb;
  --primary: #020617;
}

/* ================= HEADER BAR ================= */
.page-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.theme-toggle {
  background: var(--accent);
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 13px;
}

/* ================= ALERT ================= */
.alert {
  background: var(--accent);
  color: #fff;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
}

/* ================= TABLE ================= */
.table-wrapper { overflow-x: auto; }

table {
  width: 100%;
  border-collapse: collapse;
  background: var(--card);
  border-radius: 8px;
}

th, td {
  padding: 10px;
  border: 1px solid #e5e7eb;
  white-space: nowrap;
}

th {
  background: var(--primary);
  color: #fff;
}

/* ================= BUTTONS ================= */
.btn {
  padding: 6px 10px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  font-size: 13px;
}

.btn-role { background: #2563eb; color: #fff; }
.btn-verify { background: #16a34a; color: #fff; }
.btn-delete { background: #dc2626; color: #fff; }

/* ================= PAGINATION ================= */
.pagination {
  margin-top: 15px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination a {
  padding: 6px 12px;
  background: var(--card);
  border-radius: 5px;
  text-decoration: none;
  color: var(--text);
  border: 1px solid #ccc;
}

.pagination a.active {
  background: var(--accent);
  color: #fff;
  border-color: var(--accent);
}

/* ================= MOBILE ================= */
@media (max-width: 768px) {
  .btn, select {
    width: 100%;
    margin-top: 5px;
  }
}
</style>
</head>

<body>

<div class="admin-users-page" id="adminPage">

  <div class="page-top">
    <h2>Manage Users</h2>
    <button class="theme-toggle" onclick="toggleTheme()">🌙 </button>
  </div>

  <?php flash('success'); ?>
  <?php flash('error'); ?>

  <div class="table-wrapper">
    <table>
      <tr>
        <th>ID</th>
        <th>User ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Role</th>
        <th>Verified</th>
        <th>Created</th>
        <th>Actions</th>
      </tr>

      <?php while ($row = $users->fetch_assoc()): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= $row['user_id'] ?? '—' ?></td>
        <td><?= htmlspecialchars($row['fullname']) ?></td>
        <td><?= htmlspecialchars($row['email']) ?></td>

        <td>
          <form method="post">
            <input type="hidden" name="id" value="<?= $row['id'] ?>">
            <select name="role">
              <option value="user" <?= $row['role']=='user'?'selected':'' ?>>User</option>
              <option value="admin" <?= $row['role']=='admin'?'selected':'' ?>>Admin</option>
            </select>
            <button class="btn btn-role" name="update_role">Save</button>
          </form>
        </td>

        <td>
          <?= $row['is_verified'] ? 'Yes' : 'No' ?>
          <?php if (!$row['is_verified']): ?>
          <form method="post">
            <input type="hidden" name="id" value="<?= $row['id'] ?>">
            <button class="btn btn-verify" name="verify_user">Verify</button>
          </form>
          <?php endif; ?>
        </td>

        <td><?= $row['created_at'] ?></td>

        <td>
          <form method="post" onsubmit="return confirm('Delete user?')">
            <input type="hidden" name="id" value="<?= $row['id'] ?>">
            <button class="btn btn-delete" name="delete_user">Delete</button>
          </form>
        </td>
      </tr>
      <?php endwhile; ?>
    </table>
  </div>

  <!-- PAGINATION -->
  <div class="pagination">
    <?php for ($i = 1; $i <= $pages; $i++): ?>
      <a href="?page=<?= $i ?>" class="<?= $i==$page?'active':'' ?>">
        <?= $i ?>
      </a>
    <?php endfor; ?>
  </div>

</div>

<script>
function toggleTheme() {
  document.getElementById('adminPage').classList.toggle('dark-theme');
  localStorage.setItem('adminTheme',
    document.getElementById('adminPage').classList.contains('dark-theme') ? 'dark' : 'light'
  );
}

if (localStorage.getItem('adminTheme') === 'dark') {
  document.getElementById('adminPage').classList.add('dark-theme');
}
</script>

</body>
</html>

<?php require 'footer.php'; ?>
