<?php
// public/users/delete.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/flash.php';
require_role('admin');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  header('Location: /ldp/public/users/index.php');
  exit;
}

verify_csrf();
global $pdo;

$id = (int)($_POST['id'] ?? 0);
$me = current_user();

if ($id <= 0) {
  set_flash('warning', 'Invalid request.');
  header('Location: /ldp/public/users/index.php');
  exit;
}

// Do not allow deleting yourself
if ($id === (int)$me['id']) {
  set_flash('warning', 'You cannot delete your own account.');
  header('Location: /ldp/public/users/index.php');
  exit;
}

try {
  $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
  $stmt->execute([$id]);
  set_flash('success', 'User deleted.');
} catch (Throwable $e) {
  set_flash('danger', 'Unable to delete user. It may be referenced by other data.');
}
header('Location: /ldp/public/users/index.php');
exit;
