<?php
declare(strict_types=1);

header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
header('X-Content-Type-Options: nosniff');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    http_response_code(405);
    exit('POST only');
}

require dirname(__DIR__) . '/app/bootstrap.php';
if (!billing_schema_is_current()) {
    http_response_code(503);
    exit('RETRY');
}

try {
    if (!paynow_enabled()) throw new RuntimeException('Paynow is disabled.');
    $body = (string)file_get_contents('php://input');
    if ($body === '' || strlen($body) > 16384) throw new RuntimeException('Invalid update.');
    $incoming = paynow_parse($body);
    if (!paynow_verify($incoming)) throw new RuntimeException('Invalid Paynow signature.');
    $reference = trim((string)($incoming['reference'] ?? ''));
    if ($reference === '') throw new RuntimeException('Missing reference.');

    $find = db()->prepare('SELECT poll_url FROM online_payment_attempts WHERE provider="paynow" AND merchant_reference=? LIMIT 1');
    $find->execute([$reference]);
    $pollUrl = trim((string)$find->fetchColumn());
    if ($pollUrl === '' || !paynow_url_allowed($pollUrl)) throw new RuntimeException('Unknown payment attempt.');

    // Paynow recommends polling before treating a payment notification as final.
    $verified = paynow_poll($pollUrl);
    paynow_apply_status($verified);
    http_response_code(200);
    echo 'OK';
} catch (Throwable $error) {
    error_log('Soda ZW Paynow result error: ' . $error->getMessage());
    http_response_code(503);
    echo 'RETRY';
}
