<?php

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? ''))
{
    die('Invalid request.');
}

$id = (int)($_POST['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,
    fullname,
    email,
    role
    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))
{
    logActivity(
        $conn,
        'User Management',
        'Delete User',
        'Deleted user "' .
        $user['fullname'] .
        '" (' .
        $user['role'] .
        ')'
    );

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