<?php

use Illuminate\Support\Facades\Log;
use Mtc\Plugins\RyftPay\Classes\RyftPay;

$path = '../../../';

require_once $path . 'core/includes/header.inc.php';

$payload = @file_get_contents('php://input');

// The HMAC covers the raw body exactly as received — verify before json_decode,
// which would not round-trip byte-for-byte.
$signature = $_SERVER['HTTP_X_RYFT_SIGNATURE'] ?? '';

if (!RyftPay::verifyWebhookSignature($payload, $signature)) {
    Log::warning('RyftPay webhook rejected: missing or invalid signature');
    return response('', 400);
}

try {
    $event = json_decode($payload, true);
    if (empty($event)) {
        throw new UnexpectedValueException('Empty payload');
    }
    Log::debug(print_r($event, true));
    RyftPay::processWebhookRequest($event);
} catch (UnexpectedValueException|Exception $e) {
    // Invalid payload
    return response('', 400);
}
