<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once 'db.php';


// ✅ Handle impersonation
if (isset($_GET['impersonate'])) {
    $targetUser = $_GET['impersonate'];
    $_SESSION['impersonated_user'] = $targetUser;
    $_SESSION['logged_in_user'] = $targetUser; // ✅ Also set this to keep all user pages working
    header("Location: user-dashboard.php");
    exit;
}


// ✅ Handle exit impersonation
if (isset($_GET['stop_impersonate'])) {
    unset($_SESSION['impersonated_user']);
    $_SESSION['logged_in_user'] = 'edkeyte'; // ✅ Return to your own user account
    header("Location: admin-users.php");     // ✅ Stay on admin page
    exit;
}



// ✅ Search and Pagination
$perPage = 20;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $perPage;

$search = $_GET['search'] ?? '';
$params = [];
$sql = "SELECT * FROM users WHERE 1";

if (!empty($search)) {
    $sql .= " AND (user_id LIKE :search OR email LIKE :search OR first_name LIKE :search OR last_name LIKE :search)";
    $params[':search'] = "%$search%";
}

$sql .= " ORDER BY id DESC LIMIT $offset, $perPage";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

// ✅ Count total for pagination
$countSql = "SELECT COUNT(*) FROM users WHERE 1";
if (!empty($search)) {
    $countSql .= " AND (user_id LIKE :search OR email LIKE :search OR first_name LIKE :search OR last_name LIKE :search)";
}
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalUsers = $countStmt->fetchColumn();
$totalPages = ceil($totalUsers / $perPage);
?>


<!DOCTYPE html>
<html>
<head>
    <title>Admin User Manager</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <style>
        body { padding: 40px; font-family: 'Segoe UI', sans-serif; }
        .container { max-width: 900px; margin: auto; }
        .impersonate-btn { font-size: 14px; }
        .restore-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body style="display: flex; min-height: 100vh; margin: 0;">
<div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
  <?php include 'google-translate-widget-front-end.php'; ?>
  <?php include 'admin-links.php'; ?>
</div>

  <div style="flex-grow: 1; padding: 20px;">
<div class="container">
    <h2>👤 Admin User Manager</h2>



    <form method="GET" class="mb-3">
        <input type="text" name="search" placeholder="Search by name, email or user ID" class="form-control" value="<?= htmlspecialchars($search) ?>">
    </form>
<?php if (isset($_SESSION['impersonated_user'])): ?>
    <div class="alert alert-warning">
        You are impersonating <strong><?= htmlspecialchars($_SESSION['impersonated_user']) ?></strong>.
        <a href="admin-users.php?stop_impersonate=1" class="btn btn-sm btn-outline-dark ms-2">🔙 Stop Impersonating</a>
        <div class="mt-2">
            <a href="user-dashboard.php" target="_blank" class="btn btn-sm btn-primary">👉 Open user dashboard in new tab</a>
        </div>
    </div>
<?php endif; ?>

    <table class="table table-bordered table-hover">
        <thead class="table-light">
            <tr>
                <th>ID</th>
                <th>User ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Impersonate</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $user['id'] ?></td>
                <td><?= htmlspecialchars($user['user_id']) ?></td>
                <td><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></td>
                <td><?= htmlspecialchars($user['email']) ?></td>
                <td>
                    <a href="admin-users.php?impersonate=<?= urlencode($user['user_id']) ?>" target="_blank" class="btn btn-sm btn-primary impersonate-btn">Login as this user</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

<!-- Compact Pagination -->
<nav>
  <ul class="pagination justify-content-center">
    <?php
    $range = 2; // Show current page ±2 pages
    $start = max(1, $page - $range);
    $end = min($totalPages, $page + $range);

    // Prev button
    if ($page > 1): ?>
      <li class="page-item">
        <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">« Prev</a>
      </li>
    <?php endif; ?>

    <?php for ($i = $start; $i <= $end; $i++): ?>
      <li class="page-item <?= $i === $page ? 'active' : '' ?>">
        <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
      </li>
    <?php endfor; ?>

    <!-- Next button -->
    <?php if ($page < $totalPages): ?>
      <li class="page-item">
        <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next »</a>
      </li>
    <?php endif; ?>
  </ul>
</nav>

</div>
<?php include 'admin-footer.php'; ?>

</div> <!-- Close main-content -->
</body>
</html>
