<?php
include_once 'phpqrcode/qrlib.php';

function get_config($key = null) {
    static $config = null;
    if ($config === null) {
        if (!file_exists(__DIR__ . '/config.json')) {
            die('配置文件不存在');
        }
        $json = file_get_contents(__DIR__ . '/config.json');
        $config = json_decode($json, true);
    }
    if ($key === null) {
        return $config;
    }
    return $config[$key] ?? null;
}

// JSON 请求兼容处理
if (empty($_POST)) {
    $rawInput = file_get_contents('php://input');
    $_POST = json_decode($rawInput, true) ?? [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postData = $_POST;

    $sign_type = strtoupper($postData['sign_type'] ?? '');
    $sign = $postData['sign'] ?? '';

    unset($postData['sign'], $postData['sign_type']);
    ksort($postData);

    $signStr = '';
    foreach ($postData as $key => $value) {
        $signStr .= $key . '=' . $value . '&';
    }
    $signStr = rtrim($signStr, '&');

    $key = get_config("MERCHANT_KEY");
    $localSign = md5($signStr . $key);

    if ($sign_type !== 'MD5' || $sign !== $localSign) {
        die('签名验证失败！');
    }

    $order_id = $_POST['out_trade_no'] ?? '';
    $money = $_POST['money'] ?? '';
    $return_url = $_POST['return_url'] ?? '';
    $notify_url = $_POST['notify_url'] ?? '';
    $pid = $_POST['pid'] ?? '';
    $type = $_POST['type'] ?? '';
    $merchant_id = get_config("merchant_id");

    $qr_text = "https://run.lnova.top/pay/{$merchant_id}/{$money}/{$order_id}";

    ob_start();
    QRcode::png($qr_text, null, QR_ECLEVEL_L, 6);
    $imageString = ob_get_contents();
    ob_end_clean();
    $base64 = base64_encode($imageString);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>萌萌支付中~</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&display=swap" rel="stylesheet">
<style>  
        * {  
            box-sizing: border-box;  
            margin: 0;  
            padding: 0;  
        }  
        body {  
            font-family: 'ZCOOL KuaiLe', sans-serif;  
            background: url("bg.jpg") no-repeat center center;  
            background-size: cover;  
            display: flex;  
            align-items: center;  
            justify-content: center;  
            height: 100vh;  
            overflow: hidden;  
            padding-top: 50px;  
        }  

        .notice-bar {  
            background-color: rgba(255, 255, 255, 0.8);  
            backdrop-filter: blur(6px);  
            -webkit-backdrop-filter: blur(6px);  
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);  
            text-align: center;  
            padding: 10px;  
            font-size: 14px;  
            color: #e91e63;  
            position: fixed;  
            top: 0;  
            width: 100%;  
            z-index: 999;  
        }  

        .card {  
            background: rgba(255, 255, 255, 0.7);  
            backdrop-filter: blur(12px);  
            -webkit-backdrop-filter: blur(12px);  
            padding: 30px;  
            border-radius: 20px;  
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);  
            color: #333;  
            border: 1px solid rgba(255, 255, 255, 0.3);  
            max-width: 600px;  
            width: 90%;  
            display: flex;  
            align-items: center;  
            justify-content: space-around;  
            flex-direction: row;  
            flex-wrap: wrap;  
            text-align: center;  
        }  

        .qr-card {  
            background: rgba(255, 255, 255, 0.6);  
            backdrop-filter: blur(10px);  
            -webkit-backdrop-filter: blur(10px);  
            padding: 20px;  
            border-radius: 16px;  
            border: 2px solid rgba(255, 255, 255, 0.4);  
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1), 0 0 8px rgba(255, 255, 255, 0.4);  
            transition: transform 0.3s ease;  
            animation: float 3s ease-in-out infinite;  
            margin-bottom: 20px;  
        }  

        .qr-card:hover {  
            transform: scale(1.03);  
        }  

        .qr-card img {  
            border-radius: 10px;  
            width: 200px;  
            height: 200px;  
        }  

        .info-block {  
            display: flex;  
            flex-direction: column;  
            justify-content: center;  
            align-items: center;  
            max-width: 320px;  
        }  

        .timer {  
            font-size: 18px;  
            color: #e91e63;  
            margin: 8px 0;  
        }  

        #status {  
            font-size: 16px;  
            margin-top: 5px;  
        }  

        .pay-btn {  
            margin-top: 10px;  
            padding: 10px 20px;  
            font-size: 16px;  
            border: none;  
            background-color: #ff80ab;  
            color: white;  
            border-radius: 8px;  
            cursor: pointer;  
            display: none;  
        }  

        .pay-btn:hover {  
            background-color: #e91e63;  
        }  

        @keyframes float {  
            0%, 100% { transform: translateY(0); }  
            50% { transform: translateY(-5px); }  
        }  

        /* 响应式样式 */  
        @media (max-width: 768px) {  
            body {  
                height: 100vh;  
                overflow: hidden;  
            }  
            .card {  
                flex-direction: column;  
            }  
            .qr-card img {  
                width: 160px;  
                height: 160px;  
            }  
            .timer, #status {  
                font-size: 16px;  
            }  
            .pay-btn {  
                display: inline-block;  
            }  
        }  
    </style>  
</head>
<body>
    <div class="notice-bar">🚨 <strong>温馨提示喵~</strong> 如果你已支付成功但页面没有自动跳转，请稍等几秒或联系站长协助处理哟~站长QQ:723366591</div>
    <div class="card">
        <div class="info-block">
            <h2>请使用支付宝扫一扫~</h2>
            <p>订单号：<?= htmlspecialchars($order_id) ?></p>
            <p>支付金额：￥<?= htmlspecialchars($money) ?></p>
            <div class="timer" id="timer">剩余时间：90 秒</div>
            <div class="qr-card">
                <img src="data:image/png;base64,<?= $base64 ?>" alt="二维码" />
            </div>
            <div id="status">正在等待支付喵~</div>
            <button class="pay-btn" onclick="window.location.href='<?= $qr_text ?>'">启动支付宝</button>
        </div>
    </div>
<script>
    let seconds = 90;
    const timerEl = document.getElementById('timer');
    const statusEl = document.getElementById('status');

    const formData = <?= json_encode($_POST, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    const countdown = setInterval(() => {
        seconds--;
        timerEl.textContent = '剩余时间：' + seconds + ' 秒';
        if (seconds <= 0) {
            clearInterval(countdown);
            clearInterval(polling);
            statusEl.innerHTML = '支付超时了喵 (；´д｀)ゞ';
            setTimeout(() => {
                location.href = "<?= $return_url ?>";
            }, 2000);
        }
    }, 1000);

    const polling = setInterval(() => {
        const postData = Object.assign({}, formData, {
            timestamp: new Date().toISOString()
            
        });

        fetch('check.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(postData)
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                clearInterval(countdown);
                clearInterval(polling);
                statusEl.innerHTML = 'ฅ(＾・ω・＾ฅ) 支付成功！正在跳转~';
                setTimeout(() => location.href = "<?= $return_url ?>", 3000);
            }
        });
    }, 3000);
</script>
</body>
</html>
<?php exit; } ?>