<?php
require_once 'config/config.php';

if ($argc < 2) {
    echo "Usage: php debug_user_state.php <phone_number>\n";
    exit(1);
}
$phone = $argv[1];
$db = Database::getInstance();

$user = $db->fetch("SELECT * FROM users WHERE phone_number = :phone", ['phone' => $phone]);
if (!$user) {
    echo "User not found for phone: $phone\n";
    exit(1);
}

echo "User: id={$user['id']} phone={$user['phone_number']} name={$user['name']}\n";
echo "Flags: in_service={$user['in_service']} advisor_requested={$user['advisor_requested']} on_hold={$user['on_hold']} bot_paused_until={$user['bot_paused_until']} current_menu_id={$user['current_menu_id']} welcome_sent_at={$user['welcome_sent_at']}\n";

// Last messages
$messages = $db->fetchAll("SELECT id, direction, message_type, content, created_at FROM conversations WHERE user_id = :uid ORDER BY created_at DESC LIMIT 20", ['uid' => $user['id']]);

echo "Last messages (most recent first):\n";
foreach ($messages as $m) {
    $content = $m['content'];
    $short = mb_substr(strip_tags($content), 0, 120);
    echo " - [{$m['created_at']}] {$m['direction']} {$m['message_type']} id={$m['id']} content=" . json_encode($short) . "\n";
}

// ConversationStateService data
try {
    if (class_exists('ConversationStateService')) {
        $svc = new ConversationStateService();
        $state = $svc->getState($phone);
        echo "ConversationStateService state row: ";
        if ($state) {
            echo json_encode($state) . "\n";
            echo "Current menu via service: " . json_encode($svc->getCurrentMenuId($phone)) . "\n";
        } else {
            echo "(no state row)\n";
        }
    } else {
        echo "ConversationStateService not available\n";
    }
} catch (Exception $e) {
    echo "Error querying ConversationStateService: " . $e->getMessage() . "\n";
}

// Recent operator activity
$acts = $db->fetchAll("SELECT * FROM operator_activity WHERE user_id = :uid ORDER BY created_at DESC LIMIT 10", ['uid' => $user['id']]);
if ($acts) {
    echo "Recent operator activity:\n";
    foreach ($acts as $a) {
        echo " - [{$a['created_at']}] action={$a['action']} operator_id={$a['operator_id']} details=" . ($a['details'] ?? '') . "\n";
    }
} else {
    echo "No operator activity found\n";
}

echo "Done\n";
