// 访问限制功能
?>
<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>