<?php
// ==================== 导入导出API（必须在head.php之前处理）====================
if(isset($_GET['export_import_act'])) {
    include dirname(__DIR__) . '/includes/common.php';
    header('Content-Type: application/json; charset=utf-8');
    
    global $islogin;
    if($islogin != 1) {
        exit(json_encode(array('code' => -1, 'msg' => '未登录')));
    }
    
    switch($_GET['export_import_act']) {
        case 'get_export_list':
            $exportBiz = isset($_GET['biz']) ? daddslashes($_GET['biz']) : 'all';
            $where = $exportBiz === 'all' ? '1=1' : "biz='{$exportBiz}'";
            $apis = $DB->getAll("SELECT id, citybz, biz, url, query_api, type, cid FROM pre_loginconfig WHERE {$where} ORDER BY sort ASC");
            $protocols = $DB->getAll("SELECT id, cid, name, type, sort, status, is_pwd FROM pre_protocol ORDER BY cid, sort ASC");
            $apis = $apis ? $apis : array();
            $protocols = $protocols ? $protocols : array();
            exit(json_encode(array('code' => 1, 'data' => array('apis' => $apis, 'protocols' => $protocols))));
        break;
        
        case 'export_config':
            $ids = isset($_POST['ids']) ? $_POST['ids'] : array();
            if(!is_array($ids) || empty($ids)) {
                exit(json_encode(array('code' => -1, 'msg' => '请选择要导出的接口')));
            }
            $ids = array_filter(array_map('intval', $ids), function($v) { return $v > 0; });
            if(empty($ids)) {
                exit(json_encode(array('code' => -1, 'msg' => '无效的接口ID')));
            }
            $idList = implode(',', $ids);
            $apis = $DB->getAll("SELECT citybz, biz, url, query_api, type, cid FROM pre_loginconfig WHERE id IN ({$idList}) ORDER BY sort ASC");
            $cids = array();
            foreach($apis as $api) {
                if(!empty($api['cid'])) {
                    $cids[] = "'" . daddslashes($api['cid']) . "'";
                }
            }
            $protocols = array();
            if(!empty($cids)) {
                $cidList = implode(',', array_unique($cids));
                $protocols = $DB->getAll("SELECT cid, name, type, sort, status, is_pwd FROM pre_protocol WHERE cid IN ({$cidList}) ORDER BY cid, sort ASC");
            }
            exit(json_encode(array(
                'code' => 1,
                'msg' => '导出成功',
                'data' => array(
                    'version' => '1.0',
                    'export_time' => date('Y-m-d H:i:s'),
                    'export_count' => count($apis),
                    'apis' => $apis,
                    'protocols' => $protocols
                )
            )));
        break;
        
        case 'get_login_class':
            $cloudClasses = $DB->getAll("SELECT id, name FROM pre_login_class WHERE biz='cloud' OR biz IS NULL ORDER BY id ASC");
            $dgClasses = $DB->getAll("SELECT id, name FROM pre_login_class WHERE biz='dg' OR biz IS NULL ORDER BY id ASC");
            $cloudClasses = $cloudClasses ? $cloudClasses : array();
            $dgClasses = $dgClasses ? $dgClasses : array();
            exit(json_encode(array('code' => 1, 'data' => array('cloud' => $cloudClasses, 'dg' => $dgClasses))));
        break;
        
        case 'import_config':
            $configJson = isset($_POST['config']) ? $_POST['config'] : '';
            if(empty($configJson)) {
                exit(json_encode(array('code' => -1, 'msg' => '配置数据为空')));
            }
            $config = json_decode($configJson, true);
            if(!$config || !isset($config['apis'])) {
                exit(json_encode(array('code' => -1, 'msg' => '配置数据格式错误')));
            }
            $classCloud = isset($config['class_cloud']) ? intval($config['class_cloud']) : 0;
            $classDg = isset($config['class_dg']) ? intval($config['class_dg']) : 0;
            $skipExists = isset($config['skip_exists']) ? intval($config['skip_exists']) : 1;
            $importCount = 0;
            $protocolCount = 0;
            $skipProtocolCount = 0;
            
            if(!empty($config['protocols'])) {
                foreach($config['protocols'] as $protocol) {
                    $cid = daddslashes($protocol['cid']);
                    $name = daddslashes($protocol['name']);
                    $type = intval($protocol['type']);
                    $sort = intval($protocol['sort']);
                    $status = isset($protocol['status']) ? intval($protocol['status']) : 1;
                    $is_pwd = isset($protocol['is_pwd']) ? intval($protocol['is_pwd']) : 0;
                    $exists = $DB->getRow("SELECT id FROM pre_protocol WHERE cid='{$cid}' AND type='{$type}'");
                    if($exists) {
                        $skipProtocolCount++;
                        if($skipExists) continue;
                        $DB->exec("UPDATE pre_protocol SET name='{$name}', sort='{$sort}', status='{$status}', is_pwd='{$is_pwd}' WHERE id='{$exists['id']}'");
                        $protocolCount++;
                        continue;
                    }
                    $DB->exec("INSERT INTO pre_protocol (cid, name, type, sort, status, is_pwd) VALUES ('{$cid}', '{$name}', '{$type}', '{$sort}', '{$status}', '{$is_pwd}')");
                    $protocolCount++;
                }
            }
            
            $maxSort = $DB->getColumn("SELECT MAX(sort) FROM pre_loginconfig");
            $sort = intval($maxSort);
            foreach($config['apis'] as $api) {
                $citybz = daddslashes($api['citybz']);
                $apiBiz = isset($api['biz']) ? daddslashes($api['biz']) : 'cloud';
                $url = daddslashes($api['url']);
                $query_api = isset($api['query_api']) ? daddslashes($api['query_api']) : '';
                $type = daddslashes($api['type']);
                $cid = isset($api['cid']) ? daddslashes($api['cid']) : '';
                $cids = ($apiBiz == 'dg') ? $classDg : $classCloud;
                $sort++;
                $DB->exec("INSERT INTO pre_loginconfig (citybz, biz, url, query_api, type, cid, sort, status, cids, max, apipwd, msg, msg_type, show_online_census, api_error_check) VALUES ('{$citybz}', '{$apiBiz}', '{$url}', '{$query_api}', '{$type}', '{$cid}', '{$sort}', '1', '{$cids}', '0', '', '', '0', '1', '1')");
                $importCount++;
            }
            
            $msg = "导入成功：接口 {$importCount} 个";
            if($protocolCount > 0 || $skipProtocolCount > 0) {
                $msg .= "，协议新增 {$protocolCount} 个";
                if($skipProtocolCount > 0) $msg .= "，跳过已存在 {$skipProtocolCount} 个";
            }
            exit(json_encode(array('code' => 1, 'msg' => $msg)));
        break;
        
        default:
            exit(json_encode(array('code' => -1, 'msg' => '未知操作')));
        break;
    }
}

