<?php
// components/Assistant/views/back.php
if (!defined('BEEZUI_ROOT')) {
    // This file resides in <root>/components/Assistant/views
    define('BEEZUI_ROOT', dirname(dirname(dirname(__DIR__))));
}
require_once BEEZUI_ROOT . '/components/index.php';

use Components\Assistant\{Flow, State, FlowUtils};

[$flowId, $yaml] = FlowUtils::resolveFlowAndYaml();
$stateKey = FlowUtils::stateKeyFor($flowId);
$flow = new Flow($yaml);
$state = State::get($stateKey);

$currentId = $state['current'] ?? null;
$idxMap = $state['item_index'] ?? [];

// If we're mid-step (item index > 0), go back within the same step
if ($currentId && isset($idxMap[$currentId]) && (int)$idxMap[$currentId] > 0) {
    $idxMap[$currentId] = (int)$idxMap[$currentId] - 1;
    $state['item_index'] = $idxMap;
    State::put($state, $stateKey);
    $_GET['id'] = $currentId;
    include __DIR__ . '/step.php';
    return;
}

// Otherwise pop from the back stack to previous step
$stack = $state['stack'] ?? [];
$prev = null;
while (!empty($stack)) {
    $candidate = array_pop($stack);
    if ($candidate && $candidate !== $currentId) { $prev = $candidate; break; }
}
$state['stack'] = $stack;

if ($prev) {
    $state['current'] = $prev;
    // When going back to a previous step, set its item index to the last item to allow editing
    $step = $flow->stepById($prev);
    if ($step) {
        $count = isset($step['items']) && is_array($step['items']) ? count($step['items']) : 0;
        if ($count > 0) {
            $idxMap[$prev] = max(0, $count - 1);
            $state['item_index'] = $idxMap;
        }
    }
    State::put($state, $stateKey);
    $_GET['id'] = $prev;
    include __DIR__ . '/step.php';
    return;
}

// fallback to first step
$state['current'] = $flow->firstStepId();
State::put($state, $stateKey);
$_GET['id'] = $state['current'];
include __DIR__ . '/step.php';
