<?php
$title='升级代理';
include __DIR__ . '/head.php';

$current_vip = $userrow['vip'];
$vip_levels = $DB->query("SELECT * FROM pre_user_vip ORDER BY vip ASC")->fetchAll(PDO::FETCH_ASSOC);

// 当前等级信息（用于差价升级与固定返利差额展示）
$current_vip_info = null;
$current_vip_user_fanli = 0;
if(intval($conf['user_vip_cj'] ?? 0) == 1 && intval($current_vip) > 1) {
    $current_vip_info = $DB->getRow("SELECT * FROM pre_user_vip WHERE vip='{$current_vip}' LIMIT 1");
    if($current_vip_info) $current_vip_user_fanli = floatval($current_vip_info['user_fanli_rmb'] ?? 0);
}

// 活动配置
$activity_switch = ($conf['vip_activity_switch'] ?? '0') == '1';
$activity_start = $conf['vip_activity_start'] ?? '';
$activity_end = $conf['vip_activity_end'] ?? '';
$activity_discount = intval($conf['vip_activity_discount'] ?? 100);

// 检查活动是否有效
$activity_active = false;
$activity_discount_percent = 100;
if ($activity_switch && $activity_start && $activity_end) {
    $now = time();
    $start_time = strtotime($activity_start);
    $end_time = strtotime($activity_end);
    if ($now >= $start_time && $now <= $end_time) {
        $activity_active = true;
        $activity_discount_percent = $activity_discount;
    }
}

foreach($vip_levels as &$level) {
    if($level['vip'] > $current_vip) {
        if($current_vip_info) {
            $level['actual_price'] = floatval($level['price']) - floatval($current_vip_info['price']);
        } else {
            $level['actual_price'] = floatval($level['price']);
        }
        // 活动折扣价格（仅用于显示，不影响返利计算）
        if ($activity_active) {
            $level['activity_price'] = round($level['actual_price'] * $activity_discount_percent / 100, 2);
        } else {
            $level['activity_price'] = $level['actual_price'];
        }
        $fanli_type = intval($level['fanli_type'] ?? 0);
        $user_fanli_raw = floatval($level['user_fanli_rmb'] ?? 0);
        if($fanli_type == 1 && $current_vip_info) {
            $level['user_profit_display'] = max(0, $user_fanli_raw - $current_vip_user_fanli);
        } else {
            $level['user_profit_display'] = $user_fanli_raw;
        }
    } else {
        $level['actual_price'] = floatval($level['price']);
        $level['activity_price'] = $level['actual_price'];
    }
}
unset($level);

$current_vip_name = '';
$current_vip_discount = 100;
foreach($vip_levels as $lv) {
    if($lv['vip'] == $current_vip) {
        $current_vip_name = $lv['name'];
        $current_vip_discount = intval($lv['discount']);
        break;
    }
}
if($current_vip_name === '') $current_vip_name = '等级' . $current_vip;

// 计算下级返利说明
// 找到最低等级（VIP1）的折扣
$min_vip_discount = 100;
foreach($vip_levels as $lv) {
    if($lv['vip'] == 1) {
        $min_vip_discount = intval($lv['discount']);
        break;
    }
}
// 当前用户能获得的下级支付返利比例
// 提成 = 商品原价 × (下级折扣 - 当前折扣)
// 相对于下级支付金额的返利比例 = (下级折扣 - 当前折扣) / 下级折扣
$commission_rate = 0;
if($min_vip_discount > $current_vip_discount && $min_vip_discount > 0) {
    $commission_rate = round(($min_vip_discount - $current_vip_discount) / $min_vip_discount * 100, 1);
}

$category_name_map = [];
$rs = $DB->query("SELECT id, name FROM pre_login_class ORDER BY sort ASC");
if($rs !== false){
    while($res = $rs->fetch(PDO::FETCH_ASSOC)){
        $category_name_map[(string)$res['id']] = $res['name'];
    }
}
if(($conf['show_all_goods'] ?? 0) == 1){
    $category_name_map['9999'] = '全部接口';
}