// ==================== 正常页面逻辑 =====================
$title = '小荠菜优化';
include __DIR__ . '/head.php';

// 授权站API配置
define('AUTH_API_URL', 'https://sqz.dadxb.cn/api');
define('SHOP_URL', 'https://51mpz.shop');

// 获取当前域名
function get_current_domain() {
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    // 移除端口号
    $domain = preg_replace('/:\d+$/', '', $domain);
    return $domain;
}

// 调用授权站API
function call_auth_api($endpoint, $params = []) {
    $url = AUTH_API_URL . $endpoint . '?' . http_build_query($params);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 || empty($response)) {
        return null;
    }
    
    return json_decode($response, true);
}

// 获取当前配置
$cloud_add = $conf['stats_cloud_add'] ?? '';
$dg_add = $conf['stats_dg_add'] ?? '';
$qzone_add = $conf['stats_qzone_add'] ?? '';

// 获取后台真实数据
$cloud_online = intval($DB->getColumn("SELECT COUNT(*) FROM pre_qq WHERE login_zt = '1'"));
$dg_online = intval($DB->getColumn("SELECT COUNT(*) FROM pre_dg_qq WHERE login_zt = '1'"));
$qzone_valid = intval($DB->getColumn("SELECT COUNT(*) FROM " . DBQZ . "qzone_qq WHERE login_status=0"));
$qzone_vip = intval($DB->getColumn("SELECT COUNT(*) FROM " . DBQZ . "qzone_qq WHERE vip_time > NOW()"));

// 获取版本信息
$auth_config = include ROOT . 'includes/Auth.php';
$current_version = $auth_config['app_version'] ?? '2.90';
$app_name = $auth_config['app_name'] ?? '小荠菜网页登录系统';

// 获取挂版本配置
$bugua_version = $conf['bugua_version'] ?? 'qb';

// 获取当前域名
$current_domain = get_current_domain();
?>

