<?php
require_once '../partials/header.php';
require_once '../db/config.php';
require_once '../auth.php';

// Ensure the user is logged in and is an admin
if (!is_logged_in() || !is_admin()) {
    header('Location: ../login.php');
    exit();
}

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $user_id = $_GET['id'];

    // Prevent admin from deleting their own account
    if ($user_id == $_SESSION['user_id']) {
        header('Location: users.php?error=' . urlencode('You cannot delete your own account.'));
        exit();
    }

    try {
        $db = db();
        $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$user_id]);

        header('Location: users.php?success=' . urlencode('User deleted successfully.'));
        exit();
    } catch (PDOException $e) {
        header('Location: users.php?error=' . urlencode('Error deleting user.'));
        exit();
    }
} else {
    header('Location: users.php');
    exit();
}
