<?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(['status' => 'error', 'message' => 'Datos incompletos']);
    exit;
}

// Evitar acciones repetidas con offset
$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;
foreach ($data['result'] ?? [] as $update) {
    if (isset($update['callback_query']) &&
        strpos($update['callback_query']['data'], $transactionId) !== false) {

        // Obtener acción
        list($actionType, ) = explode(':', $update['callback_query']['data']);
        $action = $actionType;

        // Marcar este update como procesado
        $_SESSION['last_update_id'] = $update['update_id'];

        // Remover botones del mensaje
        $ch = curl_init("https://api.telegram.org/bot{$config['bot_token']}/editMessageReplyMarkup");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'chat_id' => $config['chat_id'],
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => []])
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_exec($ch);
        curl_close($ch);

        break;
    }
}

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