<div class="p-4 md:p-6 space-y-4">
    <!-- 系统检测 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-4 py-2.5 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800"><i class="fas fa-tools text-blue-500 mr-2"></i>系统检测</h3>
        </div>
        <div class="p-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div class="flex items-center py-2 border-b border-gray-100">
                    <span class="text-gray-500 w-24">程序名称</span>
                    <span class="text-gray-800 font-medium"><?php echo $app_name; ?></span>
                </div>
                <div class="flex items-center py-2 border-b border-gray-100">
                    <span class="text-gray-500 w-24">当前版本</span>
                    <span class="text-gray-800 font-medium">V <?php echo $current_version; ?></span>
                </div>
                <div class="flex items-center py-2 border-b border-gray-100">
                    <span class="text-gray-500 w-24">当前域名</span>
                    <span class="text-gray-800 font-medium text-sm"><?php echo htmlspecialchars($current_domain); ?></span>
                </div>
                <div class="flex items-center py-2 border-b border-gray-100">
                    <span class="text-gray-500 w-24">授权状态</span>
                    <span id="auth_status_text" class="text-gray-500">检测中...</span>
                </div>
            </div>
            
            <div class="flex flex-wrap gap-2">
                <button id="check_update" class="inline-flex items-center justify-center h-9 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm">
                    <i class="fas fa-sync-alt mr-2"></i>检测更新
                </button>
                <button id="check_auth" class="inline-flex items-center justify-center h-9 px-4 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors text-sm">
                    <i class="fas fa-shield-alt mr-2"></i>检测授权
                </button>
                <button id="check_schema" class="inline-flex items-center justify-center h-9 px-4 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 transition-colors text-sm">
                    <i class="fas fa-database mr-2"></i>校验数据
                </button>
                <a href="<?php echo SHOP_URL; ?>" target="_blank" class="inline-flex items-center justify-center h-9 px-4 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors text-sm">
                    <i class="fas fa-shopping-cart mr-2"></i>前往授权
                </a>
            </div>
            
            <div id="result" class="hidden mt-4 p-4 bg-gray-50 rounded-lg">
                <div id="result_content"></div>
            </div>
            
            <!-- 更新进度条 -->
            <div id="update_progress" class="hidden mt-4 p-4 bg-blue-50 rounded-lg border border-blue-100">
                <div class="flex items-center mb-2">
                    <span id="progress_status"></span>
                    <span id="progress_text" class="text-sm text-gray-600"></span>
                </div>
                <div class="bg-gray-200 rounded-full h-3 overflow-hidden">
                    <div id="progress_bar" class="bg-gradient-to-r from-blue-500 to-indigo-500 h-3 rounded-full transition-all duration-500" style="width: 0%"></div>
                </div>
                <div class="flex justify-between text-xs text-gray-400 mt-1">
                    <span>0%</span>
                    <span>下载</span>
                    <span>解压</span>
                    <span>安装</span>
                    <span>100%</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 补挂版本选择 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-4 py-2.5 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800"><i class="fas fa-rocket text-purple-500 mr-2"></i>补挂版本选择</h3>
        </div>
        <div class="p-4">
            <div class="mb-4 p-3 bg-purple-50 rounded-lg border border-purple-100 text-xs text-purple-700">
                <i class="fas fa-info-circle mr-1"></i>选择不同的补挂版本，系统将使用对应的补挂页面和API接口
            </div>

            <form id="buguaVersionForm">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- QB加速（原版） -->
                    <div class="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg border-2 border-blue-200 cursor-pointer transition-all hover:shadow-md bugua-version-card" data-version="qb">
                        <div class="flex items-start gap-3">
                            <input type="radio" name="bugua_version" value="qb" id="version_qb" class="mt-1" <?php echo ($bugua_version === 'qb') ? 'checked' : ''; ?>>
                            <label for="version_qb" class="flex-1 cursor-pointer">
                                <div class="flex items-center gap-2 mb-2">
                                    <i class="fas fa-bolt text-blue-500 text-lg"></i>
                                    <span class="font-semibold text-gray-800">QB加速</span>
                                    <span class="px-2 py-0.5 text-xs bg-blue-100 text-blue-600 rounded">原版</span>
                                </div>
                                <div class="text-xs text-gray-600 space-y-1">
                                    <div class="flex items-center gap-1"><i class="fas fa-check text-green-500"></i> 原生QB加速接口</div>
                                    <div class="flex items-center gap-1"><i class="fas fa-check text-green-500"></i> 标准项目列表</div>
                                    <div class="flex items-center gap-1"><i class="fas fa-check text-green-500"></i> 稳定可靠</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <!-- 喵喵加速 -->
                    <div class="p-4 bg-gradient-to-r from-purple-50 to-pink-50 rounded-lg border-2 border-purple-200 cursor-pointer transition-all hover:shadow-md bugua-version-card" data-version="miaomiao">
                        <div class="flex items-start gap-3">
                            <input type="radio" name="bugua_version" value="miaomiao" id="version_miaomiao" class="mt-1" <?php echo ($bugua_version === 'miaomiao') ? 'checked' : ''; ?>>
                            <label for="version_miaomiao" class="flex-1 cursor-pointer">
                                <div class="flex items-center gap-2 mb-2">
                                    <i class="fas fa-cat text-purple-500 text-lg"></i>
                                    <span class="font-semibold text-gray-800">喵喵加速</span>
                                    <span class="px-2 py-0.5 text-xs bg-purple-100 text-purple-600 rounded">增强版</span>
                                </div>
                                <div class="text-xs text-gray-600 space-y-1">
                                    <div class="flex items-center gap-1"><i class="fas fa-star text-yellow-500"></i> 新增电脑在线开关</div>
                                    <div class="flex items-center gap-1"><i class="fas fa-star text-yellow-500"></i> 新增会员签到项目</div>
                                    <div class="flex items-center gap-1"><i class="fas fa-star text-yellow-500"></i> 新增体验游戏项目</div>
                                    <div class="flex items-center gap-1"><i class="fas fa-check text-green-500"></i> 17个完整项目支持</div>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-between mt-4 pt-3 border-t border-gray-100">
                    <span class="text-xs text-gray-500">当前版本：<span id="currentBuguaVersion" class="font-medium text-purple-600"><?php echo ($bugua_version === 'qb') ? 'QB加速' : '喵喵加速'; ?></span></span>
                    <button type="submit" class="px-3 py-1.5 text-xs bg-purple-600 hover:bg-purple-700 text-white rounded transition">
                        <i class="fas fa-save mr-1"></i>保存设置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 在线统计优化设置 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-4 py-2.5 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800"><i class="fas fa-magic text-indigo-500 mr-2"></i>在线统计优化设置</h3>
        </div>
        <div class="p-4">
            <div class="mb-4 p-3 bg-blue-50 rounded-lg border border-blue-100 text-xs text-blue-700">
                <i class="fas fa-info-circle mr-1"></i>填写数字后，用户端显示 <code class="bg-blue-100 px-1 rounded">填写值 + 真实数据</code>，留空则只显示真实数据
            </div>

            <form id="optimizeForm">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- 云端 -->
                    <div class="p-3 bg-gradient-to-r from-teal-50 to-emerald-50 rounded-lg border border-teal-100">
                        <div class="flex items-center gap-2 mb-2">
                            <i class="fas fa-cloud text-teal-500"></i>
                            <span class="font-medium text-gray-800 text-sm">云端在线</span>
                            <span class="text-xs text-gray-500 ml-auto">真实: <?php echo $cloud_online; ?></span>
                        </div>
                        <input type="number" name="stats_cloud_add" value="<?php echo htmlspecialchars($cloud_add); ?>" 
                               class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-teal-500" 
                               placeholder="增加值" min="0">
                    </div>

                    <!-- 代挂 -->
                    <div class="p-3 bg-gradient-to-r from-violet-50 to-purple-50 rounded-lg border border-violet-100">
                        <div class="flex items-center gap-2 mb-2">
                            <i class="fas fa-server text-violet-500"></i>
                            <span class="font-medium text-gray-800 text-sm">代挂在线</span>
                            <span class="text-xs text-gray-500 ml-auto">真实: <?php echo $dg_online; ?></span>
                        </div>
                        <input type="number" name="stats_dg_add" value="<?php echo htmlspecialchars($dg_add); ?>" 
                               class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-violet-500" 
                               placeholder="增加值" min="0">
                    </div>

                    <!-- 秒赞 -->
                    <div class="p-3 bg-gradient-to-r from-rose-50 to-red-50 rounded-lg border border-rose-100">
                        <div class="flex items-center gap-2 mb-2">
                            <i class="fas fa-heart text-rose-500"></i>
                            <span class="font-medium text-gray-800 text-sm">秒赞有效</span>
                            <span class="text-xs text-gray-500 ml-auto">真实: <?php echo $qzone_valid; ?></span>
                        </div>
                        <input type="number" name="stats_qzone_add" value="<?php echo htmlspecialchars($qzone_add); ?>" 
                               class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-rose-500" 
                               placeholder="增加值" min="0">
                    </div>
                </div>

                <div class="flex items-center justify-between mt-4 pt-3 border-t border-gray-100">
                    <span class="text-xs text-gray-500">用户端预览：
                        <span class="text-teal-600 font-medium"><?php echo ($cloud_add !== '' ? intval($cloud_add) : 0) + $cloud_online; ?></span> 云端 ·
                        <span class="text-violet-600 font-medium"><?php echo ($dg_add !== '' ? intval($dg_add) : 0) + $dg_online; ?></span> 代挂 ·
                        <span class="text-rose-600 font-medium"><?php echo ($qzone_add !== '' ? intval($qzone_add) : 0) + $qzone_valid; ?></span> 秒赞
                    </span>
                    <div class="flex gap-2">
                        <button type="button" onclick="resetForm()" class="px-3 py-1.5 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded transition">重置</button>
                        <button type="submit" class="px-3 py-1.5 text-xs bg-indigo-600 hover:bg-indigo-700 text-white rounded transition">保存</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 登录接口导入导出 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-4 py-2.5 bg-gray-50 border-b border-gray-100">
            <h3 class="font-medium text-gray-800"><i class="fas fa-exchange-alt text-blue-500 mr-2"></i>登录接口导入导出</h3>
        </div>
        <div class="p-4">
            <div class="flex flex-wrap items-center gap-3">
                <select id="bizFilter" class="px-2 py-1.5 text-sm border border-gray-300 rounded">
                    <option value="all">全部业务</option>
                    <option value="cloud">云端</option>
                    <option value="dg">代挂</option>
                </select>
                <button type="button" onclick="showExportModal()" class="px-3 py-1.5 text-xs bg-blue-600 hover:bg-blue-700 text-white rounded transition">
                    <i class="fas fa-download mr-1"></i>导出
                </button>
                <button type="button" onclick="showImportModal()" class="px-3 py-1.5 text-xs bg-purple-600 hover:bg-purple-700 text-white rounded transition">
                    <i class="fas fa-upload mr-1"></i>导入
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 校验数据模态框 -->
<div id="schema_modal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 transition-opacity" onclick="closeSchemaModal()"></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-3xl max-h-[85vh] flex flex-col relative transform transition-all">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                <h3 class="text-lg font-semibold text-gray-800">数据库校验</h3>
                <button onclick="closeSchemaModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="px-5 py-4 overflow-y-auto">
                <div id="schema_content"></div>
            </div>
            <div class="px-5 py-3 border-t border-gray-100 text-right">
                <button onclick="closeSchemaModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">
                    关闭
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 导出模态框 -->
<div class="modal fade" id="exportModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title text-sm">导出接口配置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body py-3">
                <div id="exportList" class="max-h-64 overflow-y-auto"></div>
            </div>
            <div class="modal-footer py-2">
                <span class="text-xs text-gray-600 mr-auto">已选 <span id="exportCount">0</span> 个</span>
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary btn-sm" onclick="doExport()">导出</button>
            </div>
        </div>
    </div>
