<?php
require_once __DIR__ . '/includes/admin_auth.php';
requirePermission('manage_users');
require_once __DIR__ . '/includes/db.php'; // Ensure this file sets up $db as a mysqli connection

if (!isset($_GET['id'])) {
    $_SESSION['error'] = "Invalid request";
    header("Location: users.php");
    exit();
}

$id = intval($_GET['id']);

// Prevent deleting own account
if ($id === $_SESSION['admin_id']) {
    $_SESSION['error'] = "You cannot delete your own account";
    header("Location: users.php");
    exit();
}

try {
    $stmt = $db->prepare("DELETE FROM admin_users WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        $_SESSION['success'] = "User deleted successfully";
    } else {
        throw new Exception("Failed to delete user: " . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
}

header("Location: users.php");
exit();
?>
