<?php
/**
 * سودانا v22 — Flow Next Step API
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);

// v22: Load engine chain so StepController can call EventBus::emit()
require_once '../../engine/QueueEngine.php';
require_once '../../engine/EventBus.php';
require_once '../../engine/SupportEngines.php';
require_once '../../engine/StepController.php';

$b         = json_decode(file_get_contents('php://input'), true) ?? [];
$sessionId = trim($b['session_id'] ?? '');
$input     = $b['input'] ?? [];
$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];

if (!$sessionId || strlen($sessionId) < 10) Kernel::fail('session_id_required', '', 400);

array_walk_recursive($input, fn(&$v) => $v = is_string($v) ? mb_substr(strip_tags(trim($v)), 0, 1000) : $v);

$result = StepController::next($sessionId, $input, $u['id'] ?? null);

if (isset($result['error'])) json_response($result, 400);
json_response($result);
