<?php
declare(strict_types=1);

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
header('Referrer-Policy: no-referrer');

require dirname(__DIR__) . '/app/bootstrap.php';

if (!billing_schema_is_current()) {
    http_response_code(503);
    exit('<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Payment confirmation paused</title><body><main><h1>Payment confirmation is temporarily paused</h1><p>Your payment remains saved. Please try this page again shortly or contact Soda ZW on WhatsApp.</p></main></body></html>');
}

$reference = preg_replace('/[^A-Za-z0-9-]/', '', (string)($_GET['reference'] ?? ''));
$state = 'processing';
$heading = 'Payment is being confirmed';
$message = 'Your payment is saved. Soda ZW is securely checking the final Paynow status.';
$destination = 'https://sodazw.co.zw';
$destinationLabel = 'Return to Soda ZW';

try {
    if ($reference === '') throw new RuntimeException('Missing payment reference.');
    $find = db()->prepare('SELECT a.poll_url,a.status,a.invoice_id,d.share_token,d.share_enabled FROM online_payment_attempts a LEFT JOIN documents d ON d.id=a.invoice_id WHERE a.provider="paynow" AND a.merchant_reference=? LIMIT 1');
    $find->execute([$reference]);
    $attempt = $find->fetch();
    if (!$attempt) throw new RuntimeException('Payment reference not found.');
    if (!empty($attempt['invoice_id']) && !empty($attempt['share_enabled']) && !empty($attempt['share_token'])) {
        $destination = url('share.php?token=' . rawurlencode((string)$attempt['share_token']));
        $destinationLabel = 'View your invoice';
    }
    if (!empty($attempt['poll_url'])) {
        $result = paynow_apply_status(paynow_poll((string)$attempt['poll_url']));
        $state = (string)$result['status'];
    } else {
        $state = (string)$attempt['status'];
    }
    if ($state === 'paid') {
        $heading = 'Payment confirmed';
        $message = 'Thank you. Your Soda ZW payment has been verified and recorded. A receipt is now available from Soda ZW.';
    } elseif (in_array($state, ['cancelled','failed'], true)) {
        $heading = 'Payment was not completed';
        $message = 'Your invoice is still available. You can return to Soda ZW or contact us to choose another payment method.';
    }
} catch (Throwable $error) {
    error_log('Soda ZW Paynow return error: ' . $error->getMessage());
}

$safeReference = htmlspecialchars($reference, ENT_QUOTES, 'UTF-8');
$safeHeading = htmlspecialchars($heading, ENT_QUOTES, 'UTF-8');
$safeMessage = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
$icon = $state === 'paid' ? '&#10003;' : (in_array($state, ['cancelled','failed'], true) ? '!' : '&hellip;');
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= $safeHeading ?> &middot; Soda ZW</title><style>
:root{--navy:#082d50;--orange:#ff5a12;--green:#20ad67;--paper:#f3f7fa}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--paper);color:var(--navy);font:16px/1.55 Arial,sans-serif;padding:22px}.card{width:min(560px,100%);background:#fff;border:1px solid #d9e3eb;border-radius:24px;padding:38px;box-shadow:0 20px 55px #082d5014;text-align:center}.icon{width:68px;height:68px;border-radius:50%;display:grid;place-items:center;margin:0 auto 18px;background:<?= $state === 'paid' ? 'var(--green)' : 'var(--orange)' ?>;color:#fff;font-size:34px;font-weight:800}h1{font-size:clamp(26px,5vw,38px);line-height:1.1;margin:0 0 12px}p{color:#587087;margin:0 auto 20px}.ref{padding:12px;border-radius:12px;background:#f4f7f9;font-weight:800;margin:20px 0}.actions{display:flex;gap:10px;justify-content:center;flex-wrap:wrap}.btn{display:inline-block;padding:13px 18px;border-radius:12px;text-decoration:none;font-weight:800;background:var(--orange);color:#fff}.btn.alt{background:var(--navy)}
</style></head><body><main class="card"><div class="icon"><?= $icon ?></div><h1><?= $safeHeading ?></h1><p><?= $safeMessage ?></p><div class="ref">Payment reference <?= $safeReference ?: 'unavailable' ?></div><div class="actions"><a class="btn" href="<?=htmlspecialchars($destination,ENT_QUOTES,'UTF-8')?>"><?=htmlspecialchars($destinationLabel,ENT_QUOTES,'UTF-8')?></a><a class="btn alt" href="https://wa.me/263771739696">Contact us on WhatsApp</a></div></main></body></html>
