<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();
require_role('admin');

$currentUserId = (int)admin_user()['id'];

function admin_count(): int {
    return (int)db()->query("SELECT COUNT(*) FROM users WHERE role = 'admin'")->fetchColumn();
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = in_array($_POST['role'] ?? '', ['admin', 'editor'], true) ? $_POST['role'] : 'editor';
    $password = $_POST['password'] ?? '';
    $editId = !empty($_POST['id']) ? (int)$_POST['id'] : null;

    if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please provide a valid name and email.';
    }

    if (empty($errors) && $editId) {
        // Guard: can't demote the last remaining admin.
        $stmt = db()->prepare('SELECT role FROM users WHERE id = ?');
        $stmt->execute([$editId]);
        $existingRole = $stmt->fetchColumn();
        if ($existingRole === 'admin' && $role !== 'admin' && admin_count() <= 1) {
            $errors[] = 'You cannot demote the last remaining admin account.';
        }
    }

    if (empty($errors)) {
        if ($editId) {
            if ($password !== '') {
                $stmt = db()->prepare('UPDATE users SET name=?, email=?, role=?, password_hash=? WHERE id=?');
                $stmt->execute([$name, $email, $role, password_hash($password, PASSWORD_DEFAULT), $editId]);
            } else {
                $stmt = db()->prepare('UPDATE users SET name=?, email=?, role=? WHERE id=?');
                $stmt->execute([$name, $email, $role, $editId]);
            }
            // Keep the session's own role/name in sync if editing self.
            if ($editId === $currentUserId) {
                $_SESSION['admin_user']['name'] = $name;
                $_SESSION['admin_user']['role'] = $role;
            }
            flash_set('success', 'User updated.');
        } else {
            if ($password === '') {
                $errors[] = 'A password is required for new accounts.';
            } else {
                $stmt = db()->prepare('INSERT INTO users (name, email, password_hash, role) VALUES (?,?,?,?)');
                $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT), $role]);
                flash_set('success', 'User created.');
            }
        }
        if (empty($errors)) {
            header('Location: /admin/users.php');
            exit;
        }
    }
}

if (!empty($_GET['delete']) && isset($_GET['csrf']) && hash_equals($_SESSION['csrf'] ?? '', $_GET['csrf'])) {
    $deleteId = (int)$_GET['delete'];
    if ($deleteId === $currentUserId) {
        flash_set('success', 'You cannot delete your own account while logged in.');
    } else {
        $stmt = db()->prepare('SELECT role FROM users WHERE id = ?');
        $stmt->execute([$deleteId]);
        $targetRole = $stmt->fetchColumn();
        if ($targetRole === 'admin' && admin_count() <= 1) {
            flash_set('success', 'You cannot delete the last remaining admin account.');
        } else {
            db()->prepare('DELETE FROM users WHERE id = ?')->execute([$deleteId]);
            flash_set('success', 'User deleted.');
        }
    }
    header('Location: /admin/users.php');
    exit;
}

$editing = null;
if (!empty($_GET['edit'])) {
    $stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([(int)$_GET['edit']]);
    $editing = $stmt->fetch();
}

$users = db()->query('SELECT * FROM users ORDER BY created_at')->fetchAll();
$pageTitle = 'Admin Users';
include __DIR__ . '/includes/layout-header.php';
$flash = flash_get('success');
?>
<?php if ($flash): ?><div class="form-success mb-6"><?= e($flash) ?></div><?php endif; ?>
<?php foreach ($errors as $err): ?><div class="form-error mb-4"><?= e($err) ?></div><?php endforeach; ?>

<div class="admin-card mb-6">
  <h3><?= $editing ? 'Edit User' : 'Add User' ?></h3>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"><?php endif; ?>
    <div class="field-row mb-4">
      <div class="field"><label>Name</label><input type="text" name="name" value="<?= e($editing['name'] ?? '') ?>" required></div>
      <div class="field"><label>Email</label><input type="email" name="email" value="<?= e($editing['email'] ?? '') ?>" required></div>
    </div>
    <div class="field-row mb-4">
      <div class="field">
        <label>Role</label>
        <select name="role">
          <option value="admin" <?= ($editing['role'] ?? '') === 'admin' ? 'selected' : '' ?>>Admin — full access</option>
          <option value="editor" <?= ($editing['role'] ?? 'editor') === 'editor' ? 'selected' : '' ?>>Editor — content only, no users/settings</option>
        </select>
      </div>
      <div class="field">
        <label><?= $editing ? 'New Password (leave blank to keep current)' : 'Password' ?></label>
        <input type="password" name="password" autocomplete="new-password">
      </div>
    </div>
    <button type="submit" class="btn btn-primary"><?= $editing ? 'Update' : 'Add' ?> User</button>
    <?php if ($editing): ?><a href="/admin/users.php" class="btn btn-outline">Cancel</a><?php endif; ?>
  </form>
</div>

<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Joined</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($users as $u): ?>
        <tr>
          <td class="fw-semibold"><?= e($u['name']) ?> <?= (int)$u['id'] === $currentUserId ? '<span class="text-xs text-muted">(you)</span>' : '' ?></td>
          <td><?= e($u['email']) ?></td>
          <td><span class="badge badge-outline"><?= e(ucfirst($u['role'])) ?></span></td>
          <td><?= date('M j, Y', strtotime($u['created_at'])) ?></td>
          <td class="flex gap-2">
            <a href="/admin/users.php?edit=<?= (int)$u['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/users.php?delete=<?= (int)$u['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this user account?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
