<?php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';

if ($_SESSION['role'] != 'admin')
{
    die("Access Denied");
}

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

// System Administrator cannot be deleted
if ($id == 1) {
    die("System Administrator cannot be deleted.");
}

if ($id <= 0)
{
    die("Invalid User ID");
}

/*
|--------------------------------------------------------------------------
| Prevent deleting own account
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "SELECT id, email
     FROM users
     WHERE id = ?"
);

mysqli_stmt_bind_param(
    $stmt,
    "i",
    $id
);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) == 0)
{
    die("User not found");
}

$user = mysqli_fetch_assoc($result);

if (
    isset($_SESSION['email']) &&
    $_SESSION['email'] == $user['email']
)
{
    die("You cannot delete your own account.");
}

/*
|--------------------------------------------------------------------------
| Delete User
|--------------------------------------------------------------------------
*/

$stmt = mysqli_prepare(
    $conn,
    "DELETE FROM users
     WHERE id = ?"
);

mysqli_stmt_bind_param(
    $stmt,
    "i",
    $id
);

if (mysqli_stmt_execute($stmt))
{
    header("Location: users.php?msg=deleted");
    exit();
}
else
{
    die(
        "Delete Failed : "
        . mysqli_error($conn)
    );
}
?>