<?php
/**
 * سودانا v22 — Flow Start 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);

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) ?? [];
$flowId = trim($b['flow_id'] ?? 'medical_telemedicine_v1');
$ctx    = $b['context'] ?? [];
$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];

if (!preg_match('/^[a-z0-9_]+$/i', $flowId)) Kernel::fail('invalid_flow_id', '', 400);

$result = StepController::start($flowId, $u['id'] ?? null, $ctx);
if (isset($result['error'])) json_response($result, 404);
json_response($result);
