<?php
// 关闭错误显示，避免错误信息破坏页面结构
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);
require_once __DIR__ . '/../MPHX/common.php';

// 尝试获取用户信息
$user = is_user_login();

// 如果用户未登录，跳转到登录页面
if (!$user) {
    header('Location: /user/login.php');
    exit;
}

// 获取宝塔面板信息
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 如果宝塔面板信息不存在，显示错误信息
if (!$bt) {
    die('宝塔服务器不存在');
}

$gn = isset($_GET['gn']) ? $_GET['gn'] : 'php';
?>

<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=20260220_4">

<script src="/static/js/jquery.min.js"></script>
<script src="https://lib.baomitu.com/layer/3.5.1/layer.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>

<?php if ($gn == 'php'): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-code"></i> PHP版本切换</h3>
    </div>
    
    <div class="card-body">
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i>
            切换PHP版本后，您的网站将立即使用新版本的PHP环境。请确保您的程序代码与选定的版本兼容。
        </div>
        
        <form id="phpForm">
            <div class="form-group">
                <label for="version">选择PHP版本</label>
                <select name="version" id="version" class="form-control" style="max-width: 300px;">
                    <option value="">请稍候...</option>
                </select>
            </div>
            
            <button type="button" class="btn btn-primary" data-action="setphp" disabled>
                <i class="fas fa-check"></i> 确认切换
            </button>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    // 检测已安装的PHP版本
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=checkphp',
        dataType: 'json',
        success: function(data) {
            if(data.code == 'success' && data.versions) {
                var select = $('#version');
                select.empty();
                
                // 只显示已安装的版本
                if(data.versions.installed && data.versions.installed.length > 0) {
                    data.versions.installed.forEach(function(version) {
                        var selected = data.selected_version && data.selected_version == version.value ? ' selected' : '';
                        select.append('<option value="' + version.value + '"' + selected + '>' + version.text + '</option>');
                    });
                } else {
                    select.append('<option value="">未检测到已安装的PHP版本</option>');
                }
                
                // 启用按钮
                $('button[data-action="setphp"]').prop('disabled', false);
            }
        },
        error: function() {
            console.log('PHP版本检测失败，请刷新页面重试');
        }
    });
});

function setphp(btn) {
    var $btn = $(btn);
    var originalText = $btn.html();
    $btn.addClass('btn-loading').prop('disabled', true);
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $('#phpForm').serialize() + '&egn=setphp',
        dataType: 'json',
        success: function(data) {
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            if(data.status) {
                layer.msg(data.msg || '设置成功');
                setTimeout(function(){ location.reload(); }, 1000);
            } else {
                layer.alert(data.msg || '设置失败');
            }
        },
        error: function(xhr) {
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            var msg = '操作失败，请重试';
            if (xhr.responseJSON && xhr.responseJSON.msg) {
                msg = xhr.responseJSON.msg;
            }
            layer.alert(msg);
        }
    });
}
</script>

<?php elseif ($gn == 'ym'): ?>

<div class="card">
    <div class="card-header">
        <h3 class="card-title"><?php echo L('domain_modify', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="form-group">
            <label class="font-weight-bold" id="parseLabel">服务器IP</label>
            <p class="text-muted small mb-2" id="parseDesc">将域名解析到以下IP地址</p>
            <div class="input-group">
                <input type="text" id="serverIP" class="form-control" value="加载中..." readonly>
                <div class="input-group-append">
                    <button type="button" class="btn btn-primary" data-action="copy-ip">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="font-weight-bold">添加域名</label>
            <form id="ymForm">
                <div class="input-group">
                    <input type="text" name="ym" id="ym" class="form-control" placeholder="example.com 或 *.example.com" required>
                    <div class="input-group-append">
                        <button type="button" class="btn btn-primary" data-action="add-domain">
                            <i class="fas fa-plus"></i> 添加
                        </button>
                    </div>
                </div>
                <small class="form-text text-muted">已绑定 <span id="currentCount">0</span> 个，<?php echo $user['yms'] > 0 ? '最多 ' . $user['yms'] . ' 个' : '不限制数量'; ?> | 支持主域名、二级域名和泛解析（如 blog.example.com, *.example.com）</small>
            </form>
        </div>

        <div class="mt-4">
            <label class="font-weight-bold">已绑定域名 <span class="text-muted small font-weight-normal">(<span id="domainCount">0</span>个)</span></label>
            <div id="domainList" class="table-responsive">
                <div class="text-center py-4 text-muted">加载中...</div>
            </div>
        </div>
    </div>
</div>


<script>
function copyIP() {
  const ip = document.getElementById('serverIP').value.trim();
  if (ip && ip !== '加载中...' && ip !== '获取失败') {
    navigator.clipboard.writeText(ip).then(function() {
      layer.msg('IP已复制');
    }).catch(function() {
      layer.msg('复制失败，请手动复制');
    });
  }
}

$(document).ready(function() {
    loadDomainList();
    
    // 事件代理：删除域名
    $(document).on('click', '.btn-delete-domain:not(#zmlList .btn-delete-domain)', function(e) {
        e.preventDefault();
        var domain = $(this).attr('data-name');
        var port = $(this).attr('data-port');
        if (!domain) return;
        delym(domain, port, loadDomainList);
    });

    $(document).on('click', '.delete-encrypt', function(e) {
        e.preventDefault();
        var path = $(this).attr('data-path');
        if (!path) return;
        deleteEncrypt(path);
    });

});

function loadDomainList() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=getymlist',
        dataType: 'json',
        beforeSend: function() {
            $('#domainList').html('<div class="text-center py-4 text-muted">加载中...</div>');
        },
        success: function(data) {
            console.log('域名列表API返回:', data);
            
            if (data.server_ip) {
                $('#serverIP').val(data.server_ip);
                // 根据返回的是IP还是域名，动态更新标签
                var isIP = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(data.server_ip);
                if (isIP) {
                    $('#parseLabel').text('服务器IP');
                    $('#parseDesc').text('将域名解析到以下IP地址');
                } else {
                    $('#parseLabel').text('解析地址');
                    $('#parseDesc').text('将域名解析到以下地址');
                }
            } else {
                $('#serverIP').val('获取失败');
            }

            if ((data.status === true || data.code === 'success') && Array.isArray(data.domains)) {
                var count = data.domains.length;
                $('#currentCount').text(count);
                $('#domainCount').text(count);

                    if (count > 0) {
                    var $table = $('<table class="table table-sm table-bordered mb-0"></table>');
                    var $thead = $('<thead class="thead-light"><tr>' +
                                   '<th style="width:40px;">#</th>' +
                                   '<th>域名</th>' +
                                   '<th style="width:80px;">端口</th>' +
                                   '<th style="width:140px;" class="text-right">操作</th>' +
                                   '</tr></thead>');
                    var $tbody = $('<tbody></tbody>');
                    data.domains.forEach(function(domain, idx) {
                        var name  = domain.name || domain.domain || '';
                        var port  = domain.port || 80;
                        var $tr   = $('<tr></tr>');
                        $tr.append('<td>' + (idx + 1) + '</td>');
                        var url = (port == 80 || port == 443) ? (port == 443 ? 'https://' : 'http://') + name : 'http://' + name + ':' + port;
                        $tr.append('<td><i class="fas fa-globe text-success mr-1"></i><a href="' + url + '" target="_blank" class="font-weight-bold text-decoration-none" title="点击访问">' + name + '</a></td>');
                        $tr.append('<td>' + port + '</td>');
                        var $ops = $('<td class="text-right"></td>');
                        var $delBtn = $('<button type="button" class="btn btn-danger btn-xs btn-delete-domain">' +
                                        '<i class="fas fa-trash"></i> 删除</button>');
                        $delBtn.attr('data-name', name);
                        $delBtn.attr('data-port', port);
                        $ops.append($delBtn);
                        $tr.append($ops);
                        $tbody.append($tr);
                    });
                    $table.append($thead).append($tbody);
                    $('#domainList').empty().append($table);
                } else {
                    $('#domainList').html('<div class="text-center py-5 text-muted"><i class="fas fa-globe fa-3x mb-3 d-block"></i>暂无绑定域名</div>');
                }
            } else {
                console.error('域名列表加载失败:', data);
                var $retryEl = $('<a href="#" class="btn btn-link btn-sm btn-retry">重试</a>');
                var errorMsg = '加载失败';
                if (data.msg) errorMsg += ': ' + data.msg;
                if (data.code && data.code !== 'success') errorMsg += ' (' + data.code + ')';
                $('#domainList').empty().append($('<div class="text-center py-4 text-muted"></div>').append(errorMsg + '，').append($retryEl));
            }
        },
        error: function(xhr) {
            console.error('域名列表请求失败:', xhr);
            var $retryEl2 = $('<a href="#" class="btn btn-link btn-sm btn-retry">重试</a>');
            $('#domainList').empty().append($('<div class="text-center py-4 text-muted"></div>').append('网络错误，').append($retryEl2));
            $('#serverIP').val('获取失败');
            console && console.error && console.error('loadDomainList error', xhr);
        }
    });

}

function setym(btn) {
    var $btn = $(btn);
    var originalText = $btn.text();
    $btn.text('添加中...').prop('disabled', true);
    
    // 验证域名格式（支持主域名和二级域名）
    var domain = $('#ym').val().trim();
    if (!domain) {
        layer.msg('请输入域名');
        $btn.text(originalText).prop('disabled', false);
        return;
    }
    // 域名格式验证：支持如 example.com, blog.example.com, *.example.com（泛解析）
    var domainRegex = /^(\*\.)?([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/i;
    if (!domainRegex.test(domain)) {
        layer.msg('域名格式不正确，请输入正确的域名（如 example.com, blog.example.com, *.example.com）');
        $btn.text(originalText).prop('disabled', false);
        return;
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $('#ymForm').serialize() + '&egn=setym',
        dataType: 'json',
        success: function(data) {
            console.log('添加域名API返回:', data);
            layer.close(ii);
            $btn.text(originalText).prop('disabled', false);
            if(data.status === true || data.code === 'success') {
                layer.msg(data.msg || '添加成功');
                $('#ym').val('');
                loadDomainList();
            } else {
                layer.alert(data.msg || data.code || '添加失败');
            }
        },
        error: function(xhr) {
            console.error('添加域名请求失败:', xhr);
            layer.close(ii);
            $btn.text(originalText).prop('disabled', false);
            var msg = '操作失败，请重试';
            if (xhr.responseJSON && xhr.responseJSON.msg) {
                msg = xhr.responseJSON.msg;
            }
            layer.alert(msg);
        }
    });
}

function delym(domain, port, callback) {
    layer.confirm('确定要删除域名 "' + domain + '" 吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: {
                action: 'delym',
                domain: domain,
                port: port
            },
            dataType: 'json',
            success: function(data) {
                console.log('删除域名API返回:', data);
                layer.close(ii);
                if(data.status === true || data.code === 'success') {
                    layer.msg(data.msg || '删除成功');
                    if (callback) {
                        callback();
                    } else {
                        loadDomainList();
                    }
                } else {
                    layer.alert(data.msg || data.code || '删除失败');
                }
            },
            error: function() {
                console.error('删除域名请求失败');
                layer.close(ii);
                layer.msg('删除失败，请重试');
            }
        });
    });
}

</script>

<?php elseif ($gn == 'zml'): ?>