</div>

<!-- 导出结果模态框 -->
<div class="modal fade" id="exportResultModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title text-sm">导出成功</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body py-3">
                <textarea id="exportResult" class="w-full h-48 p-2 text-xs border border-gray-300 rounded font-mono" readonly></textarea>
            </div>
            <div class="modal-footer py-2">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-info btn-sm" onclick="copyExportResult()">复制</button>
                <button type="button" class="btn btn-success btn-sm" onclick="downloadExportResult()">下载</button>
            </div>
        </div>
    </div>
</div>

<!-- 导入模态框 -->
<div class="modal fade" id="importModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title text-sm">导入接口配置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body py-3">
                <div class="grid grid-cols-2 gap-3 mb-3">
                    <div>
                        <label class="text-xs text-gray-600 mb-1 block">云端分类</label>
                        <select id="importClassCloud" class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded"></select>
                    </div>
                    <div>
                        <label class="text-xs text-gray-600 mb-1 block">代挂分类</label>
                        <select id="importClassDg" class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded"></select>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="flex items-center text-xs">
                        <input type="checkbox" id="importSkipExists" checked class="mr-1">跳过已存在的协议
                    </label>
                </div>
                <div class="mb-3">
                    <label class="text-xs text-gray-600 mb-1 block">上传文件</label>
                    <input type="file" id="importFile" accept=".json" class="text-xs" onchange="handleFileSelect(event)">
                </div>
                <div>
                    <label class="text-xs text-gray-600 mb-1 block">或粘贴JSON</label>
                    <textarea id="importConfig" class="w-full h-24 p-2 text-xs border border-gray-300 rounded font-mono" placeholder="粘贴导出的JSON配置"></textarea>
                </div>
            </div>
            <div class="modal-footer py-2">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary btn-sm" onclick="doImport()">导入</button>
            </div>
        </div>
    </div>
