<?php
/**
 * Webhook IPN de Mercado Pago — actualiza estado de pago sin depender del redirect del navegador.
 * Configurar en MP: https://taqueriaelmexicano.com.mx/services/mercadopago_webhook.php
 */
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/config_mercadopago.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/MercadoPagoPedidoService.php';

$logFile = __DIR__ . '/webhook_mp.log';

function webhookLog(string $msg): void
{
    global $logFile;
    @file_put_contents($logFile, date('c') . ' ' . $msg . PHP_EOL, FILE_APPEND);
}

try {
    $raw = file_get_contents('php://input');
    webhookLog('RAW: ' . substr($raw ?: '', 0, 2000));

    $payload = json_decode($raw, true);
    $topic = $_GET['topic'] ?? $_GET['type'] ?? ($payload['type'] ?? null);
    $dataId = $_GET['id'] ?? $_GET['data.id'] ?? null;

    if (!$dataId && isset($payload['data']['id'])) {
        $dataId = $payload['data']['id'];
    }

    // Notificación clásica: ?topic=payment&id=123
    if ($topic === 'payment' || ($payload['type'] ?? '') === 'payment') {
        if (!$dataId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Falta id de pago']);
            exit;
        }

        $result = MercadoPagoPedidoService::procesarPagoPorId((string)$dataId);
        webhookLog('PAYMENT ' . $dataId . ': ' . json_encode($result));

        http_response_code($result['ok'] ? 200 : 404);
        echo json_encode(['success' => $result['ok'], 'data' => $result]);
        exit;
    }

    // merchant_order u otros: responder 200 para no reintentar en bucle
    http_response_code(200);
    echo json_encode(['success' => true, 'message' => 'Evento ignorado', 'topic' => $topic]);
} catch (Throwable $e) {
    webhookLog('ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
