<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


error_reporting(E_ALL & ~E_DEPRECATED);

// 引入CMS数据库
require_once dirname(__DIR__) . '/core/db/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$data = json_decode(file_get_contents('php://input'), true) ?: [];
$action = $_GET['action'] ?? '';

// 获取CMS支付配置
function get_cms_payment_config($db) {
    $configs = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')} WHERE config_group = 'payment'");
    $cfg = [];
    foreach ($configs as $c) {
        $cfg[$c['config_key']] = $c['config_value'];
    }
    return $cfg;
}

// 生成订单号
function gen_order_no() {
    return 'CMS' . date('YmdHis') . rand(1000, 9999);
}

try {
    $cfg = get_cms_payment_config($db);

    // ---------- 微信支付 ----------
    if ($action === 'wechat_pay') {
        $order_no = trim($data['order_no'] ?? '') ?: gen_order_no();
        $amount = intval($data['amount'] ?? 0); // 单位：分
        $subject = trim($data['subject'] ?? 'CMS订单');

        if ($amount <= 0) {
            echo json_encode(['code' => 400, 'msg' => '金额错误']);
            exit;
        }

        // 检查微信支付是否启用
        if (empty($cfg['wechat_enabled']) || $cfg['wechat_enabled'] != '1') {
            echo json_encode(['code' => 403, 'msg' => '微信支付未启用']);
            exit;
        }
        if (empty($cfg['wechat_appid']) || empty($cfg['wechat_mchid']) || empty($cfg['wechat_apikey'])) {
            echo json_encode(['code' => 403, 'msg' => '微信支付配置不完整']);
            exit;
        }

        $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . '/admin/pay_notify.php';
        $timestamp = time();
        $nonce_str = bin2hex(random_bytes(16));

        $payload = [
            'appid' => $cfg['wechat_appid'],
            'mchid' => $cfg['wechat_mchid'],
            'description' => $subject,
            'out_trade_no' => $order_no,
            'amount' => ['total' => $amount, 'currency' => 'CNY'],
            'notify_url' => $notify_url,
            'scene_info' => ['payer' => ['client_ip' => ($_SERVER['REMOTE_ADDR'] ?? '127.0.0.1')]]
        ];

        $payload_json = json_encode($payload, JSON_UNESCAPED_UNICODE);
        $sign_str = "POST\n/v3/transactions/native\n" . $timestamp . "\n" . $nonce_str . "\n" . $payload_json . "\n";

        // APIv3 密钥
        $wxkey = $cfg['wechat_apikey'];
        $signature_base64 = base64_encode(hash_hmac('sha256', $sign_str, $wxkey, true));

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.mch.weixin.qq.com/v3/transactions/native');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 构建Authorization头
        $serial_no = $cfg['wechat_serial_no'] ?? '';
        $auth_header = sprintf(
            'WECHATPAY2-SHA256-RSA2048 mchid="%s",serial_no="%s",timestamp="%s",nonce_str="%s",signature="%s"',
            $cfg['wechat_mchid'],
            $serial_no,
            $timestamp,
            $nonce_str,
            $signature_base64
        );

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: ' . $auth_header
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode($response, true);
        if ($http_code === 200 && !empty($result['code_url'])) {
            // 记录本地订单
            $existing = $db->fetch("SELECT id FROM {$db->table('pay_order')} WHERE order_sn = ?", [$order_no]);
            if (!$existing) {
                $db->insert('pay_order', [
                    'order_sn' => $order_no,
                    'subject' => $subject,
                    'amount' => $amount / 100,
                    'pay_type' => 1,
                    'status' => 0,
                    'user_id' => intval($data['user_id'] ?? 0),
                    'create_time' => time()
                ]);
            }
            echo json_encode(['code' => 200, 'msg' => '下单成功', 'code_url' => $result['code_url'], 'trade_no' => $result['trade_no'] ?? '', 'order_no' => $order_no]);
        } else {
            echo json_encode(['code' => 500, 'msg' => '微信支付下单失败', 'detail' => $result['message'] ?? $response]);
        }
        exit;
    }

    // ---------- 支付宝支付 ----------
    if ($action === 'alipay_pay') {
        $order_no = trim($data['order_no'] ?? '') ?: gen_order_no();
        $amount = floatval($data['amount'] ?? 0); // 单位：元
        $subject = trim($data['subject'] ?? 'CMS订单');

        if ($amount <= 0) {
            echo json_encode(['code' => 400, 'msg' => '金额错误']);
            exit;
        }

        // 检查支付宝是否启用
        if (empty($cfg['alipay_enabled']) || $cfg['alipay_enabled'] != '1') {
            echo json_encode(['code' => 403, 'msg' => '支付宝未启用']);
            exit;
        }
        if (empty($cfg['alipay_appid']) || empty($cfg['alipay_private_key']) || empty($cfg['alipay_public_key'])) {
            echo json_encode(['code' => 403, 'msg' => '支付宝配置不完整']);
            exit;
        }

        // 引入SDK
        require_once dirname(__DIR__) . '/core/lib/alipay-sdk/alipay/aop/AopClient.php';
        require_once dirname(__DIR__) . '/core/lib/alipay-sdk/alipay/aop/request/AlipayTradePagePayRequest.php';

        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $cfg['alipay_appid'];
        $aop->rsaPrivateKey = $cfg['alipay_private_key'];
        $aop->alipayrsaPublicKey = $cfg['alipay_public_key'];
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';

        $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . '/admin/pay_notify.php';

        $request = new AlipayTradePagePayRequest();
        $request->setBizContent(json_encode([
            'out_trade_no' => $order_no,
            'total_amount' => floatval($amount),
            'subject' => $subject,
            'product_code' => 'FAST_INSTANT_TRADE_PAY'
        ], JSON_UNESCAPED_UNICODE));
        $request->setNotifyUrl($notify_url);

        // 使用pageExecute生成支付链接
        $response = $aop->pageExecute($request, 'GET');

        // 记录本地订单
        $existing = $db->fetch("SELECT id FROM {$db->table('pay_order')} WHERE order_sn = ?", [$order_no]);
        if (!$existing) {
            $db->insert('pay_order', [
                'order_sn' => $order_no,
                'subject' => $subject,
                'amount' => $amount,
                'pay_type' => 2,
                'status' => 0,
                'user_id' => intval($data['user_id'] ?? 0),
                'create_time' => time()
            ]);
        }

        // 检查返回值
        if (strpos($response, 'https://') === 0) {
            echo json_encode(['code' => 200, 'msg' => '下单成功', 'pay_url' => $response, 'order_no' => $order_no]);
        } elseif (strpos($response, '<form') !== false) {
            echo json_encode(['code' => 200, 'msg' => '下单成功', 'form' => $response, 'order_no' => $order_no]);
        } else {
            $respArr = json_decode($response, true);
            if ($respArr && isset($respArr['alipay_trade_page_pay_response'])) {
                $respNode = $respArr['alipay_trade_page_pay_response'];
                if (!empty($respNode['code']) && $respNode['code'] !== '10000') {
                    $subMsg = $respNode['sub_msg'] ?? $respNode['msg'] ?? '未知错误';
                    echo json_encode(['code' => 500, 'msg' => '支付宝下单失败: ' . $subMsg]);
                    exit;
                }
            }
            echo json_encode(['code' => 500, 'msg' => '支付宝下单异常', 'detail' => $response]);
        }
        exit;
    }

    // ---------- 查询订单 ----------
    if ($action === 'query_order') {
        $order_no = trim($data['order_no'] ?? '');
        $order = $db->fetch("SELECT * FROM {$db->table('pay_order')} WHERE order_sn = ?", [$order_no]);
        if ($order) {
            echo json_encode(['code' => 200, 'data' => $order]);
        } else {
            echo json_encode(['code' => 404, 'msg' => '订单不存在']);
        }
        exit;
    }

    echo json_encode(['code' => 400, 'msg' => '未知操作']);

} catch (Exception $e) {
    echo json_encode(['code' => 500, 'msg' => '服务器错误: ' . $e->getMessage()]);
}
?>