</div>

<script>
var currentDomain = '<?php echo $current_domain; ?>';
var currentVersion = '<?php echo $current_version; ?>';
var authApiUrl = '<?php echo AUTH_API_URL; ?>';
var shopUrl = '<?php echo SHOP_URL; ?>';

$(function() {
    // 页面加载时检测授权状态
    checkAuthStatus();
    
    // 保存在线统计配置
    $('#optimizeForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax.php?act=save_optimize_stats',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res) {
                showToast(res.code === 1 ? '保存成功' : (res.msg || '保存失败'), res.code === 1 ? 'success' : 'error');
                if(res.code === 1) setTimeout(function() { location.reload(); }, 800);
            },
            error: function() { showToast('网络错误', 'error'); }
        });
    });
    
    // 保存补挂版本
    $('#buguaVersionForm').on('submit', function(e) {
        e.preventDefault();
        var version = $('input[name="bugua_version"]:checked').val();
        $.ajax({
            url: 'ajax.php?act=save_optimize_stats',
            type: 'POST',
            data: { bugua_version: version },
            dataType: 'json',
            success: function(res) {
                showToast(res.code === 1 ? '保存成功' : (res.msg || '保存失败'), res.code === 1 ? 'success' : 'error');
                if(res.code === 1) {
                    $('#currentBuguaVersion').text(version === 'qb' ? 'QB加速' : '喵喵加速');
                }
            },
            error: function() { showToast('网络错误', 'error'); }
        });
    });
    
    // 补挂版本卡片点击
    $('.bugua-version-card').click(function() {
        $(this).find('input[type="radio"]').prop('checked', true);
    });
});

function resetForm() {
    $('#optimizeForm input[type="number"]').val('');
    showToast('已重置', 'info');
}

// 检测授权状态（页面加载时）
function checkAuthStatus() {
    $.ajax({
        url: 'ajax.php?act=check_auth_status_api',
        type: 'POST',
        data: { domain: currentDomain },
        dataType: 'json',
        success: function(res) {
            if(res.code === 1 && res.data && res.data.is_valid) {
                $('#auth_status_text').html('<span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>已授权</span>');
            } else {
                $('#auth_status_text').html('<span class="text-red-500"><i class="fas fa-times-circle mr-1"></i>未授权</span>');
            }
        },
        error: function() {
            $('#auth_status_text').html('<span class="text-gray-500">检测失败</span>');
        }
    });
}

// 检测更新
$('#check_update').click(function() {
    checkUpdate(false);
});

function checkUpdate(silent) {
    var btn = $('#check_update');
    if(!silent) {
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>检测中...');
        $('#result').removeClass('hidden');
        $('#result_content').html('<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg"><p class="text-gray-600"><i class="fas fa-spinner fa-spin mr-2"></i>正在检测更新...</p></div>');
        $('#update_progress').addClass('hidden');
    }
    
    $.ajax({
        url: 'ajax.php?act=check_update_api',
        type: 'POST',
        data: { current_version: currentVersion },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-2"></i>检测更新');
            
            if(res.code === 1 && res.data && res.data.has_update) {
                var changelog = res.data.changelog ? '<div class="mt-3 p-3 bg-gray-50 rounded text-sm text-gray-700">' + res.data.changelog.replace(/\n/g, '<br>') + '</div>' : '';
                var downloadUrl = res.data.download_url || '';
                var newVersion = res.data.latest_version || '';
                
                // 在线更新按钮
                var updateBtn = downloadUrl ? 
                    '<button id="do_online_update" class="mt-3 inline-flex items-center px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm" data-download-url="' + downloadUrl + '" data-new-version="' + newVersion + '"><i class="fas fa-cloud-download-alt mr-2"></i>在线更新</button>' +
                    '<a href="' + downloadUrl + '" target="_blank" class="mt-3 ml-2 inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"><i class="fas fa-download mr-2"></i>手动下载</a>' : '';
                
                $('#result_content').html('<div class="p-4 bg-blue-50 border border-blue-200 rounded-lg">' +
                    '<p class="text-blue-600 font-medium"><i class="fas fa-arrow-circle-up mr-2"></i>发现新版本！</p>' +
                    '<p class="text-sm text-gray-600 mt-2">最新版本：<span class="font-medium text-blue-600">V ' + res.data.latest_version + '</span></p>' +
                    '<p class="text-sm text-gray-500">版本名称：' + (res.data.name || '小荠菜网页登录系统') + '</p>' +
                    changelog +
                    '<div class="mt-3">' + updateBtn + '</div>' +
                    '</div>');
                
                showToast('发现新版本 V' + res.data.latest_version, 'warning');
            } else {
                if(!silent) {
                    $('#result_content').html('<div class="p-4 bg-green-50 border border-green-200 rounded-lg">' +
                        '<p class="text-green-600 font-medium"><i class="fas fa-check-circle mr-2"></i>当前已是最新版本</p>' +
                        '<p class="text-sm text-gray-500 mt-2">当前版本：V ' + currentVersion + '</p>' +
                        '</div>');
                }
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-2"></i>检测更新');
            if(!silent) {
                $('#result_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg"><p class="text-red-600">请求失败，请稍后重试</p></div>');
            }
        }
    });
}

