<?php
require_once __DIR__ . '/../MPHX/common.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$admin = is_admin_login();
$DB = $GLOBALS['DB'];

// 获取所有宝塔服务器
$bt_servers = $DB->get_all("SELECT * FROM `bt` ORDER BY `id` ASC");

// 页面类型配置
$page_types = [
    'default' => [
        'name' => '创建网站默认页面',
        'path' => '/www/server/panel/data/defaultDoc.html',
        'desc' => '新网站创建时显示的默认页面'
    ],
    '404' => [
        'name' => '404错误页面',
        'path' => '/www/server/panel/data/404.html',
        'desc' => '网站404错误时显示的页面'
    ],
    'stop' => [
        'name' => '网站停用提示页面',
        'path' => '/www/server/stop/index.html',
        'desc' => '网站被暂停后显示的提示页面'
    ]
];

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    $btid = intval($_POST['btid'] ?? 0);
    $type = $_POST['type'] ?? '';
    
    if ($btid <= 0) {
        exit(json_encode(['code' => 0, 'msg' => '请选择宝塔服务器']));
    }
    
    if (!isset($page_types[$type])) {
        exit(json_encode(['code' => 0, 'msg' => '无效的页面类型']));
    }
    
    $bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$btid}'");
    if (!$bt) {
        exit(json_encode(['code' => 0, 'msg' => '宝塔服务器不存在']));
    }
    
    // 初始化宝塔API
    $bt_api = new bt_api();
    $protocol = isset($bt['aqfw']) && $bt['aqfw'] == 'true' ? 'https' : 'http';
    $bt_api->BT_PANEL = $protocol . '://' . $bt['ip'] . ':' . $bt['dk'];
    $bt_api->BT_KEY = $bt['key'];
    
    $file_path = $page_types[$type]['path'];
    
    if ($action === 'get') {
        // 获取页面内容
        $result = $bt_api->GetFileContent($file_path);
        if (isset($result['status']) && $result['status'] === true) {
            exit(json_encode(['code' => 1, 'data' => $result['data']]));
        } else {
            exit(json_encode(['code' => 0, 'msg' => $result['msg'] ?? '获取失败']));
        }
        
    } elseif ($action === 'save') {
        // 保存页面内容
        $content = $_POST['content'] ?? '';
        $encoding = $_POST['encoding'] ?? 'utf-8';
        
        $result = $bt_api->SaveFileBody($file_path, $content, $encoding);
        if (isset($result['status']) && $result['status'] === true) {
            exit(json_encode(['code' => 1, 'msg' => '保存成功']));
        } else {
            exit(json_encode(['code' => 0, 'msg' => $result['msg'] ?? '保存失败']));
        }
    }
    
    exit(json_encode(['code' => 0, 'msg' => '未知操作']));
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>默认页面管理 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026042403">
    <style>
        .page-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 18px;
            padding-bottom: 14px;
            border-bottom: 1px solid #e8eaed;
        }
        .page-header h3 {
            color: #202124;
            font-size: 16px;
            font-weight: 500;
            margin: 0;
            display: flex;
            align-items: center;
        }
        .page-header h3 i {
            margin-right: 8px;
            color: #1a73e8;
        }
        .tab-nav-right {
            display: flex;
            align-items: center;
            gap: 8px;
            padding-right: 12px;
        }
        .tab-nav-right label {
            color: #5f6368;
            font-size: 14px;
            font-weight: 500;
            white-space: nowrap;
        }
        .tab-nav-right select {
            min-width: 180px;
            padding: 6px 10px;
            border: 1px solid #dadce0;
            border-radius: 6px;
            font-size: 13px;
            color: #202124;
            background: #fff;
            height: 36px;
        }
        .tab-nav-right select:focus {
            border-color: #1a73e8;
            outline: none;
        }
        .tab-nav { 
            display: flex; 
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e8eaed; 
            margin-bottom: 0;
            background: #f8f9fa;
            border-radius: 6px 6px 0 0;
            padding: 0 4px;
        }
        .tab-nav-left {
            display: flex;
        }
        .tab-item { 
            padding: 12px 20px; 
            cursor: pointer; 
            border-bottom: 2px solid transparent; 
            transition: all 0.2s; 
            color: #5f6368; 
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .tab-item:hover { 
            color: #1a73e8; 
            background: rgba(26, 115, 232, 0.04);
        }
        .tab-item.active { 
            color: #1a73e8; 
            border-bottom-color: #1a73e8; 
            font-weight: 500;
            background: #fff;
        }
        .tab-content-wrapper {
            background: #fff;
            border: 1px solid #e8eaed;
            border-top: none;
            border-radius: 0 0 6px 6px;
        }
        .tab-content { 
            display: none; 
            padding: 18px;
        }
        .tab-content.active { 
            display: block; 
        }
        .page-info-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #e8f0fe;
            border-left: 3px solid #1a73e8;
            padding: 10px 14px;
            margin-bottom: 14px;
            border-radius: 0 4px 4px 0;
        }
        .page-info-bar .info-text {
            font-size: 12px;
            color: #5f6368;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .page-info-bar .info-text i {
            color: #1a73e8;
        }
        .page-info-bar .file-path {
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 11px;
            color: #1a73e8;
            background: rgba(26, 115, 232, 0.1);
            padding: 2px 8px;
            border-radius: 3px;
        }
        .code-editor { 
            width: 100%; 
            min-height: 420px; 
            padding: 12px; 
            border: 1px solid #dadce0; 
            border-radius: 4px; 
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace; 
            font-size: 13px; 
            line-height: 1.6; 
            color: #202124; 
            background: #fff; 
            resize: vertical; 
        }
        .code-editor:focus { 
            border-color: #1a73e8; 
            outline: none; 
            box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.1);
        }
        .action-bar { 
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 14px;
            padding-top: 14px;
            border-top: 1px solid #e8eaed;
        }
        .action-bar .left-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .action-bar .right-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .encoding-select { 
            padding: 6px 10px; 
            border: 1px solid #dadce0; 
            border-radius: 4px; 
            font-size: 12px; 
            color: #202124; 
            background: #fff;
        }
        .encoding-select:focus { 
            border-color: #1a73e8; 
            outline: none; 
        }
        .preview-box { 
            border: 1px solid #dadce0; 
            border-radius: 6px; 
            margin-top: 16px; 
            background: #fff;
            overflow: hidden;
        }
        .preview-box .preview-header { 
            padding: 10px 14px; 
            border-bottom: 1px solid #e8eaed; 
            background: #f8f9fa; 
            font-weight: 500; 
            color: #202124; 
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .preview-box .preview-header i {
            color: #5f6368;
        }
        .preview-box iframe { 
            width: 100%; 
            height: 320px; 
            border: none; 
            background: #fff;
        }
        .alert { 
            padding: 12px 16px; 
            border-radius: 6px; 
            margin-bottom: 16px; 
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .alert-success { 
            background: #e6f4ea; 
            color: #137333; 
            border: 1px solid #ceead6; 
        }
        .alert-danger { 
            background: #fce8e6; 
            color: #c5221f; 
            border: 1px solid #fad2cf; 
        }
        .loading { 
            display: none; 
            text-align: center; 
            padding: 40px; 
            color: #5f6368;
        }
        .loading.show { 
            display: block; 
        }
        .loading i {
            font-size: 24px;
            margin-bottom: 10px;
            display: block;
        }
        
        /* 手机版响应式优化 */
        @media (max-width: 768px) {
            .tab-nav {
                flex-direction: column;
                align-items: stretch;
                padding: 0;
            }
            .tab-nav-left {
                display: flex;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                border-bottom: 1px solid #e8eaed;
            }
            .tab-item {
                padding: 12px 16px;
                font-size: 14px;
                white-space: nowrap;
                flex-shrink: 0;
            }
            .tab-nav-right {
                padding: 12px;
                border-bottom: 1px solid #e8eaed;
                background: #fff;
            }
            .tab-nav-right label {
                font-size: 14px;
            }
            .tab-nav-right select {
                min-width: 160px;
                flex: 0 0 auto;
                font-size: 13px;
                height: 36px;
                padding: 6px 10px;
            }
            .page-info-bar {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
            .page-info-bar .info-text {
                font-size: 14px;
            }
            .page-info-bar .file-path {
                font-size: 12px;
                word-break: break-all;
            }
            .action-bar {
                flex-direction: row;
                gap: 10px;
                align-items: center;
                flex-wrap: wrap;
                margin-top: 12px;
                padding-top: 12px;
                min-height: auto;
            }
            .action-bar .left-actions {
                gap: 10px;
            }
            .action-bar .right-actions {
                gap: 8px;
                margin-left: auto;
            }
            .action-bar label {
                font-size: 14px;
            }
            .action-bar .encoding-select {
                padding: 8px 12px;
                font-size: 14px;
                height: 40px;
            }
            .code-editor {
                min-height: 300px;
                font-size: 14px;
            }
            .tab-content {
                padding: 12px;
            }
        }
        
        @media (max-width: 767.98px) {
            .tab-content {
                padding: 10px;
            }
            .tab-item {
                padding: 10px 12px;
                font-size: 13px;
            }
            .tab-item i {
                margin-right: 4px;
            }
            .tab-nav-right label {
                font-size: 13px;
            }
            .tab-nav-right select {
                font-size: 13px;
                padding: 6px 10px;
                height: 36px;
                min-width: 160px;
            }
            .code-editor {
                min-height: 250px;
                font-size: 14px;
            }
            .action-bar {
                margin-top: 10px;
                padding-top: 10px;
                padding-bottom: 0;
                min-height: auto;
            }
            .action-bar .btn,
            .action-bar .btn.btn-primary,
            .action-bar .btn.btn-secondary {
                padding: 10px 16px !important;
                font-size: 14px !important;
                line-height: 1.4 !important;
                min-height: 44px !important;
                height: 44px !important;
                white-space: nowrap;
            }
            .action-bar .btn i,
            .action-bar .btn.btn-primary i,
            .action-bar .btn.btn-secondary i {
                margin-right: 3px !important;
                font-size: 10px !important;
            }
            .action-bar label {
                font-size: 8px;
            }
            .action-bar .encoding-select {
                padding: 2px 3px;
                font-size: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="content-area">
        <div class="page-header">
            <h3><i class="fas fa-file-code"></i> 默认页面管理</h3>
        </div>

        <div id="alertBox"></div>
        
        <div class="loading" id="loadingBox">
            <i class="fas fa-spinner fa-spin"></i>
            <div>正在加载数据...</div>
        </div>

        <div class="card" style="padding: 0; overflow: hidden;">
            <div class="tab-nav">
                <div class="tab-nav-left">
                    <div class="tab-item active" onclick="switchTab('default')">
                        <i class="fas fa-home"></i> 创建网站默认页面
                    </div>
                    <div class="tab-item" onclick="switchTab('404')">
                        <i class="fas fa-exclamation-circle"></i> 404错误页面
                    </div>
                    <div class="tab-item" onclick="switchTab('stop')">
                        <i class="fas fa-ban"></i> 网站停用提示页面
                    </div>
                </div>
                <div class="tab-nav-right">
                    <label><i class="fas fa-server"></i> 选择服务器</label>
                    <select id="serverSelect" class="server-select">
                        <option value="">请选择宝塔服务器</option>
                        <?php foreach ($bt_servers as $server): ?>
                        <option value="<?php echo $server['id']; ?>">
                            <?php echo htmlspecialchars($server['btmc'] ?? $server['ip']); ?> (<?php echo $server['ip']; ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="tab-content-wrapper">
                <?php foreach ($page_types as $key => $page): ?>
                <div class="tab-content <?php echo $key === 'default' ? 'active' : ''; ?>" id="tab-<?php echo $key; ?>">
                    <div class="page-info-bar">
                        <div class="info-text">
                            <i class="fas fa-info-circle"></i> 
                            <?php echo $page['desc']; ?>
                        </div>
                        <div class="file-path"><?php echo $page['path']; ?></div>
                    </div>
                    <textarea class="code-editor" id="content-<?php echo $key; ?>" placeholder="请输入HTML代码..."></textarea>
                    
                    <div class="action-bar">
                        <div class="left-actions">
                            <button class="btn btn-primary" onclick="saveContent()">
                                <i class="fas fa-save"></i> 保存修改
                            </button>
                            <button class="btn btn-secondary" onclick="loadContent()">
                                <i class="fas fa-sync"></i> 重新加载
                            </button>
                            <button class="btn btn-secondary" onclick="previewContent()">
                                <i class="fas fa-eye"></i> 预览
                            </button>
                        </div>
                        <div class="right-actions">
                            <label style="font-size: 12px; color: #5f6368;">编码：</label>
                            <select class="encoding-select" id="encodingSelect">
                                <option value="utf-8">UTF-8</option>
                                <option value="GBK">GBK</option>
                                <option value="GB2312">GB2312</option>
                                <option value="BIG5">BIG5</option>
                            </select>
                        </div>
                    </div>

                    <div class="preview-box" id="previewBox-<?php echo $key; ?>" style="display:none;">
                        <div class="preview-header">
                            <i class="fas fa-desktop"></i> 页面预览
                        </div>
                        <iframe id="previewFrame-<?php echo $key; ?>"></iframe>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <script src="/static/js/jquery.min.js"></script>
    <script>
        let currentType = 'default';

        function switchTab(type) {
            currentType = type;
            $('.tab-item').removeClass('active');
            $(`.tab-item[onclick="switchTab('${type}')"]`).addClass('active');
            $('.tab-content').removeClass('active');
            $(`#tab-${type}`).addClass('active');
            
            // 隐藏所有预览框
            $('.preview-box').hide();
            
            loadContent();
        }

        // 服务器选择变化时加载内容
        $('#serverSelect').change(function() {
            if ($(this).val()) {
                loadContent();
            }
        });

        // 加载内容
        function loadContent() {
            const btid = $('#serverSelect').val();
            if (!btid) {
                showAlert('请先选择宝塔服务器', 'danger');
                return;
            }

            $('#loadingBox').addClass('show');
            $('#alertBox').html('');

            $.ajax({
                url: 'default_pages.php',
                type: 'POST',
                data: {
                    action: 'get',
                    btid: btid,
                    type: currentType
                },
                success: function(res) {
                    $('#loadingBox').removeClass('show');
                    if (res.code === 1) {
                        $('#content-' + currentType).val(res.data);
                        showAlert('加载成功', 'success');
                    } else {
                        showAlert(res.msg || '加载失败', 'danger');
                    }
                },
                error: function() {
                    $('#loadingBox').removeClass('show');
                    showAlert('请求失败，请检查网络', 'danger');
                }
            });
        }

        // 保存内容
        function saveContent() {
            const btid = $('#serverSelect').val();
            if (!btid) {
                showAlert('请先选择宝塔服务器', 'danger');
                return;
            }

            const content = $('#content-' + currentType).val();
            if (!content.trim()) {
                showAlert('内容不能为空', 'danger');
                return;
            }

            if (!confirm('确定要保存修改吗？')) {
                return;
            }

            $('#loadingBox').addClass('show');
            $('#alertBox').html('');

            $.ajax({
                url: 'default_pages.php',
                type: 'POST',
                data: {
                    action: 'save',
                    btid: btid,
                    type: currentType,
                    content: content,
                    encoding: $('#encodingSelect').val()
                },
                success: function(res) {
                    $('#loadingBox').removeClass('show');
                    if (res.code === 1) {
                        showAlert(res.msg || '保存成功', 'success');
                    } else {
                        showAlert(res.msg || '保存失败', 'danger');
                    }
                },
                error: function() {
                    $('#loadingBox').removeClass('show');
                    showAlert('请求失败，请检查网络', 'danger');
                }
            });
        }

        // 预览内容
        function previewContent() {
            const content = $('#content-' + currentType).val();
            if (!content.trim()) {
                showAlert('内容不能为空', 'danger');
                return;
            }

            $(`#previewBox-${currentType}`).show();
            const frame = document.getElementById(`previewFrame-${currentType}`);
            frame.srcdoc = content;
        }

        // 显示提示
        function showAlert(msg, type) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const icon = type === 'success' ? 'check-circle' : 'exclamation-circle';
            $('#alertBox').html(`<div class="alert ${alertClass}"><i class="fas fa-${icon}"></i> ${msg}</div>`);
            setTimeout(function() {
                $('#alertBox').html('');
            }, 3000);
        }
    </script>
</body>
</html>
