<?php
// handlers/mega_prompt_flow.php

require_once __DIR__ . '/../includes/functions.php';

function startMegaPrompt($chat_id, $user_id, $prompt, $pdo) {

    $pdo->prepare("
        INSERT INTO user_prompt_sessions
        (user_id, prompt_id, current_step, created_at)
        VALUES (?, ?, 0, NOW())
    ")->execute([$user_id, $prompt['id']]);

    askNextPromptQuestion($chat_id, $prompt['id'], 0, $pdo);
}

function askNextPromptQuestion($chat_id, $prompt_id, $step, $pdo) {

    $stmt = $pdo->prepare("
        SELECT question_text
        FROM mega_prompt_questions
        WHERE prompt_id = ? AND step = ?
        LIMIT 1
    ");
    $stmt->execute([$prompt_id, $step]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$question) {
        return false;
    }

    sendMessage($chat_id, "❓ " . $question['question_text']);
    return true;
}

function handlePromptAnswer($chat_id, $user_id, $text, $pdo) {

    $stmt = $pdo->prepare("
        SELECT * FROM user_prompt_sessions
        WHERE user_id = ?
        ORDER BY id DESC
        LIMIT 1
    ");
    $stmt->execute([$user_id]);
    $session = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$session) {
        return false;
    }

    $pdo->prepare("
        INSERT INTO mega_prompt_answers
        (session_id, answer_text, created_at)
        VALUES (?, ?, NOW())
    ")->execute([$session['id'], $text]);

    $nextStep = $session['current_step'] + 1;

    $pdo->prepare("
        UPDATE user_prompt_sessions
        SET current_step = ?
        WHERE id = ?
    ")->execute([$nextStep, $session['id']]);

    return askNextPromptQuestion(
        $chat_id,
        $session['prompt_id'],
        $nextStep,
        $pdo
    );
}