<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?php echo L('subdirectory_binding', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="form-inline mb-3" style="font-size:13px;">
            <span class="font-weight-bold mr-2">域名</span>
            <input type="text" class="form-control form-control-sm mr-3" id="zmlDomain" placeholder="example.com 或 *.example.com">
            <span class="font-weight-bold mr-2">子目录</span>
            <select class="form-control form-control-sm mr-3" id="zmlDir" style="min-width:180px;">
                <option value="/">加载中...</option>
            </select>
            <button type="button" class="btn btn-primary btn-sm" id="btnAddZml">
                <i class="fas fa-plus"></i> 添加
            </button>
        </div>

        <div id="zmlList" class="table-responsive">
            <div class="text-center py-4 text-muted" style="font-size:13px;">
                <i class="fas fa-spinner fa-spin mr-1"></i> 加载中...
            </div>
        </div>

        <div class="d-flex align-items-center mt-3" style="font-size:13px;">
            <input type="checkbox" id="zmlSelectAll" class="mr-2">
            <select class="form-control form-control-sm mr-2" id="zmlBatchAction" style="width:180px;">
                <option value="">请选择批量操作</option>
                <option value="delete">批量删除</option>
            </select>
            <button type="button" class="btn btn-outline-primary btn-sm" id="btnZmlBatch">批量操作</button>
        </div>
    </div>
</div>

<!-- 复用上面的子目录绑定模态框 -->
<!-- 子目录绑定模态框 -->
<div class="modal fade" id="subdirModal" tabindex="-1" role="dialog" aria-labelledby="subdirModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="subdirModalLabel"><?php echo L('subdirectory_binding', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="subdirBindingId">
                <div class="form-group">
                    <label class="font-weight-bold">域名</label>
                    <input type="text" id="subdirDomain" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">当前绑定目录</label>
                    <input type="text" id="subdirCurrentPath" class="form-control" readonly>
                    <small class="form-text text-muted">为空或 "/" 表示绑定到网站根目录。</small>
                </div>
                <div class="form-group mb-1">
                    <label class="font-weight-bold">新的子目录名称</label>
                    <input type="text" id="subdirDirName" class="form-control" placeholder="例如：blog，不要带 /">
                    <small class="form-text text-muted">
                        - 只填写目录名，如 <code>blog</code>，不要写成 <code>/blog/</code>。<br>
                        - 设为空表示取消子目录绑定，回到根目录。
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" onclick="saveSubdirBinding(this)"><?php echo L('save', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<style>
    #zmlList table.domain-subdir-table th,
    #zmlList table.domain-subdir-table td {
        font-size: 13px;
        padding: 6px 8px;
        vertical-align: middle;
        white-space: nowrap;
    }
    #zmlList table.domain-subdir-table td code {
        font-size: 12px;
    }
</style>

<!-- 子目录伪静态模态框 -->
<div class="modal fade" id="rewriteModal" tabindex="-1" role="dialog" aria-labelledby="rewriteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rewriteModalLabel"><?php echo L('rewrite', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="rewriteBindId">
                <input type="hidden" id="rewriteDomain">
                <input type="hidden" id="rewritePath">
                <div class="form-group">
                    <label class="font-weight-bold">域名</label>
                    <input type="text" id="rewriteDomainDisplay" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">子目录</label>
                    <input type="text" id="rewritePathDisplay" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">选择伪静态规则</label>
                    <select class="form-control" id="rewriteSelect" onchange="changeRewrite(this)">
                        <option value="">请选择伪静态规则...</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">伪静态规则内容</label>
                    <textarea class="form-control" id="rewriteContent" rows="10" placeholder="请输入伪静态规则..."></textarea>
                    <small class="form-text text-muted">
                        支持Nginx伪静态规则。如：<code>location / { try_files $uri $uri/ /index.php$is_args$args; }</code>
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" onclick="saveSubdirRewrite(this)"><?php echo L('save', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>

function loadZmlPage() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=getdirbinding',
        dataType: 'json',
        success: function(data) {
            console.log('子目录绑定API返回:', data);
            
            // 直接使用返回的数据，不需要提取 data.data
            var apiData = data;
            
            // dirs 下拉列表
            var dirs = (apiData && Array.isArray(apiData.dirs)) ? apiData.dirs : [];
            
            // 如果dirs为空，从binding列表中提取目录
            var bindingList = (apiData && Array.isArray(apiData.binding)) ? apiData.binding : [];
            
            // 规范化 path 字段：确保所有路径都以 ../ 开头（除了根目录 /）
            bindingList = bindingList.map(function(item) {
                var path = item.path || '/';
                // 如果不是根目录，且不以 ../ 或 / 开头，则添加 ../
                if (path !== '/' && path.indexOf('../') !== 0 && path.indexOf('/') !== 0) {
                    item.path = '../' + path;
                }
                return item;
            });
            
            if (dirs.length === 0 && bindingList.length > 0) {
                bindingList.forEach(function(item) {
                    var path = item.path || '';
                    // 提取目录名：支持 ../qq 或 qq 格式
                    var dirName = path;
                    // 去掉 ../ 前缀
                    if (dirName.indexOf('../') === 0) {
                        dirName = dirName.substring(3);
                    }
                    // 去掉首尾斜杠
                    dirName = dirName.replace(/^\/+|\/+$/g, '');
                    if (dirName && dirs.indexOf(dirName) === -1) {
                        dirs.push(dirName);
                    }
                });
            }
            
            console.log('提取的目录列表:', dirs);
            console.log('规范化后的绑定列表:', bindingList);
            
            var $sel = $('#zmlDir');
            $sel.empty();
            dirs.forEach(function(d) {
                var val = (d === '/' ? '/' : String(d).replace(/^\/+|\/+$/g, ''));
                if (!val) val = '/';
                var text = (val === '/' ? '/' : val);
                $sel.append($('<option></option>').val(val === '/' ? '/' : val).text(text));
            });
            if (!$sel.find('option[value="/"]').length) {
                $sel.prepend($('<option></option>').val('/').text('/'));
            }

            // list 表格 - 子目录绑定列表
            renderZmlList(bindingList);
        },
        error: function(xhr) {
            console.error('子目录绑定请求失败:', xhr);
            $('#zmlList').html('<div class="text-center py-4 text-muted" style="font-size:13px;">加载失败</div>');
        }
    });
}

function renderZmlList(domains) {
    if (!Array.isArray(domains) || domains.length === 0) {
        $('#zmlList').html('<div class="text-center py-5 text-muted" style="font-size:13px;"><i class="fas fa-inbox fa-3x mb-3 d-block"></i>暂无数据</div>');
        return;
    }
    var $table = $('<table class="table table-sm table-bordered mb-0 domain-subdir-table"></table>');
    var $thead = $('<thead class="thead-light"><tr>' +
                   '<th style="width:40px;"><input type="checkbox" id="zmlCheckAll"></th>' +
                   '<th>域名</th>' +
                   '<th style="width:80px;">端口</th>' +
                   '<th style="width:100px;">子目录</th>' +
                   '<th style="width:80px;">伪静态</th>' +
                   '<th style="width:160px;" class="text-right">操作</th>' +
                   '</tr></thead>');
    var $tbody = $('<tbody></tbody>');
    domains.forEach(function(item) {
        var name  = item.name || item.domain || '';
        var port  = item.port || 80;
        var url = (port == 80 || port == 443) ? (port == 443 ? 'https://' : 'http://') + name : 'http://' + name + ':' + port;
        var path  = item.path || '/';
        var bindId = item.bind_id || item.id || '';
        var isBinding = !!bindId || item.is_binding === true;
        var showDir = (path && path !== '/' && path !== '../') ? path.replace(/^\.\.\//, '').replace(/^\/+|\/+$/g, '') : '/';
        var hasRewrite = item.has_rewrite === true || item.rewrite_content;
        var $tr = $('<tr></tr>');
        $tr.append('<td><input type="checkbox" class="zml-cb" data-name="' + name + '" data-port="' + port + '" data-bind-id="' + (bindId || '') + '" data-path="' + path + '"></td>');
        $tr.append('<td><a href="' + url + '" target="_blank" class="font-weight-bold text-decoration-none" title="点击访问">' + name + '</a></td>');
        $tr.append('<td>' + port + '</td>');
        $tr.append('<td><code class="mb-0">' + showDir + '</code></td>');
        // 伪静态列
        var rewriteStatus = hasRewrite ? '<span class="badge badge-success">已设置</span>' : '<span class="badge badge-secondary">未设置</span>';
        $tr.append('<td>' + rewriteStatus + '</td>');
        var $ops = $('<td class="text-right"></td>');
        var $btnSub = $('<button type="button" class="btn btn-outline-secondary btn-xs mr-2 btn-bind-subdir"><i class="fas fa-edit"></i> 修改</button>');
        $btnSub.attr('data-name', name).attr('data-path', path);
        if (isBinding && bindId) $btnSub.attr('data-bind-id', bindId);
        // 伪静态按钮
        var $btnRewrite = $('<button type="button" class="btn btn-outline-info btn-xs mr-2 btn-rewrite-subdir" title="设置伪静态"><i class="fas fa-magic"></i> 伪静态</button>');
        $btnRewrite.attr('data-name', name).attr('data-path', path);
        if (bindId) $btnRewrite.attr('data-bind-id', bindId);
        var $btnDel = $('<button type="button" class="btn btn-danger btn-xs btn-delete-domain"><i class="fas fa-trash"></i> 删除</button>');
        $btnDel.attr('data-name', name).attr('data-port', port);
        if (isBinding && bindId) $btnDel.attr('data-bind-id', bindId);
        $ops.append($btnSub).append($btnRewrite).append($btnDel);
        $tr.append($ops);
        $tbody.append($tr);
    });
    $table.append($thead).append($tbody);
    $('#zmlList').empty().append($table);

    $('#zmlCheckAll').off('change').on('change', function() {
        $('#zmlList .zml-cb').prop('checked', this.checked);
    });
}

function addZmlBinding() {
    var domain = $('#zmlDomain').val().trim();
    var dir = $('#zmlDir').val();
    if (!domain) {
        layer.msg('请输入域名', {icon: 2});
        return;
    }
    // 域名格式验证：支持如 example.com, blog.example.com, *.example.com（泛解析）
    var domainRegex = /^(\*\.)?([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/i;
    if (!domainRegex.test(domain)) {
        layer.msg('域名格式不正确，请输入正确的域名（如 example.com, blog.example.com, *.example.com）');
        return;
    }
    // 根目录：走添加域名
    if (!dir || dir === '/') {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: { egn: 'setym', ym: domain },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res && res.status) {
                    layer.msg(res.msg || '添加成功');
                    $('#zmlDomain').val('');
                    loadZmlPage();
                } else {
                    layer.alert((res && res.msg) ? res.msg : '添加失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('添加失败，请重试');
            }
        });
        return;
    }

    // 子目录：走子目录绑定
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'adddirbinding', domain: domain, dir: dir },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res && (res.status === true || res.code === 'success')) {
                layer.msg(res.msg || '绑定成功');
                $('#zmlDomain').val('');
                loadZmlPage();
            } else {
                layer.alert((res && (res.msg || res.code)) ? (res.msg || res.code) : '绑定失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('绑定失败，请重试');
        }
    });
}