$version_name_cloud = $conf['version_name_cloud'] ?? '云端版';
$version_name_dg = $conf['version_name_dg'] ?? '代挂版';
$version_name_qzone = $conf['version_name_qzone'] ?? '秒赞版';
$version_name_cloud_all = $conf['version_name_cloud_all'] ?? (preg_replace('/版$/u', '', $version_name_cloud) . '·秒赞');
$version_name_dg_all = $conf['version_name_dg_all'] ?? (preg_replace('/版$/u', '', $version_name_dg) . '·秒赞');
$version_name_tri_all = $conf['version_name_tri_all'] ?? '三版通用';
$category_name_map['qzone'] = $version_name_qzone;

$goods = $DB->query("SELECT * FROM pre_goods WHERE status=1 ORDER BY type ASC, sort ASC")->fetchAll(PDO::FETCH_ASSOC);
$normalize_goods_version = function($version) {
    $gv = strtolower(trim((string)$version));
    if($gv === '' || $gv === 'qzone') return 'qzone';
    if($gv === 'all') return 'cloud_all';
    if(in_array($gv, ['cloud','dg','cloud_all','dg_all','tri_all'], true)) return $gv;
    return 'cloud';
};
$qzone_goods_list = [];
$tri_all_category_name_map = [];
$goods_by_version_category = [];
foreach($goods as $g) {
    $gv = $normalize_goods_version($g['version'] ?? '');
    $type_raw = trim((string)($g['type'] ?? ''));
    if($gv === 'qzone' || strtolower($type_raw) === 'qzone') $qzone_goods_list[] = $g;

    $type = $type_raw;
    if($gv === 'qzone' && $type === '') $type = 'qzone';
    if($gv === 'tri_all') {
        $type_cloud = trim((string)($g['type_cloud'] ?? $type_raw));
        $type_dg = trim((string)($g['type_dg'] ?? '0'));
        if($type_cloud === '') continue;
        $type_dg_int = intval($type_dg);
        $pair_key = $type_dg_int > 0 ? ($type_cloud . ':' . $type_dg_int) : $type_cloud;
        if(!isset($tri_all_category_name_map[$pair_key])) {
            $cloud_name = $category_name_map[(string)$type_cloud] ?? (string)$type_cloud;
            if($type_dg_int > 0) {
                $dg_id = (string)$type_dg_int;
                $dg_name = $category_name_map[$dg_id] ?? $dg_id;
                $tri_all_category_name_map[$pair_key] = ((string)$type_cloud === '9999' && $dg_id === '9999') ? $cloud_name : ($cloud_name . ' + ' . $dg_name);
            } else {
                $tri_all_category_name_map[$pair_key] = $cloud_name;
            }
        }
        $type = $pair_key;
    }
    if($type === '') continue;
    if(!isset($goods_by_version_category[$gv])) $goods_by_version_category[$gv] = [];
    if(!isset($goods_by_version_category[$gv][$type])) $goods_by_version_category[$gv][$type] = [];
    $goods_by_version_category[$gv][$type][] = $g;
}

$version_goods_count = [
    'cloud' => 0,
    'dg' => 0,
    'qzone' => 0,
    'cloud_all' => 0,
    'dg_all' => 0,
    'tri_all' => 0
];
foreach($goods as $g) {
    $gv = $normalize_goods_version($g['version'] ?? '');
    if(isset($version_goods_count[$gv])) $version_goods_count[$gv]++;
}

$show_qzone = ($QZONE_ENABLED ?? false) && !empty($qzone_goods_list);
$show_cloud = ($CLOUD_ENABLED ?? false) && $version_goods_count['cloud'] > 0;
$show_dg = ($DG_ENABLED ?? false) && $version_goods_count['dg'] > 0;
$show_cloud_all = ($QZONE_ENABLED ?? false) && ($CLOUD_ENABLED ?? false) && $version_goods_count['cloud_all'] > 0;
$show_dg_all = ($QZONE_ENABLED ?? false) && ($DG_ENABLED ?? false) && $version_goods_count['dg_all'] > 0;
$show_tri_all = ($QZONE_ENABLED ?? false) && ($CLOUD_ENABLED ?? false) && ($DG_ENABLED ?? false) && $version_goods_count['tri_all'] > 0;
$price_table_versions = [];
if($show_cloud) $price_table_versions[] = ['key'=>'cloud','name'=>$version_name_cloud];
if($show_dg) $price_table_versions[] = ['key'=>'dg','name'=>$version_name_dg];
if($show_qzone) $price_table_versions[] = ['key'=>'qzone','name'=>$version_name_qzone];
if($show_cloud_all) $price_table_versions[] = ['key'=>'cloud_all','name'=>$version_name_cloud_all];
if($show_dg_all) $price_table_versions[] = ['key'=>'dg_all','name'=>$version_name_dg_all];
if($show_tri_all) $price_table_versions[] = ['key'=>'tri_all','name'=>$version_name_tri_all];

