<?php
$title = '等级管理';
include __DIR__ . '/head.php';
?>

<div class="p-6">
    <!-- 活动配置 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-6">
        <div class="p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <h2 class="text-lg font-semibold text-gray-800">活动配置</h2>
                    <p class="text-sm text-gray-500 mt-1">配置等级升级活动，活动期间可享受额外折扣</p>
                </div>
                <div class="flex items-center gap-3">
                    <label class="flex items-center cursor-pointer">
                        <input type="checkbox" id="vip_activity_switch" <?php echo ($conf['vip_activity_switch'] ?? '0') == '1' ? 'checked' : '' ?> class="sr-only peer" onchange="toggleActivity()">
                        <div class="relative w-11 h-6 bg-gray-200 rounded-full transition-colors peer-checked:bg-blue-600">
                            <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-5"></div>
                        </div>
                        <span class="ml-2 text-sm text-gray-600"><?php echo ($conf['vip_activity_switch'] ?? '0') == '1' ? '活动进行中' : '活动已关闭' ?></span>
                    </label>
                </div>
            </div>
        </div>
        <div class="p-6">
            <form id="activity_form" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">活动开始时间</label>
                        <input type="datetime-local" name="vip_activity_start" value="<?php echo $conf['vip_activity_start'] ?? '' ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">活动结束时间</label>
                        <input type="datetime-local" name="vip_activity_end" value="<?php echo $conf['vip_activity_end'] ?? '' ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">活动折扣 (%)</label>
                        <input type="number" name="vip_activity_discount" value="<?php echo $conf['vip_activity_discount'] ?? '100' ?>" min="1" max="100" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <p class="text-xs text-gray-500 mt-1">如80表示8折</p>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    <button type="button" onclick="saveActivity()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">
                        <i class="fas fa-save mr-2"></i>保存活动配置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 等级管理 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200">
        <div class="p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <h2 class="text-lg font-semibold text-gray-800">用户等级</h2>
                    <p class="text-sm text-gray-500 mt-1">管理用户等级和对应折扣</p>
                </div>
                <div class="flex items-center gap-3">
                    <button onclick="openAddModal()" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition">
                        <i class="fas fa-plus mr-2"></i>添加等级
                    </button>
                    <button onclick="openConfigModal()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">
                        <i class="fas fa-cog mr-2"></i>扩展配置
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 等级列表表格 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">等级名称</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">级别</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">折扣</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">等级售价</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">上级返利</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">用户返利</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">操作</th>
                    </tr>
                </thead>
                <tbody id="vip-list" class="bg-white divide-y divide-gray-200">
                    <!-- 由 JavaScript 动态渲染 -->
                </tbody>
            </table>
        </div>
        
        <!-- 折扣说明 -->
        <div class="p-6 bg-blue-50 border-t border-blue-100">
            <h4 class="text-sm font-semibold text-blue-800 mb-3">等级提成/返利逻辑说明</h4>
            
            <div class="overflow-x-auto">
                <table class="w-full text-xs text-left text-blue-700 border-collapse">
                    <thead>
                        <tr class="bg-blue-100/50">
                            <th class="p-2 border border-blue-200">模式</th>
                            <th class="p-2 border border-blue-200">开启差价升级</th>
                            <th class="p-2 border border-blue-200">计算基础</th>
                            <th class="p-2 border border-blue-200">提成发放金额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="p-2 border border-blue-200">固定金额</td>
                            <td class="p-2 border border-blue-200">否（全款）</td>
                            <td class="p-2 border border-blue-200">等级设置</td>
                            <td class="p-2 border border-blue-200">全额发放</td>
                        </tr>
                        <tr>
                            <td class="p-2 border border-blue-200">固定金额</td>
                            <td class="p-2 border border-blue-200">是（补差价）</td>
                            <td class="p-2 border border-blue-200">等级设置</td>
                            <td class="p-2 border border-blue-200">目标等级返现 - 当前等级返现</td>
                        </tr>
                        <tr>
                            <td class="p-2 border border-blue-200">百分比</td>
                            <td class="p-2 border border-blue-200">否（全款）</td>
                            <td class="p-2 border border-blue-200">实际支付</td>
                            <td class="p-2 border border-blue-200">支付总额 × 比例</td>
                        </tr>
                        <tr>
                            <td class="p-2 border border-blue-200">百分比</td>
                            <td class="p-2 border border-blue-200">是（补差价）</td>
                            <td class="p-2 border border-blue-200">实际支付</td>
                            <td class="p-2 border border-blue-200">实际支付差价 × 比例</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑模态框 -->
