<?php
/**
 * 支付发起 - MAPI方式（API调用，获取支付二维码）
 */
ob_start();
require_once dirname(__DIR__, 2) . '/config.php';
require_once dirname(__DIR__, 2) . '/vendor/epay/config.php';

$order_no = $_GET['order_no'] ?? '';
$amount = floatval($_GET['amount'] ?? 0);
$name = $_GET['name'] ?? '商品购买';
$type = $_GET['type'] ?? 'alipay';

if (empty($order_no) || $amount <= 0) {
    die(json_encode(['code' => 0, 'msg' => '参数错误']));
}

// 允许的支付方式
$allowed_types = ['alipay', 'wxpay'];
if (!in_array($type, $allowed_types)) {
    $type = 'alipay';
}

// ========== 从数据库读取支付配置 ==========
$payment_config = json_decode(getSiteConfig('payment_config') ?? '{}', true);

// 如果数据库没有配置，使用默认空值（会提示配置错误）
$apiurl = $payment_config['api_url'] ?? '';
$pid = $payment_config['pid'] ?? '';
$key = $payment_config['key'] ?? '';

// 检查支付方式是否启用
if ($type == 'alipay' && empty($payment_config['pay_alipay'])) {
    die(json_encode(['code' => 0, 'msg' => '支付宝支付未启用']));
}
if ($type == 'wxpay' && empty($payment_config['pay_wxpay'])) {
    die(json_encode(['code' => 0, 'msg' => '微信支付未启用']));
}

// 检查配置是否完整
if (empty($apiurl) || empty($pid) || empty($key)) {
    die(json_encode(['code' => 0, 'msg' => '支付配置不完整，请联系管理员']));
}

// 确保 apiurl 以 / 结尾
if (substr($apiurl, -1) !== '/') {
    $apiurl .= '/';
}

// 回调地址（使用当前域名）
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? '';
$base_url = $protocol . $host;
$notify_url = $base_url . '/modules/payment/notify.php';
$return_url = $base_url . '/modules/payment/return.php';

$out_trade_no = $order_no;
$sign_type = "MD5";
$param = $order_no;

// 构建参数数组
$arr = array(
    "pid" => $pid,
    "type" => $type,
    "notify_url" => $notify_url,
    "return_url" => $return_url,
    "out_trade_no" => $out_trade_no,
    "name" => $name,
    "money" => $amount,
    "param" => $param,
    "sign_type" => $sign_type
);

// 生成签名
$sign = get_sign($arr, $key);

// 构建请求参数
$post_data = "pid=$pid&type=$type&notify_url=" . urlencode($notify_url) . "&return_url=" . urlencode($return_url) . "&out_trade_no=$out_trade_no&name=" . urlencode($name) . "&money=$amount&param=$param&sign_type=$sign_type&sign=$sign";

// 调用 MAPI 接口
$api_url_full = $apiurl . "mapi.php";
$result = getbody($api_url_full, $post_data, 'POST');

// 输出支付信息
header('Content-Type: application/json');
echo $result;
?>