// 在线更新
$(document).on('click', '#do_online_update', function() {
    if(!confirm('确定要在线更新吗？\n\n更新会自动下载并覆盖文件，config.php和授权文件不会被覆盖！')) {
        return;
    }
    
    var btn = $(this);
    btn.prop('disabled', true);
    
    var downloadUrl = btn.data('download-url');
    var newVersion = btn.data('new-version');
    
    // 显示进度面板
    $('#update_progress').removeClass('hidden');
    
    // 更新进度函数
    function updateProgress(percent, text, status) {
        $('#progress_bar').css('width', percent + '%');
        $('#progress_text').text(text);
        
        var statusIcon = '';
        if(status === 'loading') {
            statusIcon = '<i class="fas fa-spinner fa-spin text-blue-500 mr-2"></i>';
        } else if(status === 'success') {
            statusIcon = '<i class="fas fa-check-circle text-green-500 mr-2"></i>';
        } else if(status === 'error') {
            statusIcon = '<i class="fas fa-times-circle text-red-500 mr-2"></i>';
        }
        $('#progress_status').html(statusIcon);
    }
    
    // 步骤1: 下载更新包
    updateProgress(5, '正在从服务器下载更新包...', 'loading');
    btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>下载中...');
    
    $.ajax({
        url: 'ajax.php?act=download_update',
        type: 'POST',
        data: { download_url: downloadUrl, new_version: newVersion },
        dataType: 'json',
        timeout: 300000,
        success: function(res) {
            if(res.code !== 1) {
                updateProgress(0, '下载失败: ' + res.msg, 'error');
                btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
                btn.prop('disabled', false);
                return;
            }
            
            updateProgress(40, '下载完成 (' + Math.round(res.data.file_size / 1024) + ' KB)，正在解压...', 'success');
            btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>解压中...');
            
            // 步骤2: 解压更新包
            setTimeout(function() {
                $.ajax({
                    url: 'ajax.php?act=extract_update',
                    type: 'POST',
                    dataType: 'json',
                    timeout: 60000,
                    success: function(res) {
                        if(res.code !== 1) {
                            updateProgress(40, '解压失败: ' + res.msg, 'error');
                            btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
                            btn.prop('disabled', false);
                            return;
                        }
                        
                        updateProgress(60, '解压完成 (' + res.data.file_count + ' 个文件)，正在安装...', 'success');
                        btn.html('<i class="fas fa-spinner fa-spin mr-2"></i>安装中...');
                        
                        // 步骤3: 安装更新
                        setTimeout(function() {
                            $.ajax({
                                url: 'ajax.php?act=install_update',
                                type: 'POST',
                                data: { new_version: newVersion },
                                dataType: 'json',
                                timeout: 120000,
                                success: function(res) {
                                    if(res.code !== 1) {
                                        updateProgress(60, '安装失败: ' + res.msg, 'error');
                                        btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
                                        btn.prop('disabled', false);
                                        return;
                                    }
                                    
                                    updateProgress(100, '更新完成！', 'success');
                                    btn.html('<i class="fas fa-check mr-2"></i>更新完成');
                                    
                                    var info = '<div class="p-4 bg-green-50 border border-green-200 rounded-lg mt-4">' +
                                        '<p class="text-green-600 font-medium mb-2"><i class="fas fa-check-circle mr-2"></i>更新成功！</p>' +
                                        '<p class="text-gray-600 text-sm">版本：V ' + res.data.version + '</p>' +
                                        '<p class="text-gray-600 text-sm">更新文件数：' + res.data.files_copied + ' / ' + res.data.total_files + '</p>' +
                                        '<p class="text-gray-500 text-xs mt-2">备份目录：' + res.data.backup_dir + '</p>' +
                                        '</div>';
                                    
                                    $('#result_content').html(info);
                                    
                                    setTimeout(function() {
                                        alert('更新成功！即将刷新页面...');
                                        location.reload();
                                    }, 1500);
                                },
                                error: function(xhr, status) {
                                    updateProgress(60, '安装请求失败: ' + (status === 'timeout' ? '超时' : '网络错误'), 'error');
                                    btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
                                    btn.prop('disabled', false);
                                }
                            });
                        }, 500);
                    },
                    error: function(xhr, status) {
                        updateProgress(40, '解压请求失败: ' + (status === 'timeout' ? '超时' : '网络错误'), 'error');
                        btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
                        btn.prop('disabled', false);
                    }
                });
            }, 500);
        },
        error: function(xhr, status) {
            updateProgress(0, '下载请求失败: ' + (status === 'timeout' ? '超时，文件较大请重试' : '网络错误'), 'error');
            btn.html('<i class="fas fa-cloud-download-alt mr-2"></i>在线更新');
            btn.prop('disabled', false);
        }
    });
});