function batchDeleteZml() {
    var action = $('#zmlBatchAction').val();
    if (action !== 'delete') return;
    var items = [];
    $('#zmlList .zml-cb:checked').each(function() {
        items.push({
            name: $(this).data('name'),
            port: $(this).data('port'),
            bindId: $(this).data('bind-id'),
            path: $(this).data('path')
        });
    });
    if (!items.length) {
        layer.msg('请先选择要操作的域名', {icon: 2});
        return;
    }
    layer.confirm('确定删除选中的 ' + items.length + ' 项？', {btn: ['确定', '取消']}, function() {
        var promises = items.map(function(it) {
            if (it.bindId) {
                return $.ajax({ type: 'POST', url: './api/api_router.php', data: { action: 'deldirbinding', id: it.bindId }, dataType: 'json' });
            }
            return $.ajax({ type: 'POST', url: './api/api_router.php', data: { action: 'delym', domain: it.name, port: it.port }, dataType: 'json' });
        });
        $.when.apply($, promises).always(function() {
            layer.closeAll();
            loadZmlPage();
        });
    });
}

$(document).ready(function() {
    loadZmlPage();
    $('#btnAddZml').on('click', addZmlBinding);
    $('#zmlDomain').on('keydown', function(e){ if (e.key === 'Enter') { e.preventDefault(); addZmlBinding(); }});
    $('#btnZmlBatch').on('click', batchDeleteZml);

    // 修改按钮：打开子目录绑定编辑模态框
    $(document).on('click', '#zmlList .btn-bind-subdir', function(e) {
        e.preventDefault();
        console.log('修改按钮点击事件触发');
        var name = $(this).data('name') || '';
        var path = $(this).data('path') || '/';
        var bindId = $(this).data('bind-id') || '';
        
        console.log('修改按钮数据:', {name: name, path: path, bindId: bindId});
        
        $('#subdirDomain').val(name);
        $('#subdirCurrentPath').val(path);
        $('#subdirDirName').val(path && path !== '/' && path !== '../' ? path.replace(/^\.\.\//, '').replace(/^\/+|\/+$/g, '') : '');
        $('#subdirBindingId').val(bindId);
        
        $('#subdirModal').modal('show');
    });

    // 删除按钮：根域名/子目录绑定都能删（根据 bind_id 判断）
    $(document).on('click', '#zmlList .btn-delete-domain', function(e) {
        e.preventDefault();
        console.log('删除按钮点击事件触发');
        var domain = $(this).attr('data-name');
        var port = $(this).attr('data-port');
        var bindId = $(this).attr('data-bind-id');
        console.log('删除按钮数据:', {domain: domain, port: port, bindId: bindId});
        if (bindId) {
            delDirBinding(bindId, loadZmlPage);
        } else {
            delym(domain, port, loadZmlPage);
        }
    });
});

// 删除子目录绑定（zml页面专用）
function delDirBinding(id, callback) {
    layer.confirm('确定要删除该子目录绑定吗？', {btn: ['确定', '取消']}, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: id },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '删除成功');
                    if (callback) {
                        callback();
                    } else {
                        loadZmlPage();
                    }
                } else {
                    layer.alert(res.msg || res.code || '删除失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('删除失败，请重试');
            }
        });
    });
}

// 删除域名（zml页面专用）
function delym(domain, port, callback) {
    layer.confirm('确定要删除域名 "' + domain + '" 吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: {
                action: 'delym',
                domain: domain,
                port: port
            },
            dataType: 'json',
            success: function(data) {
                console.log('删除域名API返回:', data);
                layer.close(ii);
                if(data.status === true || data.code === 'success') {
                    layer.msg(data.msg || '删除成功');
                    if (callback) {
                        callback();
                    } else {
                        loadZmlPage();
                    }
                } else {
                    layer.alert(data.msg || data.code || '删除失败');
                }
            },
            error: function() {
                console.error('删除域名请求失败');
                layer.close(ii);
                layer.msg('删除失败，请重试');
            }
        });
    });
}

// 保存子目录绑定（zml页面专用）
function saveSubdirBinding(btn) {
    var $btn = $(btn);
    var domain = $('#subdirDomain').val();
    var dirName = $('#subdirDirName').val().trim();
    var bindId = $('#subdirBindingId').val();

    // 空表示取消绑定，恢复根目录
    if (!dirName) {
        if (!bindId) {
            $('#subdirModal').modal('hide');
            return;
        }
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: bindId },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '已取消子目录绑定');
                    $('#subdirModal').modal('hide');
                    loadZmlPage();
                } else {
                    layer.alert(res.msg || res.code || '取消子目录绑定失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('取消子目录绑定失败，请重试');
            }
        });
        return;
    }

    // 规范目录名：只允许相对目录名，不带首尾 /
    dirName = dirName.replace(/^\/+|\/+$/g, '');

    var doAdd = function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'adddirbinding', domain: domain, dir: dirName },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.status === true || res.code === 'success') {
                    layer.msg(res.msg || '绑定成功');
                    $('#subdirModal').modal('hide');
                    loadZmlPage();
                } else {
                    layer.alert(res.msg || res.code || '绑定失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('绑定失败，请重试');
            }
        });
    };

    // 如果已有绑定，先删除再添加
    if (bindId) {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'deldirbinding', id: bindId },
            dataType: 'json',
            complete: function() {
                layer.close(ii);
                doAdd();
            }
        });
    } else {
        doAdd();
    }
}

// 获取子目录伪静态规则列表
var subdirRewriteRulesCache = null;

function getSubdirRewriteRules() {
    var $sel = $('#rewriteSelect');
    
    // 如果有缓存，直接使用
    if (subdirRewriteRulesCache && Array.isArray(subdirRewriteRulesCache)) {
        populateSubdirRewriteSelect(subdirRewriteRulesCache);
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getrewriterules',
        dataType: 'json',
        timeout: 30000, // 增加超时时间到30秒
        success: function(data) {
            console.log('获取伪静态规则列表返回：', data);
            if (data && data.code == 'success' && data.rules && Array.isArray(data.rules)) {
                subdirRewriteRulesCache = data.rules;
                populateSubdirRewriteSelect(data.rules);
            } else {
                $sel.html('<option value="">获取规则失败</option>');
            }
        },
        error: function() {
            console.log('获取伪静态规则列表失败');
            $sel.html('<option value="">获取规则失败</option>');
        }
    });
}

function populateSubdirRewriteSelect(rules) {
    var select = $('#rewriteSelect');
    select.empty();
    select.append('<option value="">请选择伪静态规则...</option>');
    
    // 兼容各种字段名
    rules.forEach(function(rule) {
        var name = rule.name || rule.title || rule.id || '';
        var content = rule.content || rule.data || rule.rule || '';
        if (name) {
            select.append($('<option>').val(name).text(name).data('content', content));
        }
    });
}

// 切换伪静态规则选择
function changeRewrite(sel) {
    var name = $(sel).val();
    if (!name) {
        return;
    }
    
    // 先检查缓存中是否有内容
    var $selected = $(sel).find('option:selected');
    var cachedContent = $selected.data('content');
    if (cachedContent) {
        $('#rewriteContent').val(cachedContent);
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'getrewritecontent', name: name },
        dataType: 'json',
        success: function(data) {
            console.log('获取伪静态规则内容返回：', data);
            // 兼容各种字段名
            var content = data.content || data.data || data.rule || '';
            if (content) {
                $('#rewriteContent').val(content);
                $selected.data('content', content); // 存入缓存
            }
        }
    });
}

// 打开子目录伪静态设置
$(document).on('click', '.btn-rewrite-subdir', function(e) {
    e.preventDefault();
    var name = $(this).data('name') || '';
    var path = $(this).data('path') || '/';
    var bindId = $(this).data('bind-id') || '';
    
    console.log('打开伪静态设置:', {name: name, path: path, bindId: bindId});
    
    $('#rewriteBindId').val(bindId);
    $('#rewriteDomain').val(name);
    $('#rewritePath').val(path);
    $('#rewriteDomainDisplay').val(name);
    $('#rewritePathDisplay').val(path && path !== '/' ? path.replace(/^\.\.\//, '') : '/');
    $('#rewriteContent').val('');
    $('#rewriteSelect').val('');
    
    // 获取伪静态规则列表
    getSubdirRewriteRules();
    
    // 获取当前子目录的伪静态规则
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: { action: 'getsubdirrewrite', domain: name, path: path },
        dataType: 'json',
        success: function(data) {
            console.log('获取子目录伪静态返回:', data);
            if (data && data.code == 'success' && data.content) {
                $('#rewriteContent').val(data.content);
            }
        }
    });
    
    $('#rewriteModal').modal('show');
});

// 保存子目录伪静态规则
function saveSubdirRewrite(btn) {
    var bindId = $('#rewriteBindId').val();
    var domain = $('#rewriteDomain').val();
    var path = $('#rewritePath').val();
    var content = $('#rewriteContent').val();
    
    if (!bindId) {
        layer.msg('请先绑定子目录再设置伪静态', {icon: 2});
        return;
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: JSON.stringify({ action: 'setsubdirrewrite', id: bindId, domain: domain, path: path, content: content }),
        dataType: 'json',
        contentType: 'application/json',
        success: function(res) {
            layer.close(ii);
            if (res && res.status) {
                layer.msg(res.msg || '保存成功', {icon: 1});
                $('#rewriteModal').modal('hide');
                loadZmlPage();
            } else {
                layer.alert((res && res.msg) ? res.msg : '保存失败');
            }
        },
        error: function(xhr, status, error) {
            layer.close(ii);
            layer.msg('保存失败：' + error, {icon: 2});
        }
    });
}
</script>

<?php elseif ($gn == 'pass'): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><?php echo L('access_restriction', 'menu'); ?></h3>
    </div>
    
    <div class="card-body">
        <ul class="nav nav-tabs mb-4" id="passTabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active font-weight-bold" data-toggle="tab" href="#encrypt" role="tab">加密访问</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" data-toggle="tab" href="#forbid" role="tab">限制访问</a>
            </li>
        </ul>
        
        <div class="tab-content">
            <!-- 加密访问 -->
            <div id="encrypt" class="tab-pane fade show active">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-2"></i>
                    此功能可以为网站的特定目录设置访问密码，只有输入正确密码的用户才能访问该目录。
                </div>
                
                <div class="mb-3">
                    <button type="button" class="btn btn-primary" data-action="show-add-encrypt">
                        <i class="fas fa-plus mr-1"></i> 添加加密访问
                    </button>
                </div>
                
                <div id="encryptList">
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-spinner fa-spin mr-2"></i> 加载中...
                    </div>
                </div>
            </div>
            
            <!-- 限制访问 -->
            <div id="forbid" class="tab-pane fade">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-2"></i>
                    此功能可以禁止访问指定的文件、目录或文件类型，访问时将返回403错误。
                </div>
                
                <div class="mb-3">
                    <button type="button" class="btn btn-primary" data-action="show-add-forbid">
                        <i class="fas fa-plus mr-1"></i> 添加限制访问
                    </button>
                </div>
                
                <div id="forbidList">
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-spinner fa-spin mr-2"></i> 加载中...
                    </div>
                </div>
            </div>
            
        </div>
    </div>
</div>

<style>
.nav-tabs .nav-link.active {
    background: transparent !important;
    border-bottom: 2px solid #188038 !important;
    color: #188038 !important;
}
.nav-tabs .nav-link:hover {
    border-color: transparent;
    color: #188038;
}
</style>

