<?php
/**
 * 余额充值异步通知处理
 * 支付平台异步回调通知
 */
include("../MPHX/common.php");
require_once(SYSTEM_ROOT."lib/notify.class.php");

// 验证签名
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();

if($verify_result) {
    // 获取支付参数
    $out_trade_no = $_GET['out_trade_no'];
    $trade_no = $_GET['trade_no'];
    $trade_status = $_GET['trade_status'];
    $money = $_GET['money'];
    
    if($_GET['trade_status'] == 'TRADE_SUCCESS') {
        // 查询订单信息
        $order = $DB->get_row("SELECT * FROM `balance_orders` WHERE `order_no` = '{$out_trade_no}' LIMIT 1");
        
        if($order && $order['status'] != 'paid') {
            // 更新订单状态为已支付
            $DB->query("UPDATE `balance_orders` SET `status` = 'paid', `pay_time` = NOW() WHERE `order_no` = '{$out_trade_no}'");
            
            // 增加用户余额
            $uid = intval($order['uid']);
            $amount = floatval($order['amount']);
            $DB->query("UPDATE `zj` SET `balance` = `balance` + {$amount} WHERE `id` = {$uid}");
            
            // 记录日志
            $user_info = $DB->get_row("SELECT * FROM `zj` WHERE `id` = {$uid}");
            if($user_info) {
                $DB->query("INSERT INTO `log` (`user`, `date`, `lx`, `lr`, `ip`) VALUES ('{$user_info['user']}', NOW(), '余额充值', '充值金额：{$amount}元，订单号：{$out_trade_no}', '{$clientip}')");
            }
        }
        
        echo "success";
    } else {
        echo "trade_status=".$_GET['trade_status'];
    }
} else {
    echo "fail";
}
?>
