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

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

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

if ($verify_result) { // 验证成功

    // 商户订单号
    $out_trade_no = $_GET['out_trade_no'];

    // 彩虹易支付交易号
    $trade_no = $_GET['trade_no'];

    // 交易状态
    $trade_status = $_GET['trade_status'];

    // 支付金额
    $money = floatval($_GET['money']);

    if ($trade_status == 'TRADE_SUCCESS') {
        // 判断该笔订单是否在商户网站中已经做过处理
        $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) { // 确认订单存在且未处理
            $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 // 变动的原因
                ]);
            }

            // 更新订单状态
            $updateOrderStatus = $pdo->prepare("UPDATE " . table('orders') . " SET status = 1, status = 1 WHERE order_number = :order_number");
            $updateOrderStatus->execute(['order_number' => $out_trade_no]);

            echo "success"; // 返回成功响应
            echo "<script>
                    setTimeout(function() {
                        window.location.href = '/user';
                    }, 1500);
                  </script>";
        } else {
            echo "该订单已处理或不存在！"; // 返回提示信息
            echo "<script>
                    setTimeout(function() {
                        window.location.href = '/user';
                    }, 1500);
                  </script>";
        }
    }
} else {
    // 验证失败
    echo "fail";
    echo "<script>
            setTimeout(function() {
                window.location.href = '/user';
            }, 1500);
          </script>";
}
?>