<!-- 添加加密访问模态框 -->
<div class="modal fade" id="addEncryptModal" tabindex="-1" role="dialog" aria-labelledby="addEncryptModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addEncryptModalLabel"><?php echo L('set_password', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="encryptForm">
                    <div class="form-group">
                        <label for="encryptPath">加密路径</label>
                        <input type="text" name="path" id="encryptPath" class="form-control" placeholder="如：/text/">
                    </div>
                    <div class="form-group">
                        <label for="encryptName">名称</label>
                        <input type="text" name="name" id="encryptName" class="form-control" placeholder="名称">
                    </div>
                    <div class="form-group">
                        <label for="encryptUsername">用户名</label>
                        <input type="text" name="username" id="encryptUsername" class="form-control" placeholder="请输入大于三位的用户名">
                    </div>
                    <div class="form-group">
                        <label for="encryptPassword">密码</label>
                        <input type="password" name="password" id="encryptPassword" class="form-control" placeholder="请输入3-12位密码">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" data-action="add-encrypt"><?php echo L('confirm', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<!-- 添加限制访问模态框 -->
<div class="modal fade" id="addForbidModal" tabindex="-1" role="dialog" aria-labelledby="addForbidModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addForbidModalLabel"><?php echo L('access_restriction', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="forbidForm">
                    <div class="form-group">
                        <label for="forbidName">名称</label>
                        <input type="text" name="name" id="forbidName" class="form-control allow-cn-input" placeholder="限制访问规则名称" lang="zh-CN" inputmode="text" required>
                    </div>
                    <div class="form-group">
                        <label>限制类型</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="forbidType" id="forbidTypePath" value="path" checked>
                            <label class="form-check-label" for="forbidTypePath">
                                路径/文件
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="forbidType" id="forbidTypeExt" value="ext">
                            <label class="form-check-label" for="forbidTypeExt">
                                文件后缀
                            </label>
                        </div>
                    </div>
                    <div class="form-group" id="forbidPathGroup">
                        <label for="forbidPath">路径/文件</label>
                        <input type="text" name="path" id="forbidPath" class="form-control" placeholder="如：/admin/ 或 /config.php">
                        <small class="form-text text-muted">目录请以 / 结尾，如：/admin/</small>
                    </div>
                    <div class="form-group" id="forbidExtGroup" style="display:none;">
                        <label for="forbidExt">文件后缀</label>
                        <input type="text" name="ext" id="forbidExt" class="form-control" placeholder="如：txt 或 txt|log|conf">
                        <small class="form-text text-muted">多个后缀用 | 分隔，如：txt|log|conf</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                <button type="button" class="btn btn-primary" data-action="add-forbid"><?php echo L('confirm', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
// 显示添加加密访问模态框
function showAddEncryptModal() {
    $('#addEncryptModal').modal('show');
}

// 绑定按钮点击事件
$(document).on('click', '[data-action]', function() {
    var action = $(this).data('action');
    var btn = this;
    
    switch(action) {
        case 'show-add-encrypt':
            showAddEncryptModal();
            break;
        case 'add-encrypt':
            addEncrypt();
            break;
        case 'show-add-forbid':
            showAddForbidModal();
            break;
        case 'add-forbid':
            addForbid();
            break;
        case 'set-mrwd':
            setmrwd(btn);
            break;
        case 'browse-directory':
            browseDirectory();
            break;
        case 'select-directory':
            selectCurrentDirectory();
            break;
        case 'set-yxml':
            setyxml(btn);
            break;
        case 'getBTRewriteRules':
            getBTRewriteRules();
            break;
        case 'set-wjt':
            setwjt(btn);
            break;
    }
});

// 页面加载时初始化
$(function() {
    console.log('[页面初始化] 开始');
    
    // 加载加密访问列表
    loadEncryptList();
    
    // 监听标签页切换事件 - 使用多种方式确保触发
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        console.log('[标签页切换] shown.bs.tab事件触发');
        var target = $(e.target).attr("href");
        console.log('[标签页切换] 目标:', target);
        if (target === '#forbid') {
            console.log('[标签页切换] 切换到限制访问标签，加载列表');
            loadForbidList();
        }
    });
    
    console.log('[页面初始化] 完成');
});

// 加载加密访问列表
function loadEncryptList() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=getencryptlist',
        dataType: 'json',
        success: function(data) {
            if (data.status && Array.isArray(data.list)) {
                var $table = $('<table class="table table-hover"></table>');
                $table.append('<thead class="thead-light"><tr><th>加密访问</th><th>名称</th><th>用户</th><th class="text-right">操作</th></tr></thead>');
                var $tbody = $('<tbody></tbody>');

                if (data.list.length > 0) {
                    data.list.forEach(function(item) {
                        var $tr = $('<tr></tr>');
                        $tr.append($('<td></td>').text(item.path || ''));
                        $tr.append($('<td></td>').text(item.name || ''));
                        $tr.append($('<td></td>').text(item.username || ''));
                        var $opTd = $('<td class="text-right"></td>');
                        var $btn = $('<button type="button" class="btn btn-danger btn-sm delete-encrypt">删除</button>');
                        $btn.attr('data-path', item.path);
                        $opTd.append($btn);
                        $tr.append($opTd);
                        $tbody.append($tr);
                    });
                } else {
                    $tbody.append('<tr><td colspan="4" class="text-center py-4 text-muted">暂无加密访问设置</td></tr>');
                }

                $table.append($tbody);
                $('#encryptList').html($table);
            } else {
                $('#encryptList').html('<div class="alert alert-danger">' + (data.msg || '加载失败') + '</div>');
            }
        },
        error: function(xhr) {
            $('#encryptList').html('<div class="alert alert-danger">加载失败，请刷新页面重试</div>');
            console && console.error && console.error('loadEncryptList error', xhr);
        }
    });
}

// 添加加密访问
function addEncrypt() {
    var path = $('#encryptPath').val();
    var name = $('#encryptName').val();
    var username = $('#encryptUsername').val();
    var password = $('#encryptPassword').val();
    
    if(!path) {
        layer.msg('请输入加密访问路径');
        return;
    }
    
    if(!name) {
        layer.msg('请输入名称');
        return;
    }
    
    if(username.length < 3) {
        layer.msg('用户名长度必须大于三位');
        return;
    }
    
    if(password.length < 3 || password.length > 12) {
        layer.msg('密码长度必须在3-12位之间');
        return;
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $('#encryptForm').serialize() + '&egn=addencrypt',
        dataType: 'json',
        success: function(data) {
            layer.close(ii);
            if(data.status) {
                layer.msg(data.msg || '添加成功');
                $('#addEncryptModal').modal('hide');
                $('#encryptPath').val('');
                $('#encryptName').val('');
                $('#encryptUsername').val('');
                $('#encryptPassword').val('');
                loadEncryptList();
            } else {
                layer.alert(data.msg || '添加失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误，请重试');
        }
    });
}

// 删除加密访问
function deleteEncrypt(path) {
    layer.confirm('确定要删除此加密访问吗？', {
        btn: ['确定', '取消'],
        title: '确认删除'
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'egn=deleteencrypt&path=' + encodeURIComponent(path),
            dataType: 'json',
            success: function(data) {
                layer.close(ii);
                if(data.status) {
                    layer.msg(data.msg || '删除成功');
                    loadEncryptList();
                } else {
                    layer.alert(data.msg || '删除失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('网络错误，请重试');
            }
        });
    });
}

// 显示添加限制访问模态框
function showAddForbidModal() {
    $('#addForbidModal').modal('show');
}

// 限制类型切换
$(document).on('change', 'input[name="forbidType"]', function() {
    if($(this).val() == 'path') {
        $('#forbidPathGroup').show();
        $('#forbidExtGroup').hide();
        $('#forbidExt').val('');
    } else {
        $('#forbidPathGroup').hide();
        $('#forbidExtGroup').show();
        $('#forbidPath').val('');
    }
});

// 加载限制访问列表
function loadForbidList() {
    console.log('[loadForbidList] 开始加载限制访问列表');
    
    // 防止重复加载
    if (loadForbidList.isLoading) {
        console.log('[loadForbidList] 正在加载中，跳过');
        return;
    }
    loadForbidList.isLoading = true;
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=getforbidlist',
        dataType: 'json',
        success: function(data) {
            console.log('[loadForbidList] 收到响应:', data);
            console.log('[loadForbidList] 响应类型:', typeof data);
            console.log('[loadForbidList] status:', data.status);
            console.log('[loadForbidList] list:', data.list);
            
            // 标记加载完成
            loadForbidList.isLoading = false;
            
            // 检查是否有错误
            if (data.status === false || data.status === 'false' || data.status === 0) {
                console.error('[loadForbidList] API返回错误:', data.msg);
                showForbidError(data.msg || data.code || '加载失败');
                return;
            }
            
            // 检查是否有list字段
            if (!data.list) {
                console.error('[loadForbidList] 响应中没有list字段');
                showForbidError('响应数据格式错误：缺少list字段');
                return;
            }
            
            // 检查list是否是数组
            if (!Array.isArray(data.list)) {
                console.error('[loadForbidList] list不是数组:', typeof data.list);
                showForbidError('响应数据格式错误：list不是数组');
                return;
            }
            
            // 渲染列表
            renderForbidList(data.list);
        },
        error: function(xhr, status, error) {
            console.error('[loadForbidList] AJAX错误:', status, error);
            console.error('[loadForbidList] XHR状态:', xhr.status);
            console.error('[loadForbidList] XHR响应:', xhr.responseText);
            showForbidError('加载失败，请刷新重试: ' + error);
            loadForbidList.isLoading = false;
        }
    });
}

// Task 8.1: Render forbid list with data clearing
function renderForbidList(list) {
    console.log('[renderForbidList] 渲染列表，共 ' + list.length + ' 项');
    
    // Clear existing content
    $('#forbidList').empty();
    
    // 去重：根据rule_id去重
    var uniqueList = [];
    var seen = {};
    list.forEach(function(item) {
        var key = item.rule_id || item.path || item.id;
        if (!seen[key]) {
            seen[key] = true;
            uniqueList.push(item);
        }
    });
    console.log('[renderForbidList] 去重后，共 ' + uniqueList.length + ' 项');
    
    var $table = $('<table class="table table-hover"></table>');
    $table.append('<thead class="thead-light"><tr><th>名称</th><th>保护的目录</th><th>规则</th><th class="text-right">操作</th></tr></thead>');
    var $tbody = $('<tbody></tbody>');

    if (uniqueList.length > 0) {
        uniqueList.forEach(function(item) {
            console.log('[renderForbidList] 处理项:', item);
            
            // Validate item has required fields
            if (!item.path && !item.ext) {
                console.warn('[renderForbidList] 跳过无效项:', item);
                return;
            }
            
            var $tr = $('<tr></tr>');
            
            // 名称列
            $tr.append($('<td></td>').text(item.name || item.rule_id || ''));
            
            // 保护的目录列
            var displayPath = item.display_path || '/';
            $tr.append($('<td></td>').text(displayPath));
            
            // 规则列（扩展名）
            var displayRule = item.display_rule || item.ext || '';
            $tr.append($('<td></td>').text(displayRule));
            
            // 操作列
            var $opTd = $('<td class="text-right"></td>');
            var $btn = $('<button type="button" class="btn btn-danger btn-sm delete-forbid">删除</button>');
            // 使用rule_id用于删除
            var idForDelete = item.rule_id || item.path;
            $btn.attr('data-id', idForDelete);
            $btn.attr('data-path', item.path);
            $opTd.append($btn);
            $tr.append($opTd);
            $tbody.append($tr);
        });
    } else {
        $tbody.append('<tr><td colspan="4" class="text-center py-4 text-muted">暂无限制访问设置</td></tr>');
    }

    $table.append($tbody);
    $('#forbidList').html($table);
    console.log('[renderForbidList] 表格已更新');
}

