<?php
// Script de test: scripts/test_menu_backflow.php
// Simula flujo: MENÚ principal -> opción que abre "informacion_examenes" -> seleccionar "pruebas de embarazo" (end) -> enviar ATRÁS

require_once __DIR__ . '/../config/config.php';
require __DIR__ . '/../services/BotService.php';
require __DIR__ . '/../services/ConversationStateService.php';

// Ajusta este teléfono al usuario de prueba
$phone = '573022548060';

$db = Database::getInstance();

// Obtener usuario
$user = $db->fetch("SELECT * FROM users WHERE phone_number = :phone", ['phone' => $phone]);
if (!$user) {
    echo "Usuario con teléfono {$phone} no encontrado. Creando usuario de prueba...\n";
    $db->insert('users', ['phone_number' => $phone, 'name' => 'Test User', 'created_at' => date('Y-m-d H:i:s')]);
    $user = $db->fetch("SELECT * FROM users WHERE phone_number = :phone", ['phone' => $phone]);
    if (!$user) {
        echo "No se pudo crear el usuario de prueba. Abortando.\n";
        exit(1);
    }
}

// Stub de WhatsApp que imprime en stdout en lugar de hacer llamadas HTTP
class TestWhatsAppService {
    public function sendTextMessage($phone, $text) {
        echo "[TestWhatsApp] sendTextMessage to {$phone}: " . trim(preg_replace('/\s+/', ' ', $text)) . "\n";
    }
    public function sendTemplateMessage($phone, $template, $lang, $params) {
        echo "[TestWhatsApp] sendTemplateMessage to {$phone}: template={$template} lang={$lang}\n";
    }
}

$bot = new BotService();
// Injectar stub
$rp = new ReflectionProperty($bot, 'whatsappService');
$rp->setAccessible(true);
$rp->setValue($bot, new TestWhatsAppService());

$stateSvc = new ConversationStateService();

// Limpieza inicial: borrar estados y setear users.current_menu_id = NULL
$db->update('users', ['current_menu_id' => null, 'current_step' => 0, 'session_data' => null, 'welcome_sent_at' => date('Y-m-d H:i:s')], 'phone_number = :phone', ['phone' => $phone]);
$stateSvc->clearState($phone);

echo "== Estado inicial ==\n";
print_r($db->fetch("SELECT id, phone_number, current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));
print_r($stateSvc->getState($phone));

// 1) Enviar MENU
echo "\n1) Enviar 'MENU'\n";
$bot->processMessage($user, 'MENU');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 2) Seleccionar opción que abre informacion_examenes
// Encontramos qué opción en main_menu abre el menu 'informacion_examenes'
$options = $db->fetchAll("SELECT mo.* FROM menu_options mo JOIN menus m ON mo.menu_id = m.id WHERE m.is_root = 1 AND mo.is_active = 1");
$targetOption = null;
foreach ($options as $opt) {
    if ($opt['action_type'] === 'menu') {
        $targetMenu = $db->fetch("SELECT * FROM menus WHERE id = :id", ['id' => $opt['action_value']]);
        // action_value may be name not id; check by name
        $menuByName = $db->fetch("SELECT * FROM menus WHERE name = :name", ['name' => $opt['action_value']]);
        if ($menuByName && $menuByName['name'] === 'informacion_examenes') {
            $targetOption = $opt;
            break;
        }
    }
}

if (!$targetOption) {
    // Fallback: just try option 4 like user described
    $optNumber = 4;
    echo "No se encontró opción por nombre, usando opción {$optNumber} en main menu\n";
    $bot->processMessage($user, (string)$optNumber);
} else {
    echo "Seleccionando opción número {$targetOption['option_number']} que abre informacion_examenes\n";
    $bot->processMessage($user, (string)$targetOption['option_number']);
}

print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 3) En menu informacion_examenes, seleccionar 'Pruebas de embarazo' (usualmente opción 1)
echo "\n3) En menu informacion_examenes, seleccionar opción 1 (pruebas de embarazo)\n";
$bot->processMessage($user, '1');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 3b) En menu informacion_examenes, enviar '6' para volver al menú principal (según la config)
echo "\n3b) En menu informacion_examenes, enviar '6' para volver al menú principal\n";
$bot->processMessage($user, '6');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 4) Enviar 'ATRAS' (para comparar comportamiento)
echo "\n4) Enviar 'ATRAS'\n";
$bot->processMessage($user, 'ATRAS');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 5) Probar si reconoce otros comandos/números: enviar '1' y una palabra cualquiera y 'ASESOR' y 'MENU'
echo "\n5) Probar entradas posteriores: enviar '1', 'hola', 'ASESOR', 'MENU'\n";
$bot->processMessage($user, '1');
$bot->processMessage($user, 'hola');
$bot->processMessage($user, 'ASESOR');
$bot->processMessage($user, 'MENU');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

echo "\nTest script finished.\n";

// 4) Enviar ATRAS
echo "\n4) Enviar 'ATRAS'\n";
$bot->processMessage($user, 'ATRAS');
print_r($stateSvc->getState($phone));
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

// 5) Ahora, estando de vuelta en informacion_examenes, seleccionar '1' nuevamente
echo "\n5) En informacion_examenes, enviar '1' de nuevo\n";
$bot->processMessage($user, '1');
print_r($stateSvc->getState($phone));
echo "menu_history: " . json_encode($stateSvc->getStateData($phone, 'menu_history')) . "\n";
print_r($db->fetch("SELECT current_menu_id FROM users WHERE phone_number = :phone", ['phone' => $phone]));

echo "\nTest script finished.\n";
