<?php
function generateSign($params, $key) {
    ksort($params);
    $string = '';
    foreach ($params as $k => $v) {
        if ($v !== '' && $k !== 'sign' && $k !== 'sign_type') {
            $string .= "$k=$v&";
        }
    }
    $string .= "key=$key";
    return strtolower(md5($string));
}

$merchantId = "991100578";
$apiKey     = "d9c774db82d94dcf827b2a8b0ecbc203";
$responseData = null;
$raw = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $transferId = $_POST['mch_transferId'] ?? '';

    $params = [
        'mch_id'         => $merchantId,
        'mch_transferId' => $transferId
    ];

    $sign = generateSign($params, $apiKey);
    $params['sign'] = $sign;
    $params['sign_type'] = 'MD5';

    $ch = curl_init("https://pay.sunpayonline.xyz/query/transfer");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);

    $raw = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($raw, true);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Query SunPay Payment</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 2em; }
        input[type=text], input[type=submit] { padding: 10px; margin: 10px 0; width: 100%; max-width: 400px; }
        textarea, pre { width: 100%; height: 200px; margin-top: 10px; background: #f9f9f9; padding: 10px; border: 1px solid #ccc; }
    </style>
</head>
<body>
    <h2>SunPay Payment Status Inquiry</h2>
    <form method="POST">
        <label for="mch_transferId">Enter Merchant Transfer ID:</label><br>
        <input type="text" name="mch_transferId" required />
        <input type="submit" value="Check Status" />
    </form>

    <?php if ($raw): ?>
        <h3>Raw Response:</h3>
        <textarea readonly><?= htmlspecialchars($raw) ?></textarea>

        <?php if ($responseData): ?>
            <h3>Parsed Response:</h3>
            <pre><?= print_r($responseData, true) ?></pre>
        <?php endif; ?>
    <?php endif; ?>
</body>
</html>