<div id="vip-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col overflow-hidden">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between shrink-0">
            <h3 id="modal-title" class="text-lg font-semibold">添加等级</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <form onsubmit="saveVip(this);return false;" class="flex-1 flex flex-col overflow-hidden">
            <div class="flex-1 overflow-y-auto px-4 py-3 space-y-3">
            <input type="hidden" name="id" id="vip-id" value="0">
            <input type="hidden" name="act" id="vip-act" value="add">
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">等级名称</label>
                <input type="text" name="name" id="vip-name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="如：普通会员、黄金会员" required>
            </div>
            
            <div id="vip-level-row" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-1">级别</label>
                <input type="number" id="vip-level" class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50" disabled>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">折扣比例 (%)</label>
                <input type="number" name="discount" id="vip-discount" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="如80表示8折" min="1" max="100" required>
                <p class="text-xs text-gray-500 mt-1">输入1-100的整数，80表示8折购买</p>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">等级售价 (元)</label>
                <input type="number" name="price" id="vip-price" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="用户购买此等级的价格" step="0.01" required>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">返利类型</label>
                <select name="fanli_type" id="vip-fanli-type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" onchange="updateFanliLabel()">
                    <option value="0">百分比 (%)</option>
                    <option value="1">固定值 (元)</option>
                </select>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" id="daili-label">上级返利 (%)</label>
                    <input type="number" name="daili_fanli_rmb" id="vip-daili" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="0不返利" min="0" step="0.01">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" id="user-label">用户返利 (%)</label>
                    <input type="number" name="user_fanli_rmb" id="vip-user" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="0不返利" min="0" step="0.01">
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">等级描述</label>
                <textarea name="desc" id="vip-desc" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入等级描述（选填）"></textarea>
            </div>
            </div>
            <div class="flex justify-end gap-3 pt-3 pb-3 border-t border-gray-200 shrink-0 px-4">
                <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition">取消</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 扩展配置模态框 -->
<div id="config-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col overflow-hidden">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between shrink-0">
            <h3 class="text-lg font-semibold">扩展配置</h3>
            <button onclick="closeConfigModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <form onsubmit="saveConfig(this);return false;" class="flex-1 flex flex-col overflow-hidden">
            <div class="flex-1 overflow-y-auto px-4 py-2 space-y-3">
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">等级佣金存入</label>
                <select name="agent_commission" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="0" <?php echo ($conf['agent_commission'] ?? 0) == 0 ? 'selected' : ''; ?>>佣金账户</option>
                    <option value="1" <?php echo ($conf['agent_commission'] ?? 0) == 1 ? 'selected' : ''; ?>>余额账户</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">初始用户等级</label>
                <input type="number" name="user_vip" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" value="<?php echo $conf['user_vip'] ?? 1; ?>" min="1">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">用户修改下级等级</label>
                <select name="user_vip_edit" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="0" <?php echo ($conf['user_vip_edit'] ?? 0) == 0 ? 'selected' : ''; ?>>不允许</option>
                    <option value="1" <?php echo ($conf['user_vip_edit'] ?? 0) == 1 ? 'selected' : ''; ?>>允许</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">补差价开通等级</label>
                <select name="user_vip_cj" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="0" <?php echo ($conf['user_vip_cj'] ?? 0) == 0 ? 'selected' : ''; ?>>关闭</option>
                    <option value="1" <?php echo ($conf['user_vip_cj'] ?? 0) == 1 ? 'selected' : ''; ?>>开启</option>
                </select>
            </div>
            </div>
            <div class="flex justify-end gap-3 pt-3 pb-3 border-t border-gray-200 shrink-0 px-4">
                <button type="button" onclick="closeConfigModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition">取消</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">保存</button>
            </div>
        </form>
    </div>
</div>

<?php include 'foot.php'; ?>

<script>
$(document).ready(function() {
    loadVipList();
});

function toggleActivity() {
    var checked = $('#vip_activity_switch').is(':checked') ? '1' : '0';
    $.ajax({
        type: 'POST',
        url: 'ajax_vip.php?act=set',
        data: { vip_activity_switch: checked },
        dataType: 'json',
        success: function(data) {
            if (data.code == 1) {
                showToast(checked == '1' ? '活动已开启' : '活动已关闭', 'success');
                location.reload();
            } else {
                showToast(data.msg || '操作失败', 'error');
            }
        },
        error: function() {
            showToast('服务器错误', 'error');
        }
    });
}

