<?php
/**
 * TOPBD API — Server-Side Payment Verification & Listing Activation Engine
 * Supports both JSON AJAX calls and Browser Gateway Callbacks / Redirects
 */

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/ranking.php';
require_once __DIR__ . '/../includes/PaymentManager.php';

$isAjax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') 
          || (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)
          || ($_SERVER['REQUEST_METHOD'] === 'POST');

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$txnId = trim($input['transaction_id'] ?? $_GET['transaction_id'] ?? $_POST['tran_id'] ?? $_GET['tran_id'] ?? '');

if (empty($txnId)) {
    if ($isAjax) {
        json_response(['success' => false, 'message' => 'Transaction ID is required for verification.'], 400);
    } else {
        header("Location: /?payment_status=error&message=" . urlencode("Transaction ID missing"));
        exit;
    }
}

try {
    $mergedGatewayData = array_merge($_GET, $_POST, is_array($input) ? $input : []);
    $result = PaymentManager::verifyAndActivatePayment($txnId, $mergedGatewayData);

    if ($isAjax) {
        json_response($result);
    } else {
        header("Location: /?payment_status=success&txn_id=" . urlencode($txnId));
        exit;
    }
} catch (Exception $e) {
    if ($isAjax) {
        json_response(['success' => false, 'message' => $e->getMessage()], 400);
    } else {
        header("Location: /?payment_status=error&message=" . urlencode($e->getMessage()));
        exit;
    }
}