// Task 7.3: Show error helper function
function showForbidError(message) {
    console.error('[showForbidError]', message);
    $('#forbidList').html('<div class="alert alert-danger"><i class="fas fa-exclamation-triangle mr-2"></i>' + message + '</div>');
}

// 添加限制访问
function addForbid() {
    var name = $('#forbidName').val().trim();
    var type = $('input[name="forbidType"]:checked').val();
    var path = '';
    var ext = '';
    
    if(!name) {
        layer.msg('请输入名称');
        return;
    }
    
    if(type == 'path') {
        path = $('#forbidPath').val().trim();
        if(!path) {
            layer.msg('请输入路径或文件');
            return;
        }
    } else {
        ext = $('#forbidExt').val().trim();
        if(!ext) {
            layer.msg('请输入文件后缀');
            return;
        }
    }
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: 'egn=addforbid&name=' + encodeURIComponent(name) + '&path=' + encodeURIComponent(path) + '&ext=' + encodeURIComponent(ext),
        dataType: 'json',
        success: function(data) {
            layer.close(ii);
            if(data.status) {
                layer.msg(data.msg || '添加成功');
                $('#addForbidModal').modal('hide');
                $('#forbidName').val('');
                $('#forbidPath').val('');
                $('#forbidExt').val('');
                $('input[name="forbidType"][value="path"]').prop('checked', true).trigger('change');
                loadForbidList();
            } else {
                layer.alert(data.msg || '添加失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误，请重试');
        }
    });
}

// 删除限制访问
function deleteForbid(path) {
    layer.confirm('确定要删除此限制访问吗？', {
        btn: ['确定', '取消'],
        title: '确认删除'
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'egn=deleteforbid&path=' + encodeURIComponent(path),
            dataType: 'json',
            success: function(data) {
                layer.close(ii);
                if(data.status) {
                    layer.msg(data.msg || '删除成功');
                    loadForbidList();
                } else {
                    layer.alert(data.msg || '删除失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('网络错误，请重试');
            }
        });
    });
}

// 删除限制访问按钮事件
$(document).on('click', '.delete-forbid', function() {
    var ruleId = $(this).data('id');
    var path = $(this).data('path');
    deleteForbid(ruleId || path);
});

</script>

<?php elseif ($gn == 'mrwd'): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?php echo L('default_doc', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="alert alert-info d-flex align-items-center mb-4">
            <i class="fas fa-info-circle mr-2"></i>
            <div>设置网站的默认访问文档，支持多个文档，按优先级排序。</div>
        </div>
        <form id="mrwdForm">
            <div class="form-group mb-4">
                <label class="font-weight-bold" for="index">默认文档 (每行一个)</label>
                <textarea name="index" id="index" class="form-control text-monospace" rows="8" placeholder="index.php
index.html
index.htm">index.html
index.php
index.htm
default.html
default.php</textarea>
            </div>
            <button type="button" class="btn btn-success" data-action="set-mrwd">
                <i class="fas fa-check mr-1"></i> 确认修改
            </button>
        </form>
    </div>
</div>

<script>
// 页面加载完成后获取当前默认文档设置
$(document).ready(function() {
    loadCurrentIndex();
});

// 获取服务器中已有的默认文档设置
function loadCurrentIndex() {
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getmrwd',
        dataType: 'json',
        success: function(data) {
            if(data.code == 'success' && data.index) {
                $('#index').val(data.index);
            }
        },
        error: function(xhr, status, error) {
            console && console.error && console.error('loadCurrentIndex error', status, error);
        }
    });
}

function setmrwd(btn) {
    var $btn = $(btn);
    var originalHtml = $btn.html();
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 处理中...');
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $('#mrwdForm').serialize() + '&egn=setmrwd',
        dataType: 'json',
        success: function(data) {
            layer.close(ii);
            $btn.prop('disabled', false).html(originalHtml);
            if(data.status) {
                layer.msg(data.msg || '修改成功');
                setTimeout(function(){ location.reload(); }, 1000);
            } else {
                layer.msg(data.msg || '修改失败');
            }
        },
        error: function() {
            layer.close(ii);
            $btn.prop('disabled', false).html(originalHtml);
            layer.msg('网络错误，请重试');
        }
    });
}
</script>

<?php elseif ($gn == 'yxml'):?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><?php echo L('run_dir', 'menu'); ?></h3>
    </div>
    <div class="card-body">
        <div class="alert alert-info d-flex align-items-center mb-4">
            <i class="fas fa-info-circle mr-2"></i>
            <div>设置网站的运行目录，通常用于 Laravel, ThinkPHP 等框架项目。</div>
        </div>
        <form id="yxmlForm">
            <div class="form-group mb-4">
                <label class="font-weight-bold" for="rundir">运行目录</label>
                <div class="input-group">
                    <input type="text" name="rundir" id="rundir" class="form-control" placeholder="/" value="/">
                    <div class="input-group-append">
                        <button type="button" class="btn btn-outline-secondary" data-action="browse-directory">
                            <i class="fas fa-folder-open mr-1"></i> 浏览
                        </button>
                    </div>
                </div>
            </div>
            <button type="button" class="btn btn-success" data-action="set-yxml">
                <i class="fas fa-check mr-1"></i> 确认设置
            </button>
        </form>
    </div>
</div>

<!-- 目录浏览模态框 -->
<div class="modal fade" id="directoryModal" tabindex="-1" role="dialog" aria-labelledby="directoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="directoryModalLabel"><?php echo L('file_manager', 'menu'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb bg-light" id="directoryBreadcrumb">
                        <li class="breadcrumb-item"><a href="#" data-path="/">/</a></li>
                    </ol>
                </nav>
                <div class="list-group" id="directoryList" style="max-height: 400px; overflow-y: auto;">
                    <div class="text-center p-4">
                        <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
                        <div class="text-muted">加载中...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" data-action="select-directory">选择当前目录</button>
            </div>
        </div>
    </div>
</div>

<style>
#directoryList .directory-item {
    cursor: pointer;
    transition: background-color 0.2s;
}
#directoryList .directory-item:hover {
    background-color: #f8f9fa;
}
#directoryList .directory-item i {
    color: #ffc107;
}
</style>

<script>
// 页面加载完成后获取当前运行目录设置
$(document).ready(function() {
    loadCurrentRunDir();
});

// 获取服务器中已有的运行目录设置
function loadCurrentRunDir() {
    console.log('加载当前运行目录设置开始');
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getyxml',
        dataType: 'json',
        success: function(data) {
            console.log('加载当前运行目录设置成功，返回数据:', data);
            if(data.code == 'success' && data.rundir) {
                $('#rundir').val(data.rundir);
                console.log('设置当前运行目录设置成功:', data.rundir);
            } else {
                console.log('加载当前运行目录设置失败，错误信息:', data.code);
            }
        },
        error: function(xhr, status, error) {
            console.log('加载当前运行目录设置AJAX错误:', status, error);
        }
    });
}

var currentDirectory = '/';

function browseDirectory() {
    currentDirectory = '/';
    loadDirectory(currentDirectory);
    $('#directoryModal').modal('show');
}

function loadDirectory(path) {
    currentDirectory = path;
    $('#directoryList').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>');
    
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getdirectory&path=' + encodeURIComponent(path),
        dataType: 'json',
        success: function(data) {
            console.log('加载目录响应:', data);
            if (data.status === true && data.files && Array.isArray(data.files)) {
                // 过滤出目录
                var directories = data.files.filter(function(f) { return f.is_dir === true || f.type === 'dir'; });
                if (directories.length > 0) {
                    var $container = $('<div></div>');
                    directories.forEach(function(dir) {
                        var $a = $('<a href="#" class="list-group-item list-group-item-action directory-item"></a>');
                        $a.data('path', dir.path);
                        $a.append('<i class="fas fa-folder mr-2"></i> ');
                        $a.append(document.createTextNode(dir.name || dir.path.split('/').pop() || ''));
                        // 点击目录项进入子目录
                        $a.on('click', function(e) {
                            e.preventDefault();
                            var path = $(this).data('path');
                            console.log('点击目录:', path);
                            loadDirectory(path);
                        });
                        $container.append($a);
                    });
                    $('#directoryList').empty().append($container);
                } else {
                    $('#directoryList').html('<div class="list-group-item text-center text-muted">当前目录为空</div>');
                }
                updateBreadcrumb(path);
            } else {
                $('#directoryList').html('<div class="list-group-item text-center text-danger">' + (data.msg || data.code || '加载失败') + '</div>');
            }
        },
        error: function(xhr) {
            $('#directoryList').html('<div class="list-group-item text-center text-danger">加载失败，请重试</div>');
            console && console.error && console.error('loadDirectory error', xhr);
        }
    });
}

function navigateToDirectory(path) {
    loadDirectory(path);
}

function updateBreadcrumb(path) {
    var parts = path.split('/').filter(function(part) { return part !== ''; });
    var $bc = $('<div></div>');
    var $root = $('<a href="#" class="breadcrumb-item" data-path="/">/</a>');
    $root.on('click', function(e) {
        e.preventDefault();
        loadDirectory('/');
    });
    $bc.append($root);
    var currentPath = '/';

    parts.forEach(function(part) {
        currentPath += part + '/';
        var $a = $('<a href="#" class="breadcrumb-item"></a>');
        $a.text(part);
        $a.attr('data-path', currentPath);
        $a.on('click', function(e) {
            e.preventDefault();
            loadDirectory(currentPath);
        });
        $bc.append($a);
    });

    $('#directoryBreadcrumb').html($bc.children());
}

// 目录选择：将当前目录应用到输入框并关闭模态框
function selectCurrentDirectory() {
    try {
        if (typeof currentDirectory !== 'undefined') {
            $('#rundir').val(currentDirectory);
        }
        $('#directoryModal').modal('hide');
    } catch (e) {
        console && console.error && console.error('selectCurrentDirectory error', e);
    }
}

// 保存运行目录
function setyxml(btn) {
    console.log('setyxml函数被调用');
    var $btn = $(btn);
    var originalText = $btn.html();
    var rundir = $('#rundir').val();
    console.log('rundir值:', rundir);
    
    $btn.addClass('btn-loading').prop('disabled', true);

    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=setyxml&rundir=' + encodeURIComponent(rundir),
        dataType: 'json',
        success: function(data) {
            console.log('保存响应数据:', data);
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            if (data.status) {
                layer.msg(data.msg || '设置成功');
                setTimeout(function(){ location.reload(); }, 1000);
            } else {
                layer.alert(data.msg || '设置失败');
            }
        },
        error: function(xhr, status, error) {
            console.log('保存失败:', status, error);
            layer.close(ii);
            $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
            layer.msg('网络错误，请重试');
        }
    });
}

// 兼容性：有些按钮使用驼峰或短横混合命名，确保 set-yxml 也能被代理处理
$(document).on('click', '[data-action="set-yxml"]', function(e){ e.preventDefault(); setyxml(this); });

</script>

