<?php
/**
 * 支付异步回调
 */
require_once dirname(__DIR__, 2) . '/config.php';
require_once dirname(__DIR__, 2) . '/vendor/epay/config.php';

$pay_config = json_decode(getSiteConfig('payment_config') ?? '{}', true);
$key = $pay_config['key'] ?? '2LZ3NAkLVBixGcfz4oMz';

$money = $_GET["money"] ?? '';
$name = $_GET["name"] ?? '';
$pid = $_GET["pid"] ?? '';
$out_trade_no = $_GET["out_trade_no"] ?? '';
$trade_no = $_GET["trade_no"] ?? '';
$trade_status = $_GET["trade_status"] ?? '';
$type = $_GET["type"] ?? '';
$param = $_GET["param"] ?? '';
$sign = $_GET["sign"] ?? '';
$sign_type = $_GET["sign_type"] ?? '';

$arr = array(
    "pid" => $pid,
    "type" => $type,
    "out_trade_no" => $out_trade_no,
    "trade_no" => $trade_no,
    "name" => $name,
    "money" => $money,
    "param" => $param,
    "trade_status" => $trade_status,
    "sign_type" => $sign_type
);

if ($sign == get_sign($arr, $key)) {
    echo "success";
    
    $order = $db->fetchOne("SELECT * FROM orders WHERE order_no = '$out_trade_no'");
    if ($order && $order['status'] == 'pending') {
        $db->query("UPDATE orders SET status = 'paid', paid_at = NOW() WHERE order_no = '$out_trade_no'");
        
        if ($order['type'] == 'recharge') {
            $db->query("UPDATE users SET balance = balance + {$order['amount']} WHERE id = {$order['user_id']}");
            addBalanceLog($order['user_id'], $order['amount'], 'recharge', "订单号：{$out_trade_no}");
            
            // 发送充值成功邮件通知（获取支付方式）
            require_once dirname(__DIR__, 2) . '/includes/mail_helper.php';
            $user = $db->fetchOne("SELECT * FROM users WHERE id = {$order['user_id']}");
            
            // 根据支付类型参数判断支付方式
            $payment_method = '在线支付';
            if (!empty($type)) {
                if ($type == 'alipay') {
                    $payment_method = '支付宝';
                } elseif ($type == 'wxpay') {
                    $payment_method = '微信支付';
                }
            }
            
            if ($user && !empty($user['email']) && ($user['email_notify'] ?? 1)) {
                sendRechargeNotification($user, $order['amount'], $out_trade_no, $payment_method);
            }
        } elseif ($order['type'] == 'app') {
            $app = $db->fetchOne("SELECT * FROM apps WHERE id = {$order['item_id']}");
            if ($app) {
                $license_code = generateLicenseCode();
                $expire_date = $app['duration_days'] > 0 ? date('Y-m-d', strtotime("+{$app['duration_days']} days")) : null;
                $db->query("INSERT INTO licenses (license_code, app_id, user_id, expire_date) VALUES ('$license_code', {$app['id']}, {$order['user_id']}, " . ($expire_date ? "'$expire_date'" : "NULL") . ")");
                
                // 发送消费通知（购买应用）
                require_once dirname(__DIR__, 2) . '/includes/mail_helper.php';
                $user = $db->fetchOne("SELECT * FROM users WHERE id = {$order['user_id']}");
                if ($user && !empty($user['email']) && ($user['email_notify'] ?? 1)) {
                    sendConsumeNotification($user, $app['name'], $order['amount'], $out_trade_no);
                }
                
                // ========== 邀请返利（购买应用） ==========
                // 查找用户是否是被邀请的
                $invite_record = $db->fetchOne("SELECT * FROM invite_records WHERE invitee_id = {$order['user_id']} AND status = 0");
                if ($invite_record) {
                    // 更新邀请记录状态
                    $db->query("UPDATE invite_records SET status = 1 WHERE id = {$invite_record['id']}");
                    
                    // 计算返利（10%）
                    $rebate_rate = 10;
                    $rebate_amount = $order['amount'] * $rebate_rate / 100;
                    
                    if ($rebate_amount > 0) {
                        // 添加返利记录
                        $db->query("INSERT INTO rebate_records (user_id, from_user_id, order_id, amount, rate) 
                                    VALUES ({$invite_record['inviter_id']}, {$order['user_id']}, {$order['id']}, $rebate_amount, $rebate_rate)");
                        
                        // 增加用户返利余额
                        $db->query("UPDATE users SET rebate_balance = rebate_balance + $rebate_amount WHERE id = {$invite_record['inviter_id']}");
                    }
                }
                // ========== 邀请返利结束 ==========
            }
        } elseif ($order['type'] == 'group') {
            $group = $db->fetchOne("SELECT * FROM user_groups WHERE id = {$order['item_id']}");
            if ($group) {
                $expire_date = $group['duration_days'] > 0 ? date('Y-m-d', strtotime("+{$group['duration_days']} days")) : null;
                $db->query("INSERT INTO user_group_purchases (user_id, group_id, expire_date) VALUES ({$order['user_id']}, {$group['id']}, " . ($expire_date ? "'$expire_date'" : "NULL") . ")");
                $db->query("UPDATE users SET group_id = {$group['id']} WHERE id = {$order['user_id']}");
                
                // 发送消费通知（购买会员）
                require_once dirname(__DIR__, 2) . '/includes/mail_helper.php';
                $user = $db->fetchOne("SELECT * FROM users WHERE id = {$order['user_id']}");
                if ($user && !empty($user['email']) && ($user['email_notify'] ?? 1)) {
                    sendConsumeNotification($user, $group['name'], $order['amount'], $out_trade_no);
                }
                
                // ========== 邀请返利（购买会员） ==========
                $invite_record = $db->fetchOne("SELECT * FROM invite_records WHERE invitee_id = {$order['user_id']} AND status = 0");
                if ($invite_record) {
                    $db->query("UPDATE invite_records SET status = 1 WHERE id = {$invite_record['id']}");
                    
                    $rebate_rate = 10;
                    $rebate_amount = $order['amount'] * $rebate_rate / 100;
                    
                    if ($rebate_amount > 0) {
                        $db->query("INSERT INTO rebate_records (user_id, from_user_id, order_id, amount, rate) 
                                    VALUES ({$invite_record['inviter_id']}, {$order['user_id']}, {$order['id']}, $rebate_amount, $rebate_rate)");
                        $db->query("UPDATE users SET rebate_balance = rebate_balance + $rebate_amount WHERE id = {$invite_record['inviter_id']}");
                    }
                }
                // ========== 邀请返利结束 ==========
            }
        }
    }
} else {
    echo "error";
}
?>