<?php
$active = 'settings';
$pageTitle = 'Admin Users';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? '';
  $postId = (int)($_POST['id'] ?? 0);
  if ($mode === 'add') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    if ($name === '' || $email === '' || $password === '') {
      $msg = "<div class='alert alert-danger'>Name, email and password required.</div>";
    } else {
      $stmt = $pdo->prepare("SELECT id FROM admin_users WHERE email=?");
      $stmt->execute([$email]);
      if ($stmt->fetch()) {
        $msg = "<div class='alert alert-danger'>Email already exists.</div>";
      } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO admin_users (name, email, password_hash) VALUES (?,?,?)");
        $stmt->execute([$name, $email, $hash]);
        $msg = "<div class='alert alert-success'>Admin added.</div>";
        $action = '';
      }
    }
  }
  if ($mode === 'password' && $postId) {
    $password = $_POST['password'] ?? '';
    if (strlen($password) < 6) {
      $msg = "<div class='alert alert-danger'>Password must be at least 6 characters.</div>";
    } else {
      $hash = password_hash($password, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare("UPDATE admin_users SET password_hash=? WHERE id=?");
      $stmt->execute([$hash, $postId]);
      $msg = "<div class='alert alert-success'>Password updated.</div>";
    }
  }
  if ($mode === 'delete' && $postId) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM admin_users");
    $stmt->execute();
    if ((int)$stmt->fetchColumn() <= 1) {
      $msg = "<div class='alert alert-danger'>Cannot delete the last admin.</div>";
    } else {
      $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id=?");
      $stmt->execute([$postId]);
      $msg = "<div class='alert alert-success'>Admin removed.</div>";
      $action = '';
      $id = 0;
    }
  }
}

$admins = $pdo->query("SELECT id, name, email, created_at FROM admin_users ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="page-header d-flex justify-content-between align-items-center">
  <div>
    <h1>Admin Users</h1>
    <p class="subtitle">Manage admin accounts</p>
  </div>
  <button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#addAdminModal">+ Add Admin</button>
</div>

<?php echo $msg; ?>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Created</th><th class="text-end">Actions</th></tr></thead>
        <tbody>
          <?php foreach ($admins as $a): ?>
          <tr>
            <td>#<?php echo $a['id']; ?></td>
            <td><?php echo htmlspecialchars($a['name']); ?></td>
            <td><?php echo htmlspecialchars($a['email']); ?></td>
            <td class="small"><?php echo date('M d, Y', strtotime($a['created_at'])); ?></td>
            <td class="text-end">
              <button type="button" class="btn btn-sm btn-outline-dark" data-bs-toggle="modal" data-bs-target="#pwdModal<?php echo $a['id']; ?>">Change Password</button>
              <?php if (count($admins) > 1): ?>
              <form method="post" class="d-inline" onsubmit="return confirm('Remove this admin?');">
                <input type="hidden" name="mode" value="delete">
                <input type="hidden" name="id" value="<?php echo $a['id']; ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Remove</button>
              </form>
              <?php endif; ?>
            </td>
          </tr>
          <div class="modal fade" id="pwdModal<?php echo $a['id']; ?>" tabindex="-1">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">Change Password - <?php echo htmlspecialchars($a['name']); ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <form method="post">
                  <div class="modal-body">
                    <input type="hidden" name="mode" value="password">
                    <input type="hidden" name="id" value="<?php echo $a['id']; ?>">
                    <label class="form-label">New Password</label>
                    <input type="password" name="password" class="form-control" required minlength="6">
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-dark">Update</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade" id="addAdminModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Add Admin</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="post">
        <div class="modal-body">
          <input type="hidden" name="mode" value="add">
          <div class="mb-3"><label class="form-label">Name</label><input type="text" name="name" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">Email</label><input type="email" name="email" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">Password</label><input type="password" name="password" class="form-control" required minlength="6"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-dark">Add Admin</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