<?php elseif ($gn == 'wjt'): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-magic"></i> 设置伪静态</h3>
    </div>
    
    <div class="card-body">
        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i>
            快速选择常用规则，或手动编辑下方内容。
        </div>
        
        <div class="row">
            <div class="col-md-5">
                <div class="form-group">
                    <label>常用规则列表</label>
                    <input type="text" id="ruleSearch" class="form-control mb-2" placeholder="搜索规则...">
                    <select id="rewrite" class="form-control" size="8" style="height: auto;">
                        <option value="default">正在加载规则列表...</option>
                    </select>
                    <div class="mt-2 text-right">
                        <button type="button" class="btn btn-light btn-sm" data-action="getBTRewriteRules">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                </div>
            </div>
            <div class="col-md-7">
                <div class="form-group">
                    <label for="content">规则内容编辑</label>
                    <div class="text-right mb-2">
                        <button type="button" class="btn btn-light btn-sm" onclick="copyContent()">
                            <i class="fas fa-copy"></i> 复制
                        </button>
                        <button type="button" class="btn btn-light btn-sm" onclick="clearContent()">
                            <i class="fas fa-eraser"></i> 清空
                        </button>
                    </div>
                    <textarea id="content" class="form-control" rows="12" placeholder="在此输入规则..." style="height: 280px; font-family: monospace;"></textarea>
                </div>
                
                <div class="text-right mt-3">
                    <button type="button" class="btn btn-primary" data-action="set-wjt">
                        <i class="fas fa-save"></i> 保存设置
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // 页面加载时自动获取规则列表
    getBTRewriteRules();
    
    // 获取当前正在使用的伪静态规则内容
    loadCurrentRewrite();

    // 监听规则选择变化
    $('#rewrite').on('change', function() {
        var $selected = $(this).find('option:selected');
        var name = $selected.val();
        var content = $selected.data('content');
        
        if (content) {
            $('#content').val(content);
        } else if (name && name !== 'default') {
            // 如果内容为空且不是默认项，尝试从后端获取
            var $textarea = $('#content');
            var originalVal = $textarea.val();
            $textarea.val('正在加载规则内容...').prop('disabled', true);
            
            $.ajax({
                type: 'POST',
                url: './api/api_router.php',
                data: { action: 'getrewritecontent', name: name },
                dataType: 'json',
                success: function(res) {
                    if (res && res.code === 'success' && res.content) {
                        $selected.data('content', res.content); // 存入缓存
                        $textarea.val(res.content);
                    } else {
                        $textarea.val(originalVal);
                        layer.alert('获取规则内容失败');
                    }
                },
                error: function() {
                    $textarea.val(originalVal);
                    layer.alert('网络错误，获取规则内容失败');
                },
                complete: function() {
                    $textarea.prop('disabled', false);
                }
            });
        }
    });

    // 搜索功能
    $('#ruleSearch').on('input', function() {
        var val = $(this).val().toLowerCase();
        $('#rewrite option').each(function() {
            var text = $(this).text().toLowerCase();
            if (text.indexOf(val) > -1 || $(this).val() === 'default') {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
});

// 快速应用规则
function applyQuickRule(name) {
    var $select = $('#rewrite');
    var $opt = $select.find('option[value="' + name + '"]');
    if ($opt.length) {
        $select.val(name).trigger('change');
        // 滚动到选中项
        $opt[0].scrollIntoView({ block: 'nearest' });
    } else {
        // 如果列表中没有，尝试直接请求
        var $textarea = $('#content');
        $textarea.val('正在加载规则内容...').prop('disabled', true);
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: { action: 'getrewritecontent', name: name },
            dataType: 'json',
            success: function(res) {
                if (res && res.code === 'success' && res.content) {
                    $textarea.val(res.content);
                } else {
                    layer.alert('获取规则内容失败');
                }
            },
            error: function() {
                layer.alert('网络错误');
            },
            complete: function() {
                $textarea.prop('disabled', false);
            }
        });
    }
}

// 复制代码
function copyContent() {
    var content = $('#content').val();
    if (!content) return;
    var $temp = $('<textarea>');
    $('body').append($temp);
    $temp.val(content).select();
    document.execCommand('copy');
    $temp.remove();
    layer.msg('已复制到剪贴板');
}

// 清空代码
function clearContent() {
    layer.confirm('确定要清空当前规则内容吗？清空后将保存到服务器。', {
        btn: ['确定', '取消']
    }, function() {
        // 自动保存空规则到服务器
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            type: 'POST',
            url: './api/api_router.php',
            data: {
                action: 'setwjt',
                rewrite: 'default',
                content: ''
            },
            dataType: 'json',
            timeout: 30000,
            success: function(data) {
                layer.close(ii);
                if (data && data.code == 'success') {
                    // 清空文本框
                    $('#content').val('');
                    layer.msg('已清空并保存');
                } else {
                    layer.msg(data.code || '保存失败');
                }
            },
            error: function(xhr, status, error) {
                layer.close(ii);
                layer.msg('网络错误，请重试');
                console.error('清空保存失败:', status, error);
            }
        });
    });
}

// 缓存已获取的规则，避免重复请求
var rewriteRulesCache = null;

// 绑定相关按钮点击事件
$(document).on('click', '[data-action="getBTRewriteRules"]', function(e){
    e.preventDefault();
    getBTRewriteRules(this);
});
$(document).on('click', '[data-action="set-wjt"]', function(e){ e.preventDefault(); setwjt(this); });

function loadCurrentRewrite() {
    console.log('[loadCurrentRewrite] 开始获取当前伪静态');
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getcurrentrewrite',
        dataType: 'json',
        success: function(data) {
            console.log('[loadCurrentRewrite] 返回数据:', data);
            if (data && data.code == 'success' && data.rule) {
                // 如果内容存在则显示，否则清空（表示没有设置伪静态）
                var content = data.rule.content || '';
                console.log('[loadCurrentRewrite] 设置内容:', content);
                $('#content').val(content);
            } else {
                console.log('[loadCurrentRewrite] 未获取到规则数据');
            }
        },
        error: function(xhr, status, error) {
            console && console.error && console.error('[loadCurrentRewrite] error', status, error);
        }
    });
}

// 获取宝塔面板的伪静态规则
function getBTRewriteRules(btn) {
    var $btn = btn ? $(btn) : $('[data-action="getBTRewriteRules"]').first();
    if ($btn.data('loading')) return; // 防止重复点击
    $btn.data('loading', true);
    var originalHtml = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i> 获取中...').prop('disabled', true);

    // 如果有缓存，直接使用并跳过网络请求
    if (rewriteRulesCache && Array.isArray(rewriteRulesCache)) {
        try {
            populateRewriteSelect(rewriteRulesCache);
        } finally {
            $btn.data('loading', false).html(originalHtml).prop('disabled', false);
        }
        return;
    }

    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: 'action=getrewriterules',
        dataType: 'json',
        timeout: 30000, // 增加超时时间到30秒
        success: function(data) {
            console.log('获取宝塔面板的伪静态规则返回：', data);
            if (data && data.code == 'success' && data.rules && Array.isArray(data.rules)) {
                rewriteRulesCache = data.rules; // 缓存
                populateRewriteSelect(data.rules);
            } else {
                var msg = (data && data.code) ? data.code : '获取规则失败';
                console && console.error && console.error('获取宝塔面板的伪静态规则失败，返回：', data);
                // 不弹窗，直接在下拉框显示错误
                $('#rewrite').html('<option value="default">' + msg + '</option>');
            }
        },
        error: function(xhr, status, error) {
            var msg = (status === 'timeout') ? '请求超时，请稍后再试' : '获取规则失败';
            $('#rewrite').html('<option value="default">' + msg + '</option>');
            console && console.error && console.error('getBTRewriteRules AJAX error', status, error, xhr);
        },
        complete: function() {
            $btn.data('loading', false).html(originalHtml).prop('disabled', false);
        }
    });
}

function populateRewriteSelect(rules) {
    try {
        var select = $('#rewrite');
        select.empty();
        // 添加默认项
        select.append($('<option>').val('default').text('默认').data('content', ''));
        // 兼容各种字段名（content/rule/body/value）
        rules.forEach(function(rule) {
            var name = rule.name || rule.title || rule.id || '';
            var content = rule.content || rule.rule || rule.body || rule.value || '';
            // 保证 name 至少有值
            var displayName = name || (content ? 'rule-' + Math.random().toString(36).substr(2,6) : '未命名');
            var $opt = $('<option>').val(displayName).text(displayName).data('content', content);
            select.append($opt);
        });

        // 触发 change 事件以更新内容（如果当前没内容）
        if (!$('#content').val()) {
            select.trigger('change');
        }
    } catch (e) {
        console && console.error && console.error('populateRewriteSelect error', e);
    }
}

// 设置伪静态（提交）函数
function setwjt(btn) {
    var $btn = $(btn);
    var originalHtml = $btn.html();
    if ($btn.data('loading')) return; // 已在提交中
    $btn.data('loading', true).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 提交中...');

    var rewrite = $('#rewrite').val() || '';
    var content = $('#content').val() || '';

    var payload = { action: 'setwjt', rewrite: rewrite, content: content };

    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        type: 'POST',
        url: './api/api_router.php',
        data: payload,
        dataType: 'json',
        timeout: 30000,
        success: function(data) {
            layer.close(ii);
            try {
                // 支持两种返回格式：code: 'success' 或 status: true
                var isSuccess = (data.code === 'success') || (data.status === true);
                if (isSuccess) {
                    layer.msg(data.msg || '保存成功');
                    setTimeout(function(){ location.reload(); }, 1000);
                    return;
                }
                var msg = data.msg || data.code || '设置失败';
                layer.alert(msg);
            } catch (e) {
                console && console.error && console.error('setwjt success handler error', e);
                layer.msg('操作完成');
            }
        },
        error: function(xhr, status, err) {
            layer.close(ii);
            if (status === 'timeout') {
                layer.msg('请求超时，请稍后再试');
            } else {
                layer.msg('网络错误，请重试');
            }
            console && console.error && console.error('setwjt AJAX error', status, err, xhr);
        },
        complete: function() {
            $btn.data('loading', false).prop('disabled', false).html(originalHtml);
        }
    });
}
</script>

