<?php
/**
 * Delete user (church staff roles) - admin only. Cannot delete admin or self.
 */

require_once __DIR__ . '/../../includes/user-roles.php';

$deletableRoles = nazarethChurchStaffRoleSlugs();
$stmt = $pdo->prepare('SELECT id, username, role FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user || !in_array($user['role'], $deletableRoles, true)) {
    header('Location: ' . BASE_PATH . '/users?toast_error=' . urlencode('User not found or cannot be deleted.'));
    exit;
}

if ($user['id'] == currentUserId()) {
    header('Location: ' . BASE_PATH . '/users?toast_error=' . urlencode('You cannot delete your own account.'));
    exit;
}

$placeholders = implode(',', array_fill(0, count($deletableRoles), '?'));
$pdo->prepare("DELETE FROM users WHERE id = ? AND role IN ($placeholders)")->execute(array_merge([$id], $deletableRoles));
header('Location: ' . BASE_PATH . '/users?toast=' . urlencode('User deleted.'));
exit;
