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

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

    if ($user) {
        $newState = $user['is_active'] ? 0 : 1;
        Auth::toggleActive($userId, (bool)$newState);
        $label = $newState ? 'activé' : 'désactivé';
        AuditLog::log('user.toggle', 'user', $userId, $user['username'] . " → $label");
        $_SESSION['flash'] = ['type' => 'success', 'message' => "Compte « {$user['username']} » $label."];
    }
}

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