// 检测授权（手动点击）
$('#check_auth').click(function() {
    var btn = $(this);
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>检测中...');
    
    $.ajax({
        url: 'ajax.php?act=check_auth_status_api',
        type: 'POST',
        data: { domain: currentDomain },
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-shield-alt mr-2"></i>检测授权');
            $('#result').removeClass('hidden');
            
            if(res.code === 1 && res.data && res.data.is_valid) {
                var html = '<div class="p-4 bg-green-50 border border-green-200 rounded-lg">' +
                    '<p class="text-green-600 font-medium"><i class="fas fa-check-circle mr-2"></i>授权有效</p>';
                if(res.data.domain) html += '<p class="text-sm text-gray-600 mt-2">授权域名：' + res.data.domain + '</p>';
                if(res.data.expire_time) html += '<p class="text-sm text-gray-600">到期时间：' + res.data.expire_time + '</p>';
                if(res.data.days_left) html += '<p class="text-sm text-gray-600">剩余天数：' + res.data.days_left + ' 天</p>';
                html += '</div>';
                $('#result_content').html(html);
            } else {
                $('#result_content').html('<div class="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">' +
                    '<p class="text-yellow-600 font-medium"><i class="fas fa-exclamation-triangle mr-2"></i>未授权或授权已过期</p>' +
                    '<p class="text-sm text-gray-600 mt-2">' + (res.msg || '当前域名未获得授权') + '</p>' +
                    '<a href="' + shopUrl + '" target="_blank" class="mt-3 inline-flex items-center px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors text-sm"><i class="fas fa-shopping-cart mr-2"></i>前往购买授权</a>' +
                    '</div>');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-shield-alt mr-2"></i>检测授权');
            $('#result').removeClass('hidden');
            $('#result_content').html('<div class="p-4 bg-red-50 border border-red-200 rounded-lg"><p class="text-red-600">请求失败，请稍后重试</p></div>');
        }
    });
});

// 校验数据
$('#check_schema').click(function() {
    var btn = $(this);
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>校验中...');
    
    $.ajax({
        url: 'ajax.php?act=check_schema',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            btn.prop('disabled', false).html('<i class="fas fa-database mr-2"></i>校验数据');
            
            if(res.code === 1) {
                renderSchemaResult(res.data);
                $('#schema_modal').removeClass('hidden');
            } else {
                showToast(res.msg || '校验失败', 'error');
            }
        },
        error: function() {
            btn.prop('disabled', false).html('<i class="fas fa-database mr-2"></i>校验数据');
            showToast('网络错误', 'error');
        }
    });
});

function renderSchemaResult(data) {
    var summary = data.summary || {};
    var missingTables = data.missing_tables || [];
    var tables = data.tables || [];
    
    var totalMissingCols = summary.missing_columns_count || 0;
    var totalExtraCols = summary.extra_columns_count || 0;
    var totalMissingTables = summary.missing_tables_count || 0;
    
    // 只有缺表或缺列才是真正的问题
    var hasIssue = totalMissingTables > 0 || totalMissingCols > 0;
    
    var html = '';
    
    if(!hasIssue){
        // 没有问题，显示正常
        html += '<div class="p-4 bg-green-50 border border-green-200 rounded-lg mb-3">';
        html += '<p class="text-green-700 font-medium"><i class="fas fa-check-circle mr-2"></i>数据库结构正常</p>';
        if(totalExtraCols > 0) {
            html += '<p class="text-green-600 text-sm mt-1">检测到 '+totalExtraCols+' 个扩展字段（定制化功能）</p>';
        }
        html += '</div>';
    } else {
        // 有问题，显示需要修复
        html += '<div class="p-4 bg-red-50 border border-red-200 rounded-lg mb-3">';
        html += '<p class="text-red-700 font-medium"><i class="fas fa-exclamation-triangle mr-2"></i>数据库结构异常</p>';
        html += '<p class="text-red-600 text-sm mt-1">缺表 '+totalMissingTables+' 个，缺列 '+totalMissingCols+' 个</p>';
        html += '</div>';
    }
    
    // 只在有实际问题时显示详情
    if(hasIssue){
        // 缺失的表
        if(missingTables.length){
            html += '<div class="mb-3"><div class="font-medium text-red-700 mb-1"><i class="fas fa-table mr-1"></i>缺少的表</div>';
            html += '<div class="text-sm text-red-600 bg-red-50 p-2 rounded border border-red-200">'+missingTables.join(', ')+'</div></div>';
        }
        
        // 缺失的列
        if(tables.length){
            var hasMissing = false;
            tables.forEach(function(t){
                if(t.missing_columns && t.missing_columns.length){
                    hasMissing = true;
                }
            });
            if(hasMissing){
                html += '<div class="mb-3"><div class="font-medium text-red-700 mb-1"><i class="fas fa-columns mr-1"></i>缺少的列</div>';
                html += '<div class="text-sm bg-red-50 p-2 rounded border border-red-200">';
                tables.forEach(function(t){
                    if(t.missing_columns && t.missing_columns.length){
                        html += '<div class="py-1"><span class="font-medium text-gray-800">'+t.table+'：</span>';
                        html += '<span class="text-red-600">'+t.missing_columns.join(', ')+'</span></div>';
                    }
                });
                html += '</div></div>';
            }
        }
        
        // 修复按钮
        html += '<div class="flex gap-2 mt-4">';
        html += '<button onclick="fixSchema()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm"><i class="fas fa-wrench mr-1"></i>一键修复</button>';
        html += '<button onclick="closeSchemaModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 text-sm">关闭</button>';
        html += '</div>';
    } else {
        // 没有问题，只显示关闭按钮
        html += '<div class="text-center mt-4">';
        html += '<button onclick="closeSchemaModal()" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">关闭</button>';
        html += '</div>';
    }
    
    $('#schema_content').html(html);
}

