<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'users', 'edit', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['user_id'])) {
    json_response(false, 'User ID required.', [], 400);
}

$target_user_id = (int)$input['user_id'];

/* FETCH TARGET USER */
$stmt = $pdo->prepare("
    SELECT u.id, u.role, u.company_id, c.rsp_id, u.status
    FROM users u
    LEFT JOIN companies c ON c.id = u.company_id
    WHERE u.id = ?
    LIMIT 1
");
$stmt->execute([$target_user_id]);
$target = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$target) {
    json_response(false, 'User not found.', [], 404);
}

/* BLOCK SELF-DISABLE */
if ($target_user_id === (int)$user['id']) {
    json_response(false, 'Cannot modify your own account status.', [], 403);
}

/* BLOCK SUPER_ADMIN */
if ($target['role'] === 'super_admin') {
    json_response(false, 'Cannot modify super_admin account.', [], 403);
}

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {
    enforce_rsp_isolation($user, (int)$target['rsp_id']);
}

/* TOGGLE */
$new_status = ($target['status'] === 'active') ? 'inactive' : 'active';

$stmt = $pdo->prepare("
    UPDATE users
    SET status = ?
    WHERE id = ?
");
$stmt->execute([$new_status, $target_user_id]);

/* AUDIT */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'users',
    'status_toggle',
    $target_user_id
);

/* RESPONSE */
json_response(true, 'User status updated.', [
    'user_id' => $target_user_id,
    'new_status' => $new_status
]);