<?php
// components/Assistant/views/answer.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, Validator, FlowUtils};

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

$step = $flow->stepById(\mh_post('step_id', '', 'string')) ?? ($state['current'] ? $flow->stepById($state['current']) : null);
if (!$step) {
    http_response_code(400);
    echo '<div class="p-4 text-red-600">Invalid step</div>';
    return;
}

$stepId = (string)($step['id'] ?? '');
// Use filtered items based on current answers to align with rendering logic
$answersBefore = $state['answers'] ?? [];
$items = $flow->itemsForStep($step, $answersBefore);
$idxMap = $state['item_index'] ?? [];
$idx = isset($idxMap[$stepId]) ? (int)$idxMap[$stepId] : 0;
$idx = max(0, min($idx, max(0, count($items) - 1)));
$currentItem = $items[$idx] ?? null;

$input = \Components\Common\Request::all('post');
unset($input['step_id']);

if ($currentItem) {
    // Validate only the current item to enable single-question progression
    $id = $currentItem['id'] ?? null;
    if ($id) {
        $subsetStep = ['items' => [$currentItem]];
        $errors = Validator::validate($subsetStep, $input, $answersBefore);

        if (!empty($errors)) {
            // Re-render same step with errors (keep index unchanged)
            $answers = $state['answers'] ?? [];
            $errs = $errors;
            $old = array_intersect_key($input, [$id => true]);
            include __DIR__ . '/step.php';
            return;
        }

        // Save only the current item's answer
        $answers = $state['answers'] ?? [];
        if (array_key_exists($id, $input)) {
            $answers[$id] = $input[$id];
        } else {
            if (($currentItem['type'] ?? '') === 'multi_choice') {
                // When all checkboxes are unchecked
                $answers[$id] = [];
            }
        }
        $state['answers'] = $answers;

        // If there are more items in this step, advance within the step (re-evaluate visibility after saving)
        $itemsAfter = $flow->itemsForStep($step, $state['answers'] ?? []);
        if ($idx + 1 < count($itemsAfter)) {
            $idxMap[$stepId] = $idx + 1;
            $state['item_index'] = $idxMap;
            State::put($state, $stateKey);
            $_GET['id'] = $stepId;
            include __DIR__ . '/step.php';
            return;
        }

        // Finished all items in this step
        unset($idxMap[$stepId]);
        $state['item_index'] = $idxMap;
    }
}

// Move to next step (push current to back stack once per step)
$answers = $state['answers'] ?? [];
$nextId = $flow->nextStepId($answers, $step);
$stack = $state['stack'] ?? [];
$stack[] = $stepId;
$state['stack'] = $stack;

if (!$nextId || $nextId === ($flow->config()['end'] ?? 'done')) {
    // go to review
    $state['current'] = 'review';
    State::put($state, $stateKey);
    $_GET['id'] = 'review';
    include __DIR__ . '/step.php';
    return;
}

$state['current'] = $nextId;
State::put($state, $stateKey);
$_GET['id'] = $nextId;
include __DIR__ . '/step.php';
return;
