<?php
/* *
 * 功能：彩虹易支付页面跳转同步通知页面
 * 说明：
 * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 */

 require_once("EpayCore.class.php");
 require_once '../../../include/common.php';

// 计算得出通知验证结果
$epay = new EpayCore($epay_config);
$verify_result = $epay->verifyReturn();

if ($verify_result) { // 验证成功
    // 商户订单号
    $out_trade_no = $_GET['out_trade_no'];

    // 向数据库查询订单
    $stmt = $pdo->prepare("SELECT user_id, amount, status FROM " . table('orders') . " WHERE order_number = :order_number");
    $stmt->execute(['order_number' => $out_trade_no]);
    $order = $stmt->fetch();

    if ($order && $order['status'] == 0) { // 确保订单存在且状态为0
        $userId = $order['user_id'];
        $amount = $order['amount'];

        // 更新用户余额
        $updateBalance = $pdo->prepare("UPDATE " . table('users') . " SET balance = balance + :amount WHERE id = :user_id");
        $updateBalance->execute([
            'amount' => $amount,
            'user_id' => $userId
        ]);

        // 查询用户的最新余额
        $stmtUser = $pdo->prepare("SELECT balance FROM " . table('users') . " WHERE id = :id");
        $stmtUser->execute(['id' => $userId]);
        $user = $stmtUser->fetch();

        if ($user) {
            // 记录余额变动日志
            $stmtLog = $pdo->prepare("INSERT INTO " . table('balance_logs') . " (user_id, change_amount, new_balance, reason) VALUES (:user_id, :change_amount, :new_balance, :reason)");
            $stmtLog->execute([
                'user_id' => $userId,
                'change_amount' => $amount, 
                'new_balance' => $user['balance'] + $amount, 
                'reason' => "余额充值，订单号: " . $out_trade_no 
            ]);
        }

        // 收集所有参数，并构建完整的补单 URL
        $params = [
            'pid' => $_GET['pid'] ?? '',
            'trade_no' => $_GET['trade_no'] ?? '',
            'out_trade_no' => $out_trade_no, // 保持原值
            'type' => $_GET['type'] ?? '',
            'name' => $_GET['name'] ?? '',
            'money' => $amount, // 使用我们操作的金额
            'trade_status' => $_GET['trade_status'] ?? '',
            'sign' => $_GET['sign'] ?? '',
            'sign_type' => $_GET['sign_type'] ?? ''
        ];

        // 直接拼接参数到 URL
        $returnUrl = "http://{$_SERVER['HTTP_HOST']}/other/epay/return_url.php?" . http_build_query($params);

        // 更新订单状态为已处理和已支付，同时添加补单 URL
        $updateOrderStatus = $pdo->prepare("UPDATE " . table('orders') . " SET status = 1, return_url = :return_url WHERE order_number = :order_number");
        $updateOrderStatus->execute([
            'return_url' => $returnUrl,
            'order_number' => $out_trade_no
        ]);

        echo "<h3>充值成功，金额已添加至用户账户。</h3><br />";
        echo "<script>
                setTimeout(function() {
                    window.location.href = '/user';
                }, 1000);
              </script>";
        
    } else {
        echo "<h3>该订单已处理或不存在！</h3>";
        echo "<script>
                setTimeout(function() {
                    window.location.href = '/user'; 
                }, 1000); 
              </script>";
        
    }
} else {
    // 验证失败
    echo "<h3>验证失败</h3>";
    echo "<script>
            setTimeout(function() {
                window.location.href = '/user';
            }, 2000);
          </script>";
}
?>