function fixSchema() {
    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>修复中...';
    
    $.ajax({
        url: 'ajax.php?act=fix_schema',
        type: 'POST',
        dataType: 'json',
        success: function(res) {
            btn.disabled = false;
            if(res.code === 1) {
                showToast('修复成功！', 'success');
                // 重新检测
                $('#check_schema').click();
            } else {
                showToast(res.msg || '修复失败', 'error');
                btn.innerHTML = '<i class="fas fa-wrench mr-1"></i>一键修复';
            }
        },
        error: function() {
            btn.disabled = false;
            showToast('网络错误', 'error');
            btn.innerHTML = '<i class="fas fa-wrench mr-1"></i>一键修复';
        }
    });
}

function closeSchemaModal() {
    $('#schema_modal').addClass('hidden');
}

// 导出导入功能
function showExportModal() {
    var biz = $('#bizFilter').val();
    $.get('?export_import_act=get_export_list', {biz: biz}, function(res) {
        if(res.code === 1) {
            var html = '';
            res.data.apis.forEach(function(api) {
                html += '<div class="flex items-center gap-2 py-1.5 border-b border-gray-100">' +
                    '<input type="checkbox" class="export-item" value="' + api.id + '">' +
                    '<span class="text-xs text-gray-700">' + (api.citybz || api.biz) + '</span>' +
                    '<span class="text-xs text-gray-400 ml-auto">' + api.type + '</span>' +
                    '</div>';
            });
            $('#exportList').html(html || '<p class="text-gray-500 text-sm">暂无数据</p>');
            $('#exportCount').text(0);
            
            $('.export-item').change(function() {
                $('#exportCount').text($('.export-item:checked').length);
            });
            
            new bootstrap.Modal(document.getElementById('exportModal')).show();
        } else {
            showToast(res.msg || '获取列表失败', 'error');
        }
    }, 'json');
}

function doExport() {
    var ids = [];
    $('.export-item:checked').each(function() {
        ids.push($(this).val());
    });
    
    if(ids.length === 0) {
        showToast('请选择要导出的接口', 'warning');
        return;
    }
    
    $.post('?export_import_act=export_config', {ids: ids}, function(res) {
        if(res.code === 1) {
            $('#exportResult').val(JSON.stringify(res.data, null, 2));
            bootstrap.Modal.getInstance(document.getElementById('exportModal')).hide();
            new bootstrap.Modal(document.getElementById('exportResultModal')).show();
        } else {
            showToast(res.msg || '导出失败', 'error');
        }
    }, 'json');
}

function copyExportResult() {
    var textarea = document.getElementById('exportResult');
    textarea.select();
    document.execCommand('copy');
    showToast('已复制到剪贴板', 'success');
}

function downloadExportResult() {
    var data = $('#exportResult').val();
    var blob = new Blob([data], {type: 'application/json'});
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'login_apis_' + new Date().toISOString().slice(0,10) + '.json';
    a.click();
    URL.revokeObjectURL(url);
    showToast('下载成功', 'success');
}

function showImportModal() {
    $.get('?export_import_act=get_login_class', function(res) {
        if(res.code === 1) {
            var cloudHtml = '<option value="0">默认分类</option>';
            res.data.cloud.forEach(function(c) {
                cloudHtml += '<option value="' + c.id + '">' + c.name + '</option>';
            });
            $('#importClassCloud').html(cloudHtml);
            
            var dgHtml = '<option value="0">默认分类</option>';
            res.data.dg.forEach(function(c) {
                dgHtml += '<option value="' + c.id + '">' + c.name + '</option>';
            });
            $('#importClassDg').html(dgHtml);
        }
    }, 'json');
    
    $('#importConfig').val('');
    $('#importFile').val('');
    new bootstrap.Modal(document.getElementById('importModal')).show();
}

function handleFileSelect(event) {
    var file = event.target.files[0];
    if(file) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#importConfig').val(e.target.result);
        };
        reader.readAsText(file);
    }
}

function doImport() {
    var config = $('#importConfig').val();
    if(!config) {
        showToast('请输入或上传配置', 'warning');
        return;
    }
    
    var data = {
        config: config,
        class_cloud: $('#importClassCloud').val(),
        class_dg: $('#importClassDg').val(),
        skip_exists: $('#importSkipExists').is(':checked') ? 1 : 0
    };
    
    $.post('?export_import_act=import_config', data, function(res) {
        if(res.code === 1) {
            bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
            showToast(res.msg, 'success');
        } else {
            showToast(res.msg || '导入失败', 'error');
        }
    }, 'json');
}
</script>

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