<?php elseif ($gn == 'ssl'): ?>
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><?php echo L('ssl', 'menu'); ?></h3>
    </div>

    <div class="card-body">
        <ul class="nav nav-tabs mb-4" id="sslTabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="ssl-status-tab" data-toggle="tab" href="#ssl-status" role="tab">当前证书</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="ssl-list-tab" data-toggle="tab" href="#ssl-list" role="tab" onclick="loadSSLCertList()">证书列表</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="ssl-apply-tab" data-toggle="tab" href="#ssl-apply" role="tab">申请证书</a>
            </li>
        </ul>

        <div class="tab-content" id="sslTabsContent">
            <!-- SSL部署 -->
            <div class="tab-pane fade show active" id="ssl-status" role="tabpanel">
                <!-- 状态提示栏 -->
                <div id="sslStatusGuide" class="alert alert-warning align-items-center justify-content-between mb-4 d-none">
                    <div>
                        <div id="sslStatusTitle" class="font-weight-bold mb-1">网站未开启HTTPS，站点访问可能存在风险</div>
                        <div id="sslStatusDesc" class="small opacity-80">建议立即开启HTTPS保护您的网站</div>
                    </div>
                    <button type="button" class="btn btn-success btn-sm" onclick="$('#sslKey').focus()">
                        <i class="fas fa-shield-alt"></i> 前往开启
                    </button>
                </div>

                <div class="mb-4">
                    <div class="d-flex align-items-center mb-3">
                        <i class="fas fa-shield-alt text-success mr-2"></i>
                        <h5 class="mb-0">当前证书 - [<span id="sslStatusText" class="text-muted">正在获取...</span>]</h5>
                    </div>
                    
                    <div class="row bg-light rounded p-3 mx-0">
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">证书分类</div>
                            <div id="sslCertType" class="font-weight-bold">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">证书品牌</div>
                            <div id="sslCertBrand" class="font-weight-bold">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3 mb-md-0">
                            <div class="small text-muted mb-1">认证域名</div>
                            <div id="sslCertDomains" class="font-weight-bold text-truncate" title="">-</div>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <div class="small text-muted mb-1">到期时间</div>
                            <div id="sslCertExpiry" class="font-weight-bold">-</div>
                        </div>
                    </div>

                    <div class="mt-3 d-flex align-items-center">
                        <span class="mr-3 font-weight-bold">强制HTTPS</span>
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="forceHttpsSwitch" onchange="toggleForceHttps(this)">
                            <label class="custom-control-label" for="forceHttpsSwitch"></label>
                        </div>
                    </div>
                </div>
                
                <!-- 证书内容区域 -->
                <div class="row mb-4">
                    <div class="col-md-6 form-group">
                        <label class="font-weight-bold">密钥(KEY)</label>
                        <textarea class="form-control text-monospace small" id="sslKey" style="height: 200px;" placeholder="请输入密钥内容"></textarea>
                    </div>
                    <div class="col-md-6 form-group">
                        <label class="font-weight-bold">证书(PEM格式)</label>
                        <textarea class="form-control text-monospace small" id="sslPem" style="height: 200px;" placeholder="请输入证书内容"></textarea>
                    </div>
                </div>
                
                <div class="alert alert-info small mb-4">
                    <i class="fas fa-info-circle mr-1"></i> 粘贴您的 *.key 以及 *.pem 内容，然后保存即可部署。
                </div>

                <div class="d-flex justify-content-between align-items-center border-top pt-3">
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary btn-sm" onclick="saveSSLCertificate()">
                            <i class="fas fa-save mr-1"></i> 保存并启用
                        </button>
                        <button type="button" class="btn btn-danger btn-sm" onclick="closeSSL()">
                            <i class="fas fa-times mr-1"></i> 关闭SSL
                        </button>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="loadSSLStatus()">
                        <i class="fas fa-sync-alt mr-1"></i> 刷新状态
                    </button>
                </div>

                <style>
                @media (max-width: 768px) {
                    #ssl-status .btn-group .btn {
                        padding: 6px 10px;
                        font-size: 12px;
                        border-radius: 8px;
                    }

                    #ssl-status .btn-outline-primary.btn-sm {
                        padding: 6px 10px;
                        font-size: 12px;
                        border-radius: 8px;
                    }
                }
                </style>
            </div>

            <!-- 证书列表 -->
            <div class="tab-pane fade" id="ssl-list" role="tabpanel">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-1"></i>
                    这里列出了您名下的所有可用证书，您可以选择一个进行部署。
                </div>
                <div id="sslCertList" class="min-vh-20">
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                        <div>加载中...</div>
                    </div>
                </div>
            </div>

            <!-- 申请证书 -->
            <div class="tab-pane fade" id="ssl-apply" role="tabpanel">
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle mr-1"></i>
                    通过 Let's Encrypt 申请免费证书。申请前请确保域名已解析到本服务器。
                </div>
                
                <form id="applyCertForm">
                    <div class="form-group mb-4">
                        <label class="font-weight-bold">申请域名</label>
                        <div id="applyDomainList" class="d-flex flex-wrap mb-2 p-3 border rounded bg-light">
                            <div class="text-muted small"><i class="fas fa-spinner fa-spin mr-1"></i> 正在加载域名...</div>
                        </div>
                        <small class="text-muted">请勾选需要申请证书的域名</small>
                    </div>

                    <div class="form-group mb-4">
                        <label class="font-weight-bold d-block">验证方式</label>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="verify_file" name="verify_method" class="custom-control-input" value="file" checked>
                            <label class="custom-control-label" for="verify_file">文件验证 (推荐)</label>
                        </div>
                        <div class="custom-control custom-radio custom-control-inline">
                            <input type="radio" id="verify_dns" name="verify_method" class="custom-control-input" value="dns">
                            <label class="custom-control-label" for="verify_dns">DNS验证</label>
                        </div>
                    </div>

                    <div class="border-top pt-4">
                        <button type="button" class="btn btn-primary" onclick="applySSLCertificate()">
                            <i class="fas fa-paper-plane mr-1"></i> 提交申请
                        </button>
                    </div>
                </form>
            </div>

        </div>
    </div>

<script>
// 加载SSL状态
function loadSSLStatus() {
    var $statusText = $('#sslStatusText');
    $statusText.text('正在获取...');
    
    $.ajax({
        url: 'ajax.php?egn=getssl',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.status === true) {
                var data = res.data;
                $statusText.text(data.status ? '已部署' : '未部署');
                
                if (data.status) {
                    $('#sslCertType').text(data.type || '宝塔证书');
                    $('#sslCertBrand').text(data.cert_data && data.cert_data.issuer ? data.cert_data.issuer : '-');
                    $('#sslCertDomains').text(data.cert_data && data.cert_data.dns ? data.cert_data.dns.join(', ') : '-');
                    $('#sslCertExpiry').text(data.cert_data && data.cert_data.notAfter ? data.cert_data.notAfter : '-');
                    $('#forceHttpsSwitch').prop('checked', data.httpToHttps === true);
                    
                    // 填充证书内容（如果后端返回了）
                    if (data.key) $('#sslKey').val(data.key);
                    if (data.csr) $('#sslPem').val(data.csr);
                    
                    if (data.httpToHttps) {
                        $('#sslStatusGuide').addClass('d-none').removeClass('d-flex');
                    } else {
                        $('#sslStatusGuide').addClass('d-flex').removeClass('d-none');
                        $('#sslStatusTitle').text('网站未开启强制HTTPS跳转');
                        $('#sslStatusDesc').text('建议开启强制HTTPS，确保所有访问都通过加密连接');
                    }
                } else {
                    $('#sslStatusGuide').addClass('d-flex').removeClass('d-none');
                    $('#sslStatusTitle').text('网站未开启HTTPS，站点访问可能存在风险');
                    $('#sslStatusDesc').text('建议立即开启HTTPS保护您的网站');
                }
            } else {
                $statusText.text('获取失败');
                layer.alert(res.msg || '获取SSL状态失败');
            }
        },
        error: function() {
            $statusText.text('网络错误');
        }
    });
}

// 切换强制HTTPS
function toggleForceHttps(el) {
    var checked = $(el).is(':checked');
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $.ajax({
        url: 'ajax.php?egn=setHttpToHttps',
        type: 'POST',
        data: { type: checked ? 1 : 0 },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === '配置成功' || res.status === true || res.code === '设置成功') {
                layer.msg(res.msg || '设置成功');
                loadSSLStatus();
            } else {
                layer.alert(res.msg || res.code || '操作失败');
                $(el).prop('checked', !checked);
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误');
            $(el).prop('checked', !checked);
        }
    });
}

// 保存SSL证书
function saveSSLCertificate() {
    var key = $('#sslKey').val().trim();
    var pem = $('#sslPem').val().trim();
    
    if (!key || !pem) {
        layer.alert('请填写完整的密钥和证书内容');
        return;
    }
    
    var $btn = $(event.currentTarget);
    var originalHtml = $btn.html();
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 正在保存...');
    
    $.ajax({
        url: 'ajax.php?egn=setssl',
        type: 'POST',
        data: {
            type: 1, // 自定义证书
            key: key,
            cert: pem
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === '配置成功' || res.status === true) {
                layer.msg('证书部署成功');
                loadSSLStatus();
            } else {
                layer.alert(res.msg || '部署失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误');
        },
        complete: function() {
            $btn.prop('disabled', false).html(originalHtml);
        }
    });
}

// 关闭SSL
function closeSSL() {
    layer.confirm('确定要关闭SSL吗？（此操作将停用HTTPS访问）', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            url: 'ajax.php?egn=setssl',
            type: 'POST',
            data: {
                type: -1 // 关闭
            },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.code === '配置成功' || res.status === true) {
                    layer.msg('SSL已成功关闭');
                    loadSSLStatus();
                } else {
                    layer.alert(res.msg || '操作失败');
                }
            },
            error: function() {
                layer.close(ii);
                layer.msg('网络错误');
            }
        });
    });
}

// 加载证书列表
function loadSSLCertList() {
    var $list = $('#sslCertList');
    $list.html('<div class="text-center py-4 text-muted"><i class="fas fa-spinner fa-spin"></i> 正在获取证书列表...</div>');
    
    $.ajax({
        url: 'ajax.php?egn=getsslcert&_t=' + Date.now(),
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function(res) {
            console.log('证书列表响应:', res);
            if (res.code === 'success') {
                var certs = res.certificates || [];
                if (certs.length === 0) {
                    // 空列表时显示提示信息
                    $list.html('<div style="text-align: center; padding: 60px 20px; color: #5f6368;">' +
                        '<i class="fas fa-certificate" style="font-size: 48px; color: #dadce0; margin-bottom: 16px;"></i>' +
                        '<div style="font-size: 16px; margin-bottom: 8px;">暂无可用证书</div>' +
                        '<div style="font-size: 14px; color: #80868b;">您还没有申请或上传任何SSL证书</div>' +
                        '</div>');
                    return;
                }
                
                var html = '<div class="table-responsive"><table class="table table-hover"><thead><tr>' +
                    '<th>证书品牌</th><th>域名</th><th>到期时间</th><th>状态</th><th>操作</th>' +
                    '</tr></thead><tbody>';
                
                certs.forEach(function(cert) {
                    var statusClass = cert.status === 'valid' ? 'text-success' : 'text-danger';
                    var statusText = cert.status === 'valid' ? '有效' : '已过期';
                    
                    html += '<tr>' +
                        '<td>' + (cert.brand || '-') + '</td>' +
                        '<td>' + (cert.domain || '-') + '</td>' +
                        '<td>' + (cert.expire_date || '-') + ' <small class="text-muted">(' + cert.expire_days + '天)</small></td>' +
                        '<td class="' + statusClass + '">' + statusText + '</td>' +
                        '<td>' +
                            '<button class="btn btn-primary btn-sm mr-1" onclick="deployCert(\'' + cert.hash + '\')">部署</button> ' +
                            '<button class="btn btn-danger btn-sm" onclick="deleteCert(\'' + cert.hash + '\')">删除</button>' +
                        '</td>' +
                        '</tr>';
                });
                
                html += '</tbody></table></div>';
                $list.html(html);
            } else {
                $list.html('<div class="alert alert-danger">' + (res.msg || '获取列表失败') + '</div>');
            }
        },
        error: function(xhr, status, error) {
            console.error('证书列表加载错误:', xhr, status, error);
            // 网络错误时显示友好的错误提示
            $list.html('<div style="text-align: center; padding: 60px 20px; color: #5f6368;">' +
                '<i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #f4b400; margin-bottom: 16px;"></i>' +
                '<div style="font-size: 16px; margin-bottom: 8px;">加载失败</div>' +
                '<div style="font-size: 14px; color: #80868b; margin-bottom: 16px;">网络连接出现问题，请检查网络后重试</div>' +
                '<button class="btn btn-primary btn-sm" onclick="loadSSLCertList()">重新加载</button>' +
                '</div>');
        }
    });
}

