<?php
/**
 * actions/user-toggle.php — POST handler: activate or deactivate a user
 * Super admin only. POST only.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/audit.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(base_url('pages/users.php'));
}

require_role('super_admin');
csrf_verify();

$target_id = isset($_POST['id']) && ctype_digit($_POST['id']) ? (int)$_POST['id'] : 0;
$active    = isset($_POST['active']) && $_POST['active'] === '1' ? 1 : 0;

if (!$target_id) {
    set_flash('error', 'Invalid request.');
    redirect(base_url('pages/users.php'));
}

// Prevent deactivating yourself
if ($target_id === current_user_id()) {
    set_flash('error', 'You cannot deactivate your own account.');
    redirect(base_url('pages/users.php'));
}

// Verify user exists
$stmt = db()->prepare('SELECT name FROM users WHERE id = ?');
$stmt->execute([$target_id]);
$user = $stmt->fetch();

if (!$user) {
    set_flash('error', 'User not found.');
    redirect(base_url('pages/users.php'));
}

$upd = db()->prepare('UPDATE users SET active = ? WHERE id = ?');
$upd->execute([$active, $target_id]);

$action_word = $active ? 'activated' : 'deactivated';
audit_log(
    "user.$action_word",
    "User {$user['name']} was $action_word",
    $target_id,
    'user'
);

set_flash('success', 'User "' . $user['name'] . '" has been ' . $action_word . '.');
redirect(base_url('pages/users.php'));
