<?php
/**
 * AURA FARMING — Webhook Mercado Pago dos Diamantes — Parte 05
 */
require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../includes/functions.php';
require_once __DIR__ . '/../../../includes/diamond_mercadopago_functions.php';

header('Content-Type: application/json; charset=utf-8');

function afDiamondWebhookRespond(int $code, array $payload): void
{
    http_response_code($code);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$raw = file_get_contents('php://input') ?: '';
$payload = json_decode($raw, true);
if (!is_array($payload)) $payload = [];

try {
    $expectedToken = afDiamondMpWebhookToken($pdo);
    $receivedToken = (string)($_GET['token'] ?? '');
    if ($expectedToken !== '' && !hash_equals($expectedToken, $receivedToken)) {
        afDiamondMpLog($pdo, null, null, 'webhook_invalid_token', 'webhook', 'blocked', ['query' => $_GET, 'body' => $payload]);
        afDiamondWebhookRespond(403, ['ok' => false, 'error' => 'token_invalido']);
    }

    if (!afDiamondMpEnabled($pdo)) {
        afDiamondMpLog($pdo, null, null, 'webhook_mp_disabled', 'webhook', 'ignored', ['query' => $_GET, 'body' => $payload]);
        afDiamondWebhookRespond(200, ['ok' => true, 'ignored' => true, 'reason' => 'mp_disabled']);
    }

    if (!afDiamondMpIsPaymentNotification($payload, $_GET)) {
        afDiamondMpLog($pdo, null, null, 'webhook_non_payment', 'webhook', 'ignored', ['query' => $_GET, 'body' => $payload]);
        afDiamondWebhookRespond(200, ['ok' => true, 'ignored' => true, 'reason' => 'not_payment']);
    }

    $paymentId = afDiamondMpExtractPaymentId($payload, $_GET);
    if (!$paymentId) {
        afDiamondMpLog($pdo, null, null, 'webhook_missing_payment_id', 'webhook', 'ignored', ['query' => $_GET, 'body' => $payload]);
        afDiamondWebhookRespond(200, ['ok' => true, 'ignored' => true, 'reason' => 'missing_payment_id']);
    }

    $result = afDiamondMpProcessPayment($pdo, $paymentId, 'webhook');
    afDiamondWebhookRespond(200, ['ok' => true, 'result' => [
        'credited' => !empty($result['credited']),
        'duplicate' => !empty($result['duplicate']),
        'status' => $result['status'] ?? null,
        'order_id' => $result['order_id'] ?? null,
    ]]);
} catch (Throwable $e) {
    afDiamondMpLog($pdo, null, null, 'webhook_error', 'webhook', 'error', [
        'error' => $e->getMessage(),
        'query' => $_GET,
        'body' => $payload,
    ]);
    // Retorna 200 para evitar tempestade de retentativas quando o erro é de regra de negócio.
    afDiamondWebhookRespond(200, ['ok' => false, 'error' => $e->getMessage()]);
}