// 部署证书
function deployCert(hash) {
    if (!hash) {
        layer.alert('证书标识为空，无法部署');
        return;
    }
    layer.confirm('确定要部署此证书吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            url: 'ajax.php?egn=deploycert',
            type: 'POST',
            data: { cert_hash: hash },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                if (res.code === 'success' || res.status === true || res.code === '部署成功') {
                    layer.msg('证书部署成功');
                    $('#ssl-status-tab').tab('show');
                    loadSSLStatus();
                } else {
                    var msg = res.msg || res.code || '部署失败';
                    if (res.details) {
                        msg += '<br><br>详情: ' + res.details;
                    }
                    layer.alert(msg);
                }
            },
            error: function(xhr) {
                layer.close(ii);
                layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
            }
        });
    });
}

// 删除证书
function deleteCert(hash) {
    if (!hash) {
        layer.alert('证书标识为空，无法删除');
        return;
    }
    layer.confirm('确定要从证书库中删除此证书吗？', {
        btn: ['确定', '取消']
    }, function() {
        var ii = layer.load(2, {shade: [0.1, '#fff']});
        $.ajax({
            url: './api/api_router.php',
            type: 'POST',
            data: { action: 'deletecert', cert_hash: hash },
            dataType: 'json',
            success: function(res) {
                layer.close(ii);
                console.log('删除证书响应:', res);
                if (res.code === 'success' || res.status === true || res.msg === '删除成功' || (res.msg && res.msg.indexOf('已删除') !== -1) || (res.msg && res.msg.indexOf('已清理') !== -1)) {
                    layer.msg('删除成功');
                    // 延迟500ms后刷新列表，确保服务器端删除完成
                    setTimeout(function() {
                        loadSSLCertList();
                    }, 500);
                } else {
                    layer.alert(res.msg || res.code || '删除失败');
                }
            },
            error: function(xhr) {
                layer.close(ii);
                console.error('删除证书错误:', xhr);
                layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
            }
        });
    });
}

// 加载申请域名的列表
function loadApplyDomains() {
    var $container = $('#applyDomainList');
    $container.html('<div class="text-center py-4 text-muted"><i class="fas fa-spinner fa-spin"></i> 正在加载域名...</div>');
    
    $.ajax({
        url: 'ajax.php?egn=getssl',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.status === true && res.data) {
                // 优先使用 site_domains (站点绑定域名)，如果没有则退而求其次使用 cert_data.dns (证书域名)
                var domains = (res.data.site_domains && res.data.site_domains.length > 0) ? res.data.site_domains : (res.data.cert_data ? res.data.cert_data.dns : null);
                
                if (domains && Array.isArray(domains) && domains.length > 0) {
                    var html = '';
                    domains.forEach(function(domain) {
                        html += '<label class="m-1" style="display: flex; align-items: center; background: #f8f9fa; padding: 8px 15px; border-radius: 20px; cursor: pointer; border: 1px solid #eef2f7;">' +
                            '<input type="checkbox" name="apply_domains" class="mr-2" value="' + domain + '" checked> ' + domain +
                            '</label>';
                    });
                    $container.html(html);
                } else {
                    $container.html('<div class="alert alert-warning">未能获取到网站域名，请前往“域名管理”添加域名后再试</div>');
                }
            } else {
                $container.html('<div class="alert alert-warning">未能获取到网站域名，请刷新重试</div>');
            }
        },
        error: function() {
            $container.html('<div class="alert alert-danger">加载域名失败</div>');
        }
    });
}

// 申请SSL证书
function applySSLCertificate() {
    var domains = [];
    $('input[name="apply_domains"]:checked').each(function() {
        domains.push($(this).val());
    });
    
    if (domains.length === 0) {
        layer.alert('请至少勾选一个域名');
        return;
    }
    
    var verifyMethod = $('input[name="verify_method"]:checked').val();
    var $btn = $(event.currentTarget);
    var originalHtml = $btn.html();
    
    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 正在申请并部署...');
    
    $.ajax({
        url: 'ajax.php?egn=applycert',
        type: 'POST',
        data: {
            brand: 'letsencrypt',
            verifyMethod: verifyMethod,
            domains: domains
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.code === 'success' || res.status === true || (res.msg && res.msg.indexOf('成功') !== -1)) {
                layer.msg(res.msg || '申请证书成功并已部署');
                $('#ssl-status-tab').tab('show');
                loadSSLStatus();
            } else {
                var msg = res.msg || res.code || '申请失败';
                if (res.details) {
                    msg += '<br><br>详情: ' + res.details;
                }
                layer.alert(msg);
            }
        },
        error: function(xhr) {
            layer.close(ii);
            layer.msg('网络错误: ' + (xhr.statusText || '未知错误'));
        },
        complete: function() {
            $btn.prop('disabled', false).html(originalHtml);
        }
    });
}

// 初始化
$(document).ready(function() {
    loadSSLStatus();
});

// 监听Tab切换
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    if (e.target.id === 'ssl-apply-tab') {
        loadApplyDomains();
    }
});
</script>

<?php elseif ($gn == 'fdl'): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title mb-0"><i class="fas fa-shield-alt mr-2"></i>防盗链设置</h3>
    </div>
    
    <div class="card-body">
        <div class="alert alert-info mb-4">
            <i class="fas fa-info-circle mr-1"></i>
            开启防盗链后，只有在“许可域名”列表中的站点才能正常访问您的静态资源（如图片、视频等）。
        </div>

        <div class="form-section mb-4">
            <h5 class="font-weight-bold mb-3">状态控制</h5>
            <div class="d-flex align-items-center justify-content-between p-3 bg-light rounded" style="max-width: 800px;">
                <div>
                    <div class="font-weight-bold">启用防盗链</div>
                    <div class="small text-muted">开启后将限制指定域名之外的站点访问您的资源</div>
                </div>
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="fdl-status">
                    <label class="custom-control-label" for="fdl-status"></label>
                </div>
            </div>
        </div>

        <div class="form-section mb-4">
            <h5 class="font-weight-bold mb-3">详细设置</h5>
            <div class="form-group mb-4">
                <label class="font-weight-bold">许可域名</label>
                <p class="small text-muted mb-2">允许访问资源的域名列表，每行一个。支持通配符，如 *.example.com。建议包含本站域名。</p>
                <textarea class="form-control" id="fdl-domains" rows="5" placeholder="example.com&#10;www.example.com" style="max-width: 800px;"></textarea>
            </div>

            <div class="form-group mb-4">
                <label class="font-weight-bold">资源后缀</label>
                <p class="small text-muted mb-2">设置需要保护的资源后缀，用英文逗号分隔</p>
                <input type="text" class="form-control" id="fdl-exts" placeholder="jpg,png,gif,js,css" style="max-width: 800px;">
            </div>
        </div>

        <div class="border-top pt-4 text-left">
            <button class="btn btn-primary" data-action="save-fdl">
                <i class="fas fa-save mr-1"></i> 保存设置
            </button>
        </div>
    </div>
</div>

<script>
// 加载防盗链状态
function loadFDLStatus() {
    $.ajax({
        url: 'ajax.php?egn=getfdl',
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            if (res.status === true || res.code === 'success') {
                var data = res.data || res;
                $('#fdl-status').prop('checked', data.status === true || data.enable === 'true');
                $('#fdl-domains').val(data.url || data.domains || '');
                $('#fdl-exts').val(data.exts || 'jpg,png,gif,js,css');
            }
        }
    });
}

// 保存防盗链设置
function saveFDL() {
    var $btn = $('button[data-action="save-fdl"]');
    var originalHtml = $btn.html();
    
    var enable = $('#fdl-status').is(':checked');
    var domains = $('#fdl-domains').val();
    var exts = $('#fdl-exts').val();
    
    if (enable && !domains) {
        layer.alert('启用防盗链时，许可域名不能为空');
        return;
    }
    
    if (enable && !exts) {
        layer.alert('启用防盗链时，资源后缀不能为空');
        return;
    }

    var ii = layer.load(2, {shade: [0.1, '#fff']});
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 保存中...');

    $.ajax({
        url: 'ajax.php?egn=setfdl',
        type: 'POST',
        data: {
            enable: enable ? 'true' : 'false',
            domains: domains,
            exts: exts
        },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if (res.status === true || res.code === '设置成功') {
                layer.msg(res.msg || '防盗链设置成功');
                loadFDLStatus();
            } else {
                layer.alert(res.msg || '设置失败');
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误');
        },
        complete: function() {
            $btn.prop('disabled', false).html(originalHtml);
        }
    });
}

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

<?php endif; ?>

<!-- 统一事件代理：处理 data-action 和重试链接 -->
<script>
// 统一事件代理，避免内联 onclick 并把常用动作绑定到函数上
$(document).on('click', 'button[data-action], a.btn-retry, .btn-guide-toggle, button[data-action^="show-"], button[data-action^="add-"], button[data-action^="select-directory"]', function(e) {
    var $el = $(e.currentTarget);

    // 重试链接的专用处理
    if ($el.is('a.btn-retry')) {
        e.preventDefault();
        loadDomainList();
        return;
    }

    var action = $el.attr('data-action');
    if (!action) return;
    e.preventDefault();

    switch(action) {
        case 'setphp':
            setphp(this);
            break;
        case 'copy-ip':
            copyIP();
            break;
        case 'add-domain':
            setym(this);
            break;
        case 'browse-directory':
            browseDirectory();
            break;
        case 'select-directory':
            selectCurrentDirectory();
            break;
        case 'show-add-encrypt':
            showAddEncryptModal();
            break;
        case 'show-add-forbid':
            showAddForbidModal();
            break;
        case 'add-encrypt':
            addEncrypt();
            break;
        case 'add-forbid':
            addForbid();
            break;
        case 'getBTRewriteRules':
            getBTRewriteRules(this);
            break;
        case 'set-mrwd':
            setmrwd(this);
            break;
        case 'set-yxml':
            setyxml(this);
            break;
        case 'set-wjt':
            setwjt(this);
            break;
        case 'close-ssl-modal':
            $('.ssl-modal').remove();
            break;
        case 'save-ssl':
            saveSSLCertificate();
            break;
        case 'download-ssl':
            downloadSSLCertificate();
            break;
        case 'close-ssl':
            closeSSL();
            break;
        case 'save-fdl':
            saveFDL();
            break;
        default:
            // 未知 action 可在此处记录或忽略
            break;
    }
});

// 目录面包屑委托（已在文件中使用 data-path）
$(document).on('click', '#directoryBreadcrumb a[data-path]', function(e) {
    e.preventDefault();
    var path = $(this).data('path');
    if (path) navigateToDirectory(path);
});

// 将原有单独注册的旧式绑定保留以兼容历史代码
$(document).on('click', '[data-action="set-yxml"]', function(e){ e.preventDefault(); setyxml(this);});
$(document).on('click', '[data-action="set-wjt"]', function(e){ e.preventDefault(); setwjt(this);});
$(document).on('click', '[data-action="set-mrwd"]', function(e){ e.preventDefault(); setmrwd(this);});

// 复制IP的键盘友好行为
$(document).on('keydown', 'input#serverIP', function(e) {
    if (e.key === 'Enter') copyIP();
});
</script>
