<?php
@header('Content-Type: text/html; charset=UTF-8');
require_once __DIR__ . '/../MPHX/common.php';

$user = is_user_login();
if (!$user) {
    header('Location: /user/login.php');
    exit;
}

// 获取用户余额
$balance = 0;
$user_info = $DB->get_row("SELECT * FROM `zj` WHERE `id`='{$user['id']}'");
if ($user_info && isset($user_info['balance'])) {
    $balance = floatval($user_info['balance']);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo L('title', 'payment'); ?></title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
    /* 确保整个页面所有元素始终可见 */
    html, body, div, span, button, input, label, table, thead, tbody, tr, td, th {
        opacity: 1 !important;
        visibility: visible !important;
    }

    /* 确保所有内容始终可见，不受hover影响 */
    .amount-option, .payment-method, .btn {
        opacity: 1 !important;
        visibility: visible !important;
    }
    
    /* 确保选中状态的按钮始终可见且有正确的背景色 */
    .amount-option.selected, .payment-method.selected {
        background-color: #188038 !important;
        color: #fff !important;
        border-color: #188038 !important;
    }
    
    /* 确保未选中状态的按钮可见 */
    .amount-option.btn-outline-primary, .payment-method.btn-outline-primary {
        opacity: 1 !important;
        visibility: visible !important;
        background-color: transparent !important;
        color: #188038 !important;
        border-color: #188038 !important;
    }
    
    .amount-option.btn-outline-success, .payment-method.btn-outline-success {
        opacity: 1 !important;
        visibility: visible !important;
        background-color: transparent !important;
        color: #1a73e8 !important;
        border-color: #1a73e8 !important;
    }
    
    /* 确保按钮交互正常 */
    .amount-option, .payment-method {
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .amount-option:hover, .payment-method:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    /* 确保表单元素可见 */
    .form-control {
        opacity: 1 !important;
        visibility: visible !important;
    }
    /* 确保卡片标题可见 */
    .card-title {
        opacity: 1 !important;
        visibility: visible !important;
    }
    /* 确保表格内容始终可见 */
    .table, .table td, .table th {
        opacity: 1 !important;
        visibility: visible !important;
    }
    /* 修复表格hover效果 */
    .table tbody tr {
        opacity: 1 !important;
    }
    </style>
</head>
<body style="background-color: #f5f7fa; padding: 20px;">

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><i class="fas fa-wallet mr-2"></i><?php echo L('recharge', 'order'); ?></h3>
    </div>
    <div class="card-body">
        <!-- 余额显示 -->
        <div class="alert alert-info d-flex align-items-center mb-4">
            <i class="fas fa-info-circle mr-2"></i>
            <div><?php echo L('current_balance', 'payment'); ?>: <strong class="text-danger" id="currentBalance">¥<?php echo number_format($balance, 2); ?></strong> <?php echo L('yuan', 'payment'); ?></div>
        </div>

        <!-- 充值表单 -->
        <div class="form-group">
            <label class="font-weight-bold">选择充值金额</label>
            <div class="d-flex flex-wrap mb-3">
                <div class="amount-option btn btn-outline-primary mr-2 mb-2" data-amount="10" onclick="selectAmount(this, 10)">10元</div>
                <div class="amount-option btn btn-outline-primary mr-2 mb-2" data-amount="30" onclick="selectAmount(this, 30)">30元</div>
                <div class="amount-option btn btn-outline-primary mr-2 mb-2 selected" data-amount="50" onclick="selectAmount(this, 50)">50元</div>
                <div class="amount-option btn btn-outline-primary mr-2 mb-2" data-amount="100" onclick="selectAmount(this, 100)">100元</div>
            </div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">自定义金额</label>
            <input type="number" class="form-control" id="customAmount" placeholder="请输入充值金额（1-10000）" min="1" max="10000" style="max-width: 300px;" oninput="onCustomAmountInput()">
        </div>

        <div class="form-group">
            <label class="font-weight-bold">选择支付方式</label>
            <div class="d-flex flex-wrap">
                <?php 
                $pay_alipay_enabled = !isset($conf['pay_alipay']) || $conf['pay_alipay'] !== 'false';
                $pay_wechat_enabled = !isset($conf['pay_wechat']) || $conf['pay_wechat'] !== 'false';
                $first_method = '';
                ?>
                <?php if($pay_alipay_enabled): ?>
                <div class="payment-method btn btn-outline-primary mr-2 mb-2 <?php if(!$pay_wechat_enabled || empty($first_method)) { echo 'selected'; $first_method = 'alipay'; } ?>" data-method="alipay" onclick="selectPaymentMethod(this, 'alipay')">
                    <i class="fab fa-alipay mr-1"></i> 支付宝
                </div>
                <?php endif; ?>
                <?php if($pay_wechat_enabled): ?>
                <div class="payment-method btn btn-outline-success mr-2 mb-2 <?php if(empty($first_method)) { echo 'selected'; $first_method = 'wechat'; } ?>" data-method="wechat" onclick="selectPaymentMethod(this, 'wechat')">
                    <i class="fab fa-weixin mr-1"></i> 微信支付
                </div>
                <?php endif; ?>
                <?php if(!$pay_alipay_enabled && !$pay_wechat_enabled): ?>
                <div class="alert alert-warning mb-0">
                    <i class="fas fa-exclamation-triangle mr-1"></i> 暂无可用支付方式，请联系管理员
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="form-group mt-4">
            <button type="button" class="btn btn-primary" onclick="submitRecharge()">
                <i class="fas fa-paper-plane mr-1"></i> 立即充值
            </button>
        </div>
    </div>
</div>

<!-- 充值记录 -->
<div class="card mt-4">
    <div class="card-header">
        <h3 class="card-title mb-0"><i class="fas fa-history mr-2"></i>充值记录</h3>
    </div>
    <div class="card-body">
        <div id="historyList">
            <p class="text-muted">加载中...</p>
        </div>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script src="https://lib.baomitu.com/layer/3.5.1/layer.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script>
var selectedAmount = 50;
var selectedMethod = '<?php echo $first_method; ?>';

// 选择充值金额
function selectAmount(btn, amount) {
    $('.amount-option').removeClass('selected btn-primary').addClass('btn-outline-primary');
    $(btn).removeClass('btn-outline-primary').addClass('selected btn-primary');
    
    // 确保所有按钮可见
    $('.amount-option').css({
        'opacity': '1',
        'visibility': 'visible'
    });
    
    selectedAmount = amount;
    $('#customAmount').val('');
}

// 自定义金额输入
function onCustomAmountInput() {
    var val = parseFloat($('#customAmount').val());
    if (val > 0) {
        $('.amount-option').removeClass('selected btn-primary').addClass('btn-outline-primary');
        selectedAmount = val;
    }
}

// 选择支付方式
function selectPaymentMethod(btn, method) {
    $('.payment-method').removeClass('selected btn-primary btn-success').addClass('btn-outline-primary');
    
    // 根据支付方式设置正确的样式
    if (method === 'wechat') {
        $(btn).removeClass('btn-outline-primary').addClass('selected btn-success');
    } else {
        $(btn).removeClass('btn-outline-primary btn-success').addClass('selected btn-primary');
    }
    
    // 确保所有按钮可见
    $('.payment-method').css({
        'opacity': '1',
        'visibility': 'visible'
    });
    
    selectedMethod = method;
}

// 提交充值
function submitRecharge() {
    var amount = selectedAmount;
    
    // 获取自定义金额
    var customAmount = parseFloat($('#customAmount').val());
    if (customAmount > 0) {
        amount = customAmount;
    }
    
    // 验证金额
    if (!amount || amount <= 0) {
        layer.msg('请选择或输入充值金额');
        return;
    }
    
    if (amount > 10000) {
        layer.msg('单次充值金额不能超过10000元');
        return;
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    
    // 提交充值请求
    $.ajax({
        type: 'POST',
        url: 'api/api_router.php',
        data: {
            action: 'recharge',
            amount: amount,
            payment_method: selectedMethod
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            console.log('充值API返回:', res);
            if (res.status === true || res.code === 'success') {
                // 获取返回数据（在res.data中）
                var data = res.data || {};
                // 如果返回了支付表单
                if (data.pay_url) {
                    console.log('支付表单HTML:', data.pay_url);
                    
                    // 提取表单action
                    var tempDiv = document.createElement('div');
                    tempDiv.innerHTML = data.pay_url;
                    var form = tempDiv.querySelector('form');
                    
                    if (form) {
                        var formAction = form.getAttribute('action') || '';
                        console.log('表单action:', formAction);
                        
                        // 检查是否是混合内容（当前HTTPS但表单是HTTP）
                        if (window.location.protocol === 'https:' && formAction.indexOf('http:') === 0) {
                            // 混合内容问题：使用新窗口打开支付页面
                            console.log('检测到混合内容，使用新窗口打开');
                            
                            // 创建支付页面内容
                            var payHtml = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>正在跳转支付...</title></head><body style="text-align:center;padding-top:50px;">';
                            payHtml += '<h3>正在跳转支付页面...</h3>';
                            payHtml += '<p>如果页面没有自动跳转，请<button onclick="document.forms[0].submit()">点击这里</button></p>';
                            payHtml += data.pay_url;
                            payHtml += '</body></html>';
                            
                            // 打开新窗口
                            var payWindow = window.open('', '_blank');
                            if (payWindow) {
                                payWindow.document.write(payHtml);
                                payWindow.document.close();
                                layer.msg('支付页面已在新窗口打开，请完成支付');
                            } else {
                                // 弹窗被阻止，显示提示
                                layer.confirm('支付页面准备就绪，点击确定前往支付', {
                                    btn: ['前往支付', '取消']
                                }, function(index) {
                                    layer.close(index);
                                    var payWindow = window.open('about:blank', '_blank');
                                    payWindow.document.write(payHtml);
                                    payWindow.document.close();
                                });
                            }
                        } else {
                            // 非混合内容，直接在当前页面提交
                            console.log('非混合内容，直接提交');
                            tempDiv.style.display = 'none';
                            document.body.appendChild(tempDiv);
                            form.submit();
                        }
                    } else {
                        layer.msg('支付表单生成失败，请重试');
                    }
                } else {
                    layer.msg('充值请求已提交，请完成支付');
                }
                loadRechargeHistory();
            } else {
                layer.msg(res.msg || '充值失败，请重试');
            }
        },
        error: function(xhr) {
            layer.close(ii);
            layer.msg('网络错误：' + (xhr.statusText || '请重试'));
        }
    });
}

// 加载充值记录（只显示最新3条）
function loadRechargeHistory() {
    $.ajax({
        type: 'POST',
        url: 'api/api_router.php',
        data: {
            action: 'get_history',
            page: 1,
            page_size: 3
        },
        dataType: 'json',
        success: function(res) {
            if (res.status === true || res.code === 'success') {
                // res.data 包含 list 数组和 balance
                var list = res.data && res.data.list ? res.data.list : [];
                renderRechargeHistory(list);
                // 刷新余额显示
                if (res.data && res.data.balance !== undefined) {
                    $('#currentBalance').text('¥' + parseFloat(res.data.balance).toFixed(2));
                }
            } else {
                $('#historyList').html('<p class="text-muted">加载失败</p>');
            }
        },
        error: function() {
            $('#historyList').html('<p class="text-muted">加载失败</p>');
        }
    });
}

// 渲染充值记录
function renderRechargeHistory(data) {
    if (!data || data.length === 0) {
        $('#historyList').html('<p class="text-muted">暂无充值记录</p>');
        return;
    }
    
    var html = '<div class="table-responsive"><table class="table table-striped">';
    html += '<thead><tr><th>订单号</th><th>金额</th><th>支付方式</th><th>状态</th><th>时间</th></tr></thead>';
    html += '<tbody>';
    
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var statusClass = item.status === 'paid' ? 'text-success' : (item.status === 'pending' ? 'text-warning' : 'text-danger');
        var statusText = item.status === 'paid' ? '已支付' : (item.status === 'pending' ? '待支付' : '已取消');
        var methodText = item.payment_method === 'alipay' ? '支付宝' : (item.payment_method === 'wechat' ? '微信支付' : item.payment_method);
        
        html += '<tr>';
        html += '<td>' + item.order_no + '</td>';
        html += '<td>¥' + parseFloat(item.amount).toFixed(2) + '</td>';
        html += '<td>' + methodText + '</td>';
        html += '<td class="' + statusClass + '">' + statusText + '</td>';
        html += '<td>' + item.create_time + '</td>';
        html += '</tr>';
    }
    
    html += '</tbody></table></div>';
    $('#historyList').html(html);
}

// 页面加载完成后加载充值记录
$(document).ready(function() {
    loadRechargeHistory();
    
    // 初始化选中状态的样式
    $('.amount-option.selected').removeClass('btn-outline-primary').addClass('btn-primary');
    $('.payment-method.selected').removeClass('btn-outline-primary').addClass('btn-primary');
});
</script>
</body>
</html>
