<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\PaymentGateway;
use App\Core\Response;

$gateway = strtolower(trim((string)($_GET['gateway'] ?? $_POST['gateway'] ?? '')));
$result = strtolower(trim((string)($_GET['result'] ?? 'ipn')));
$payload = $_POST + $_GET;
try {
    if ($gateway !== 'sslcommerz') {
        Response::json(['ok'=>false,'message'=>'Unsigned callbacks for this gateway are disabled.'], 400);
    }
    $out = PaymentGateway::handleSslCommerzCallback($payload, $result);
    if ($result === 'ipn') Response::json($out, $out['ok'] ? 200 : 422);
    $orderId = (int)($out['order_id'] ?? 0);
    if ($out['ok']) {
        header('Location: ' . url('public/thank-you.php?order_id=' . $orderId));
    } else {
        set_flash('error', (string)$out['message']);
        header('Location: ' . url('public/thank-you.php?order_id=' . $orderId));
    }
    exit;
} catch (Throwable $e) {
    if ($result === 'ipn') Response::json(['ok'=>false,'message'=>$e->getMessage()], 422);
    set_flash('error', $e->getMessage());
    header('Location: ' . url('public/thank-you.php'));
    exit;
}
