44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
require_once 'session.php';
|
|
check_admin();
|
|
require_once 'db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$id = $_POST['id'] ?? null;
|
|
|
|
if ($id) {
|
|
// Prevent deleting the last admin user
|
|
$db = db();
|
|
if ($id == $_SESSION['user_id']) {
|
|
header("Location: users.php?error=Cannot delete yourself");
|
|
exit;
|
|
}
|
|
|
|
$stmt = $db->prepare("SELECT role FROM users WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && $user['role'] === 'admin') {
|
|
$stmt = $db->query("SELECT COUNT(*) FROM users WHERE role = 'admin'");
|
|
$admin_count = $stmt->fetchColumn();
|
|
if ($admin_count <= 1) {
|
|
header("Location: users.php?error=Cannot delete the last admin");
|
|
exit;
|
|
}
|
|
}
|
|
|
|
try {
|
|
$stmt = $db->prepare("DELETE FROM users WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
header("Location: users.php?success=User deleted");
|
|
exit;
|
|
} catch (PDOException $e) {
|
|
header("Location: users.php?error=Error deleting user");
|
|
exit;
|
|
}
|
|
}
|
|
} else {
|
|
header("Location: users.php");
|
|
exit;
|
|
}
|
|
?>
|