$req_version = isset($_GET['version']) ? daddslashes($_GET['version']) : '';
if(!in_array($req_version, ['cloud','dg','qzone','cloud_all','dg_all','tri_all'], true)) $req_version = '';
$default_price_version = $price_table_versions[0]['key'] ?? '';
if($req_version){
    foreach($price_table_versions as $pv){
        if($pv['key'] === $req_version){ $default_price_version = $req_version; break; }
    }
}

$price_table_categories = [];
foreach($price_table_versions as $pv){
    $ver = $pv['key'];
    $price_table_categories[$ver] = [];
    foreach(($goods_by_version_category[$ver] ?? []) as $type => $list){
        if(empty($list)) continue;
        $type_key = (string)$type;
        $display_name = '';
        if($ver === 'tri_all') {
            $display_name = $tri_all_category_name_map[$type_key] ?? '';
        } else {
            $display_name = $category_name_map[$type_key] ?? '';
        }
        if($display_name === '') continue;
        $price_table_categories[$ver][] = ['id'=>$type_key, 'name'=>$display_name];
    }
}
?>

<div class="space-y-3 lg:space-y-4 max-w-5xl mx-auto">
    <?php if ($activity_active): ?>
    <div class="bg-gradient-to-r from-red-500 to-orange-500 rounded-xl shadow-sm overflow-hidden">
        <div class="p-4 text-white">
            <div class="flex items-center gap-3">
                <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-gift text-2xl"></i>
                </div>
                <div class="flex-1">
                    <h3 class="font-bold text-lg">限时活动进行中！</h3>
                    <p class="text-white/90 text-sm mt-1">升级代理享 <span class="font-bold text-yellow-300"><?php echo $activity_discount_percent == 100 ? '无折扣' : ($activity_discount_percent / 10 . '折'); ?></span> 优惠</p>
                    <p class="text-white/70 text-xs mt-1">活动时间：<?php echo $activity_start; ?> 至 <?php echo $activity_end; ?></p>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="p-3 lg:p-4 bg-gradient-to-r from-indigo-500 to-purple-600">
            <h2 class="text-lg lg:text-xl font-bold text-white flex items-center">
                <i class="fas fa-crown mr-2 text-yellow-300"></i>
                代理升级介绍
            </h2>
        </div>
        <div class="p-3 lg:p-4">
            <div class="space-y-3">
                <p class="text-gray-700 leading-relaxed text-sm">升级到更高等级可以享受更多优惠和特权：</p>
                <ul class="space-y-1.5 text-gray-600 text-sm">
                    <li class="flex items-center"><i class="fas fa-check-circle text-green-500 mr-2"></i><span>享受更低的商品折扣价格</span></li>
                    <li class="flex items-center"><i class="fas fa-check-circle text-green-500 mr-2"></i><span>获得更高的上级返利比例</span></li>
                    <li class="flex items-center"><i class="fas fa-check-circle text-green-500 mr-2"></i><span>解锁更多高级功能</span></li>
                </ul>
                <div class="flex items-center p-2 lg:p-3 bg-indigo-50 rounded-lg border border-indigo-100">
                    <i class="fas fa-user-tag text-indigo-600 mr-2"></i>
                    <p class="text-gray-700 font-medium text-sm">当前等级：<span class="font-bold text-indigo-600"><?php echo htmlspecialchars($current_vip_name); ?></span>（折扣 <span class="font-bold text-green-600"><?php echo $current_vip_discount; ?>%</span>）</p>
                </div>
                <?php if($commission_rate > 0): ?>
                <div class="flex items-center p-2 lg:p-3 bg-green-50 rounded-lg border border-green-100">
                    <i class="fas fa-coins text-green-600 mr-2"></i>
                    <p class="text-gray-700 text-sm">当前折扣 <span class="font-bold text-green-600"><?php echo $current_vip_discount; ?>%</span>，您将获得普通下级支付金额的 <span class="font-bold text-green-600"><?php echo $commission_rate; ?>%</span> 返利</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800 flex items-center">
                <i class="fas fa-arrow-up mr-1.5 text-indigo-500"></i>
                升级选项
            </h3>
        </div>
        <div class="p-3 lg:p-4">
            <?php
            $has_higher_level = false;
            foreach($vip_levels as $level) {
                if($level['vip'] > $current_vip) {
                    $has_higher_level = true;
                    break;
                }
            }
            ?>
            <?php if($has_higher_level): ?>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">选择要升级的等级</label>
                    <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" id="vip-select">
                        <?php foreach($vip_levels as $level): ?>
                            <?php if($level['vip'] > $current_vip): ?>
                                <option value="<?php echo $level['id']; ?>"
                                        data-name="<?php echo htmlspecialchars($level['name']); ?>"><?php echo $level['name']; ?></option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>

                    <div id="vip-detail" class="mt-4 p-3 lg:p-4 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg border border-indigo-100">
                        <div class="grid grid-cols-2 gap-2 text-sm">
                            <?php
                            $first_higher_level = null;
                            foreach($vip_levels as $level) {
                                if($level['vip'] > $current_vip) {
                                    $first_higher_level = $level;
                                    break;
                                }
                            }
                            ?>
                            <div class="flex items-center p-2 bg-white rounded-lg">
                                <i class="fas fa-star text-yellow-400 mr-2"></i>
                                <span class="text-gray-600">等级：<span class="font-bold text-gray-800 ml-1" id="detail-vip"><?php echo htmlspecialchars($first_higher_level['name']); ?></span></span>
                            </div>
                            <div class="flex items-center p-2 bg-white rounded-lg">
                                <i class="fas fa-percentage text-green-500 mr-2"></i>
                                <span class="text-gray-600">折扣：<span class="font-bold text-gray-800 ml-1" id="detail-discount"><?php echo $first_higher_level['discount']; ?>%</span></span>
                            </div>
                            <div class="col-span-2 flex items-center p-2 bg-white rounded-lg">
                                <i class="fas fa-tag text-indigo-600 mr-2"></i>
                                <span class="text-gray-600">升级价格：<span class="font-bold text-indigo-600 ml-1" id="detail-price">¥<?php echo $first_higher_level['actual_price']; ?></span></span>
                            </div>
                            <div class="col-span-2 flex items-center p-2 bg-white rounded-lg">
                                <i class="fas fa-gift text-red-500 mr-2"></i>
                                <span class="text-gray-600"><span id="detail-gift-label">赠送<?php echo isset($conf['agent_commission']) && intval($conf['agent_commission']) == 1 ? '余额' : '佣金'; ?>：</span><span class="font-bold text-green-600 ml-1" id="detail-user">¥0</span></span>
                            </div>
                            <div class="col-span-2 p-2 bg-white rounded-lg">
                                <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                                <span class="text-gray-600 text-xs" id="detail-desc"><?php echo htmlspecialchars($first_higher_level['desc'] ?? ''); ?></span>
                            </div>
                        </div>
                        <button type="button" id="upgrade-btn" class="w-full mt-4 py-2 bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white rounded-lg font-medium transition-colors text-sm">
                            <i class="fas fa-rocket mr-1"></i>
                            立即升级
                        </button>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200">
                    <i class="fas fa-trophy text-3xl mb-2 text-yellow-500"></i>
                    <h3 class="text-lg font-bold text-gray-800 mb-1">恭喜您！</h3>
                    <p class="text-gray-600">您已经是最高等级了！</p>
                    <p class="text-gray-500 text-xs mt-1">享受专属特权，继续为您的业务助力</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-4 py-3 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800 flex items-center">
                <i class="fas fa-box mr-1.5 text-indigo-500"></i>
                商品价格表
            </h3>
        </div>
        <div class="p-3 lg:p-4">
            <?php if(!empty($price_table_versions)): ?>
                <div>
                    <?php if(count($price_table_versions) > 1): ?>
                    <label class="block text-sm font-medium text-gray-700 mb-2">产品版本</label>
                    <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm mb-4" id="price-version-select">
                        <?php foreach($price_table_versions as $pv): ?>
                            <option value="<?php echo htmlspecialchars($pv['key']); ?>" <?php echo $pv['key'] === $default_price_version ? 'selected' : ''; ?>><?php echo htmlspecialchars($pv['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php else: ?>
                    <input type="hidden" id="price-version-select" value="<?php echo htmlspecialchars($default_price_version); ?>">
                    <?php endif; ?>

                    <div id="category-select-wrapper">
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择商品分类</label>
                        <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm mb-4" id="category-select"></select>
                    </div>

                    <div id="goods-table-container">
                        <?php
                        $has_any_table = !empty($qzone_goods_list);
                        if(!$has_any_table){
                            foreach($price_table_versions as $pv){
                                $ver = $pv['key'];
                                if($ver === 'qzone') continue;
                                foreach(($price_table_categories[$ver] ?? []) as $cat){
                                    $cid = (string)$cat['id'];
                                    if(isset($goods_by_version_category[$ver][$cid]) && !empty($goods_by_version_category[$ver][$cid])) { $has_any_table = true; break 2; }
                                }
                            }
                        }
                        ?>
                        <?php if(!$has_any_table): ?>
                            <div class="text-center py-6 bg-gray-50 rounded-lg border border-gray-200">
                                <i class="fas fa-box text-2xl mb-2 text-gray-300"></i>
                                <p class="text-gray-500 text-sm">暂无商品数据</p>
                            </div>
                        <?php else: ?>
                            <?php
                            $default_first_cat = '';
                            if($default_price_version && !empty($price_table_categories[$default_price_version])) {
                                $default_first_cat = (string)$price_table_categories[$default_price_version][0]['id'];
                            }
                            ?>
                            <?php if(!empty($qzone_goods_list)): ?>
                                <div class="goods-table" data-version="qzone" <?php echo $default_price_version !== 'qzone' ? 'style="display:none;"' : ''; ?>>
                                    <h4 class="font-medium text-gray-800 mb-3 pb-2 border-b border-gray-200 flex items-center text-sm">
                                        <i class="fas fa-list-ul text-indigo-500 mr-1.5"></i>
                                        <?php echo htmlspecialchars($version_name_qzone); ?>
                                    </h4>
                                    <div class="overflow-x-auto rounded-lg border border-gray-100">
                                        <table class="w-full text-xs min-w-[500px] bg-white">
                                            <thead>
                                                <tr class="bg-gray-50 text-gray-700">
                                                    <th class="px-3 py-2 text-left whitespace-nowrap font-medium">商品名称</th>
                                                    <th class="px-3 py-2 text-left whitespace-nowrap font-medium">时长</th>
                                                    <?php foreach($vip_levels as $level): ?>
                                                        <th class="px-3 py-2 text-left whitespace-nowrap font-medium"><?php echo htmlspecialchars($level['name']); ?></th>
                                                    <?php endforeach; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach($qzone_goods_list as $g): ?>
                                                        <?php
                                                        $time_type_map = [0 => '月', 1 => '天', 2 => '小时', 3 => '年'];
                                                        $time_type = isset($g['time_type']) ? intval($g['time_type']) : 0;
                                                        $time_unit = isset($time_type_map[$time_type]) ? $time_type_map[$time_type] : '月';
                                                        $time_num = isset($g['num']) ? intval($g['num']) : 1;
                                                        $time_text = $time_num . $time_unit;

                                                        if($time_type == 0 && $time_num > 60) {
                                                            $time_text = '无期';
                                                        }

                                                        if($time_num == 0) {
                                                            $time_text = '未知';
                                                        }

                                                        $price = isset($g['price']) ? floatval($g['price']) : 0;
                                                        $is_fixed_price = isset($g['is_fixed_price']) ? intval($g['is_fixed_price']) : 0;
                                                        $fixed_prices = [];
                                                        if($is_fixed_price == 1 && !empty($g['fixed_prices'])) {
                                                            $fixed_prices = json_decode($g['fixed_prices'], true);
                                                            if(!is_array($fixed_prices)) $fixed_prices = [];
                                                        }
                                                        ?>
                                                        <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                                                            <td class="px-3 py-2 text-gray-800 whitespace-nowrap font-medium">
                                                                <div class="flex items-center">
                                                                    <i class="fas fa-shopping-cart text-indigo-500 mr-2 text-xs"></i>
                                                                    <?php echo $g['name']; ?>
                                                                </div>
                                                            </td>
                                                            <td class="px-3 py-2 text-gray-600 whitespace-nowrap">
                                                                <span class="px-1.5 py-0.5 bg-green-50 text-green-700 rounded text-xs font-medium">
                                                                    <?php echo $time_text; ?>
                                                                </span>
                                                            </td>
                                                            <?php foreach($vip_levels as $level): ?>
                                                                <?php
                                                                if($is_fixed_price == 1 && isset($fixed_prices[$level['vip']])) {
                                                                    $display_price = floatval($fixed_prices[$level['vip']]);
                                                                } else {
                                                                    $display_price = $price * $level['discount'] / 100;
                                                                }
                                                                ?>
                                                                <td class="px-3 py-2 text-indigo-600 font-medium whitespace-nowrap">
                                                                    <div class="flex items-center">
                                                                        <i class="fas fa-tag text-yellow-400 mr-1 text-xs"></i>
                                                                        ¥<?php echo number_format($display_price, 2); ?>
                                                                    </div>
                                                                </td>
                                                            <?php endforeach; ?>
                                                        </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php foreach($price_table_versions as $pv): ?>
                                <?php $ver = $pv['key']; ?>
                                <?php if($ver === 'qzone') continue; ?>
                                <?php foreach(($price_table_categories[$ver] ?? []) as $cat): ?>
                                    <?php $cid = (string)$cat['id']; ?>
                                    <?php if(isset($goods_by_version_category[$ver][$cid]) && !empty($goods_by_version_category[$ver][$cid])): ?>
                                        <div class="goods-table" data-version="<?php echo htmlspecialchars($ver); ?>" data-category="<?php echo htmlspecialchars($cid); ?>" <?php echo ($ver !== $default_price_version || $cid !== $default_first_cat) ? 'style="display:none;"' : ''; ?>>
                                            <h4 class="font-medium text-gray-800 mb-3 pb-2 border-b border-gray-200 flex items-center text-sm">
                                                <i class="fas fa-list-ul text-indigo-500 mr-1.5"></i>
                                                <?php echo htmlspecialchars($cat['name']); ?>
                                            </h4>
                                            <div class="overflow-x-auto rounded-lg border border-gray-100">
                                                <table class="w-full text-xs min-w-[500px] bg-white">
                                                    <thead>
                                                        <tr class="bg-gray-50 text-gray-700">
                                                            <th class="px-3 py-2 text-left whitespace-nowrap font-medium">商品名称</th>
                                                            <th class="px-3 py-2 text-left whitespace-nowrap font-medium">时长</th>
                                                            <?php foreach($vip_levels as $level): ?>
                                                                <th class="px-3 py-2 text-left whitespace-nowrap font-medium"><?php echo htmlspecialchars($level['name']); ?></th>
                                                            <?php endforeach; ?>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach($goods_by_version_category[$ver][$cid] as $g): ?>
                                                            <?php
                                                                $time_type_map = [0 => '月', 1 => '天', 2 => '小时', 3 => '年'];
                                                                $time_type = isset($g['time_type']) ? intval($g['time_type']) : 0;
                                                                $time_unit = isset($time_type_map[$time_type]) ? $time_type_map[$time_type] : '月';
                                                                $time_num = isset($g['num']) ? intval($g['num']) : 1;
                                                                $time_text = $time_num . $time_unit;

                                                                if($time_type == 0 && $time_num > 60) {
                                                                    $time_text = '无期';
                                                                }

                                                                if($time_num == 0) {
                                                                    $time_text = '未知';
                                                                }

                                                                $price = isset($g['price']) ? floatval($g['price']) : 0;
                                                                $is_fixed_price = isset($g['is_fixed_price']) ? intval($g['is_fixed_price']) : 0;
                                                                $fixed_prices = [];
                                                                if($is_fixed_price == 1 && !empty($g['fixed_prices'])) {
                                                                    $fixed_prices = json_decode($g['fixed_prices'], true);
                                                                    if(!is_array($fixed_prices)) $fixed_prices = [];
                                                                }
                                                            ?>
                                                            <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                                                                <td class="px-3 py-2 text-gray-800 whitespace-nowrap font-medium">
                                                                    <div class="flex items-center">
                                                                        <i class="fas fa-shopping-cart text-indigo-500 mr-2 text-xs"></i>
                                                                        <?php echo $g['name']; ?>
                                                                    </div>
                                                                </td>
                                                                <td class="px-3 py-2 text-gray-600 whitespace-nowrap">
                                                                    <span class="px-1.5 py-0.5 bg-green-50 text-green-700 rounded text-xs font-medium">
                                                                        <?php echo $time_text; ?>
                                                                    </span>
                                                                </td>
                                                                <?php foreach($vip_levels as $level): ?>
                                                                    <?php
                                                                        if($is_fixed_price == 1 && isset($fixed_prices[$level['vip']])) {
                                                                            $display_price = floatval($fixed_prices[$level['vip']]);
                                                                        } else {
                                                                            $display_price = $price * $level['discount'] / 100;
                                                                        }
                                                                    ?>
                                                                    <td class="px-3 py-2 text-indigo-600 font-medium whitespace-nowrap">
                                                                        <div class="flex items-center">
                                                                            <i class="fas fa-tag text-yellow-400 mr-1 text-xs"></i>
                                                                            ¥<?php echo number_format($display_price, 2); ?>
                                                                        </div>
                                                                    </td>
                                                                <?php endforeach; ?>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-center py-6 bg-gray-50 rounded-lg border border-gray-200">
                    <i class="fas fa-box text-2xl mb-2 text-gray-300"></i>
                    <p class="text-gray-500 text-sm">暂无商品数据</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div id="modalBody" class="px-5 py-4 overflow-y-auto"></div>
            <div id="modalFooter" class="px-5 py-3 border-t border-gray-100 hidden"></div>
        </div>
    </div>
</div>

<script>
var activityActive = <?php echo $activity_active ? 'true' : 'false'; ?>;
var activityDiscount = <?php echo $activity_discount_percent; ?>;
var vipLevelsData = <?php
$vipLevelsData = [];
foreach($vip_levels as $level) {
    if($level['vip'] > $current_vip) {
        $vipLevelsData[(string)$level['id']] = [
            'vip' => $level['vip'],
            'name' => $level['name'],
            'desc' => $level['desc'] ?? '',
            'discount' => $level['discount'],
            'price' => $level['price'],
            'actual_price' => $level['actual_price'],
            'activity_price' => $level['activity_price'],
            'user_profit' => $level['user_fanli_rmb'] ?? 0,
            'user_profit_display' => $level['user_profit_display'] ?? ($level['user_fanli_rmb'] ?? 0),
            'fanli_type' => $level['fanli_type'] ?? 0,
            'commission_account' => isset($conf['agent_commission']) ? intval($conf['agent_commission']) : 0
        ];
    }
}
echo json_encode($vipLevelsData, JSON_UNESCAPED_UNICODE);
?>;
$('#vip-select').change(function() {
    var id = $(this).val();
    var data = vipLevelsData[id];
    if(!data) return;
    $('#detail-vip').text(data.name);
    $('#detail-discount').text(data.discount + '%');
    
    // 显示活动价格
    if (activityActive && activityDiscount < 100) {
        $('#detail-price').html('<span class="line-through text-gray-400 mr-2">¥' + data.actual_price + '</span><span class="text-red-500">¥' + data.activity_price + '</span>');
    } else {
        $('#detail-price').text('¥' + data.actual_price);
    }
    
    $('#detail-desc').text(data.desc || '');

    var giftLabel = data.commission_account == 1 ? '赠送余额：' : '赠送佣金：';
    $('#detail-gift-label').text(giftLabel);

    var giftAmount = 0;
    var payPrice = (activityActive && activityDiscount < 100) ? parseFloat(data.activity_price) : parseFloat(data.actual_price);
    if (data.fanli_type == 1) {
        giftAmount = parseFloat(data.user_profit_display);
    } else {
        giftAmount = payPrice * parseFloat(data.user_profit) / 100;
    }
    $('#detail-user').text('¥' + giftAmount.toFixed(2));
});

$(document).ready(function() {
    $('#vip-select').trigger('change');
    refreshPriceTableCategorySelect();
    var defaultVersion = ($('#price-version-select').val() || '').toString();
    $('#category-select-wrapper').toggle(defaultVersion !== 'qzone');
});

var priceTableCategories = <?php echo json_encode($price_table_categories, JSON_UNESCAPED_UNICODE); ?>;
var qzoneGoodsList = <?php echo json_encode($qzone_goods_list ?? [], JSON_UNESCAPED_UNICODE); ?>;
function refreshPriceTableCategorySelect() {
    var version = ($('#price-version-select').val() || '').toString();
    var cats = priceTableCategories[version] || [];
    var html = '';
    for (var i = 0; i < cats.length; i++) {
        html += '<option value="' + cats[i].id + '">' + cats[i].name + '</option>';
    }
    $('#category-select').html(html);
    var first = cats.length ? cats[0].id : '';
    if (first) $('#category-select').val(first);
    $('#category-select-wrapper').toggle(version !== 'qzone');
    refreshPriceTable();
}
function refreshPriceTable() {
    var version = ($('#price-version-select').val() || '').toString();
    var categoryId = ($('#category-select').val() || '').toString();
    $('.goods-table').hide();
    
    if (version === 'qzone') {
        $('.goods-table[data-version="qzone"]').show();
    } else {
        $('.goods-table[data-version="' + version + '"][data-category="' + categoryId + '"]').show();
    }
}
$('#price-version-select').change(function() {
    refreshPriceTableCategorySelect();
});
$('#category-select').change(function() {
    refreshPriceTable();
});

$(document).on('click', '#upgrade-btn', function() {
    var selectedOption = $('#vip-select').find('option:selected');
    var vipId = selectedOption.val();
    var vipName = selectedOption.data('name');
    var data = vipLevelsData[vipId];
    var actual_price = data ? (activityActive && activityDiscount < 100 ? data.activity_price : data.actual_price) : 0;
    buyUpgrade(vipId, vipName, actual_price);
});

function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function buyUpgrade(vipId, vipName, price) {
    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_available_payments',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            var payments = (data.code == 1 && data.data) ? data.data : [];
            var html = '<div class="space-y-3">';
            html += '<button onclick="balancePay(' + vipId + ', \'' + vipName + '\', ' + price + ')" class="w-full flex items-center justify-between bg-indigo-50 hover:bg-indigo-100 text-indigo-700 font-medium py-2.5 px-4 rounded-lg transition-colors">';
            html += '<div class="flex items-center gap-2"><i class="fas fa-wallet"></i><span>余额支付</span></div>';
            html += '<span class="text-sm text-gray-500">余额: <?php echo $userrow['rmb']; ?>元</span></button>';

            if(payments.length > 0){
                html += '<div class="pt-3 border-t border-gray-100"><p class="text-xs text-gray-500 mb-2 text-center">在线支付</p><div class="grid grid-cols-2 gap-2">';
                for(var i=0; i<payments.length; i++){
                    var item = payments[i];
                    var icon = 'alipay.png', color = 'text-blue-600', label = item.name || '支付宝';
                    if(item.pay_type == 'wxpay'){ icon = 'wxpay.png'; color = 'text-green-600'; label = item.name || '微信支付'; }
                    if(item.pay_type == 'qqpay'){ icon = 'qqpay.png'; color = 'text-sky-600'; label = item.name || 'QQ钱包'; }
                    html += '<button onclick="dopayUpgrade(' + vipId + ', ' + item.interface_id + ')" class="flex items-center justify-center gap-2 bg-gray-50 hover:bg-gray-100 '+color+' font-medium py-2.5 px-4 rounded-lg transition-colors">';
                    html += '<img src="../assets/img/'+icon+'" style="width:24px;"><span>'+label+'</span></button>';
                }
                html += '</div></div>';
            }
            html += '</div>';
            openModal('选择支付方式', html, function() {
                return '<button onclick="closeModal()" class="w-full py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button>';
            });
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function balancePay(vipId, vipName, price) {
    closeModal();
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=pay',
        data: { goods: vipId, qq: '0', type: '99' },
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == '1') {
                var tmp = '<p class="text-center">'+data.msg+'</p><div class="grid gap-2 mt-4"><a class="block py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center text-sm" href="./">返回首页</a><a class="block py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium text-center text-sm" href="./upgrade.php">继续升级</a></div>';
                openModal('操作成功', tmp, function(){ return '<button onclick="closeModal();location.reload();" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            } else if (data.code == '-2') {
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./recharge.php" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往充值</a></div>'; });
            } else { showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function dopayUpgrade(vipId, interface_id) {
    closeModal();
    showLoading();
    $.get("ajax.php?act=dopay&interface_id=" + interface_id + "&id=" + vipId + "&qq=0&grade=99", function(data){
        hideLoading();
        if(data.code == 0){
            window.location.href='../other/submit.php?type='+data.type+'&orderid='+data.trade_no;
        }else if(data.code == '-3'){
            openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往找回</a></div>'; });
        }else{ showToast(data.msg); }
    }, 'json').fail(function(){ hideLoading(); showToast('服务器错误'); });
}
</script>
