<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();
Auth::requireRole('admin');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: settings.php');
    exit;
}

$userId = (int)($_POST['user_id'] ?? 0);

if (!$userId) {
    header('Location: settings.php');
    exit;
}

// Interdire de se supprimer soi-même
if ($userId === Auth::currentUserId()) {
    $_SESSION['flash'] = ['type' => 'danger', 'message' => 'Vous ne pouvez pas supprimer votre propre compte.'];
    header('Location: settings.php');
    exit;
}

$stmt = Database::get()->prepare('SELECT username, role FROM app_users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: settings.php');
    exit;
}

// Interdire de supprimer le dernier admin
if ($user['role'] === 'admin') {
    $count = (int)Database::get()->query("SELECT COUNT(*) FROM app_users WHERE role = 'admin'")->fetchColumn();
    if ($count <= 1) {
        $_SESSION['flash'] = ['type' => 'danger', 'message' => 'Impossible de supprimer le dernier compte admin.'];
        header('Location: settings.php');
        exit;
    }
}

Database::get()->prepare('DELETE FROM app_users WHERE id = ?')->execute([$userId]);
AuditLog::log('user.delete', 'user', $userId, $user['username']);
$_SESSION['flash'] = [
    'type'    => 'success',
    'message' => "Compte « {$user['username']} » supprimé.",
];

header('Location: settings.php');
exit;