function saveActivity() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_vip.php?act=set',
        data: $('#activity_form').serialize(),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showToast(data.msg, data.code == 1 ? 'success' : 'error');
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function loadVipList() {
    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax_vip.php?act=list',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            renderVipList(data.rows || data);
        },
        error: function() {
            hideLoading();
            showToast('加载失败', 'error');
        }
    });
}

function renderVipList(list) {
    var html = '';
    $.each(list, function(i, v) {
        var discount = v.discount || (100 - (v.vip - 1) * 20);
        var fanliUnit = v.fanli_type == 1 ? '元' : '%';
        var dailiText = v.daili_fanli_rmb > 0 ? '<span class="text-blue-600">' + v.daili_fanli_rmb + fanliUnit + '</span>' : '<span class="text-gray-400">不返利</span>';
        var userText = v.user_fanli_rmb > 0 ? '<span class="text-blue-600">' + v.user_fanli_rmb + fanliUnit + '</span>' : '<span class="text-gray-400">不返利</span>';
        
        html += `<tr class="hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm font-medium text-gray-900">${v.name}</span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800">
                    VIP${v.vip}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                    ${discount}%
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                ${v.price} 元
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${dailiText}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${userText}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <div class="flex items-center justify-end space-x-3">
                    <button onclick='editVip(${JSON.stringify(v)})' class="text-indigo-600 hover:text-indigo-900 bg-indigo-50 hover:bg-indigo-100 px-3 py-1 rounded-md transition-colors">
                        <i class="fas fa-edit mr-1"></i>编辑
                    </button>
                    ${v.vip > 5 && v.delete == 1 ? `
                    <button onclick="delVip(${v.id}, ${v.vip})" class="text-red-600 hover:text-red-900 bg-red-50 hover:bg-red-100 px-3 py-1 rounded-md transition-colors">
                        <i class="fas fa-trash-alt mr-1"></i>删除
                    </button>` : ''}
                </div>
            </td>
        </tr>`;
    });
    $('#vip-list').html(html);
}

function updateFanliLabel() {
    var type = $('#vip-fanli-type').val();
    var unit = type == 1 ? '(元)' : '(%)';
    $('#daili-label').text('上级返利 ' + unit);
    $('#user-label').text('用户返利 ' + unit);
}

function openAddModal() {
    $('#modal-title').text('添加等级');
    $('#vip-id').val(0);
    $('#vip-act').val('add');
    $('#vip-name').val('');
    $('#vip-discount').val('');
    $('#vip-price').val('');
    $('#vip-fanli-type').val(0);
    $('#vip-daili').val('');
    $('#vip-user').val('');
    $('#vip-desc').val('');
    $('#vip-level-row').hide();
    updateFanliLabel();
    $('#vip-modal').removeClass('hidden').addClass('flex');
}

function editVip(row) {
    $('#modal-title').text('编辑等级');
    $('#vip-id').val(row.id);
    $('#vip-act').val('edit');
    $('#vip-name').val(row.name);
    $('#vip-level').val(row.vip);
    $('#vip-discount').val(row.discount || (100 - (row.vip - 1) * 20));
    $('#vip-price').val(row.price);
    $('#vip-fanli-type').val(row.fanli_type || 0);
    $('#vip-daili').val(row.daili_fanli_rmb);
    $('#vip-user').val(row.user_fanli_rmb);
    $('#vip-desc').val(row.desc);
    $('#vip-level-row').show();
    updateFanliLabel();
    $('#vip-modal').removeClass('hidden').addClass('flex');
}

function closeModal() {
    $('#vip-modal').removeClass('flex').addClass('hidden');
}

function saveVip(form) {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_vip.php?act=add',
        data: $(form).serialize(),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showToast(data.msg, data.code == 1 ? 'success' : 'error');
            if (data.code == 1) {
                closeModal();
                loadVipList();
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}

function delVip(id, vip) {
    if (confirm('删除后该等级用户会降为VIP' + (vip - 1) + '，确定删除吗？')) {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax_vip.php?act=edit',
            data: {type: 'del', id: id},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
                if (data.code == 1) {
                    loadVipList();
                }
            }
        });
    }
}

function openConfigModal() {
    $('#config-modal').removeClass('hidden').addClass('flex');
}

function closeConfigModal() {
    $('#config-modal').removeClass('flex').addClass('hidden');
}

function saveConfig(form) {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_vip.php?act=set',
        data: $(form).serialize(),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showToast(data.msg, data.code == 1 ? 'success' : 'error');
            if (data.code == 1) {
                closeConfigModal();
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
        }
    });
}
</script>
