<?php
session_start();
require_once '../config.php';
require_once 'functions.php';
require_once '../includes/api.php';

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$message = '';
$message_type = '';

// 检查配置文件权限
$permission_check = check_config_permission();
if ($permission_check !== true) {
    $message = $permission_check;
    $message_type = 'danger';
}

// 获取分类列表
$categories_result = get_categories();
$categories = [];
if ($categories_result['code'] == 200 && isset($categories_result['data']['categories'])) {
    $categories = $categories_result['data']['categories'];
}

// 添加导航
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_nav'])) {
    $new_nav = [
        'name' => safe_input($_POST['name']),
        'url' => safe_input($_POST['url']),
        'type' => safe_input($_POST['type']),
        'target' => safe_input($_POST['target']),
        'status' => 'active',
        'created_at' => date('Y-m-d H:i:s')
    ];

    if ($new_nav['type'] === 'category') {
        $new_nav['category_id'] = intval($_POST['category_id']);
        // 自动生成分类URL
        $new_nav['url'] = '/category/' . $new_nav['category_id'];
    }

    // 确保custom_nav数组存在
    if (!isset($config['custom_nav']) || !is_array($config['custom_nav'])) {
        $config['custom_nav'] = [];
    }
    
    $config['custom_nav'][] = $new_nav;

    if (save_config($config)) {
        $message = '导航添加成功！';
        $message_type = 'success';
    } else {
        $message = '导航添加失败，请检查文件权限！';
        $message_type = 'danger';
    }
}

// 删除导航
if (isset($_GET['delete'])) {
    $index = intval($_GET['delete']);
    if (isset($config['custom_nav'][$index])) {
        array_splice($config['custom_nav'], $index, 1);
        if (save_config($config)) {
            $message = '导航删除成功！';
            $message_type = 'success';
        } else {
            $message = '导航删除失败，请检查文件权限！';
            $message_type = 'danger';
        }
    } else {
        $message = '导航不存在！';
        $message_type = 'danger';
    }
}

// 切换导航状态
if (isset($_GET['toggle_status'])) {
    $index = intval($_GET['toggle_status']);
    if (isset($config['custom_nav'][$index])) {
        $config['custom_nav'][$index]['status'] = 
            $config['custom_nav'][$index]['status'] === 'active' ? 'inactive' : 'active';
        
        if (save_config($config)) {
            $message = '导航状态更新成功！';
            $message_type = 'success';
        } else {
            $message = '状态更新失败，请检查文件权限！';
            $message_type = 'danger';
        }
    }
}

$page_title = '导航栏目';
?>
<?php include 'header.php'; ?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <div class="col-md-10 p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="mb-0">导航管理</h2>
                <span class="badge bg-primary"><?php echo count($config['custom_nav'] ?? []); ?> 个导航</span>
            </div>

            <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <style>
                .usage-guide {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                    border-radius: 8px;
                    padding: 1.5rem;
                    margin: 1.5rem 0;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                }
                .usage-guide h6 {
                    color: #2c3e50;
                    margin-bottom: 1rem;
                    font-weight: 600;
                    border-bottom: 2px solid #3498db;
                    padding-bottom: 0.5rem;
                }
                .code-example {
                    background: #2c3e50;
                    color: #ecf0f1;
                    padding: 1rem;
                    border-radius: 6px;
                    font-family: 'Courier New', monospace;
                    font-size: 0.85rem;
                    margin: 0.75rem 0;
                    border-left: 4px solid #3498db;
                }
                .nav-card {
                    transition: transform 0.2s;
                    border: 1px solid #e9ecef;
                    border-radius: 10px;
                }
                .nav-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                }
                .status-badge {
                    font-size: 0.7rem;
                }
                .inactive-nav {
                    opacity: 0.6;
                    background-color: #f8f9fa;
                }
            </style>

            <div class="row">
                <div class="col-md-6">
                    <div class="card nav-card">
                        <div class="card-header bg-primary text-white">
                            <i class="bi bi-plus-circle"></i> 添加导航
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label">导航名称</label>
                                    <input type="text" class="form-control" name="name" placeholder="输入导航名称" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">导航类型</label>
                                    <select class="form-select" name="type" id="navType" required>
                                        <option value="custom">自定义链接</option>
                                        <option value="category">分类链接</option>
                                    </select>
                                </div>
                                <div class="mb-3" id="customUrlGroup">
                                    <label class="form-label">链接地址</label>
                                    <input type="text" class="form-control" name="url" placeholder="/或http://开头">
                                    <div class="form-text">例如: /about 或 https://example.com</div>
                                </div>
                                <div class="mb-3 d-none" id="categoryGroup">
                                    <label class="form-label">选择分类</label>
                                    <select class="form-select" name="category_id">
                                        <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?> (ID: <?php echo $category['id']; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text">选择要链接到的分类</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">打开方式</label>
                                    <select class="form-select" name="target">
                                        <option value="_self">当前窗口</option>
                                        <option value="_blank">新窗口</option>
                                    </select>
                                </div>
                                <button type="submit" name="add_nav" class="btn btn-primary w-100">
                                    <i class="bi bi-check-lg"></i> 添加导航
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card nav-card">
                        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-list-ul"></i> 导航列表</span>
                            <span class="badge bg-light text-dark"><?php echo count($config['custom_nav'] ?? []); ?> 个</span>
                        </div>
                        <div class="card-body">
                            <?php if (empty($config['custom_nav'])): ?>
                            <div class="text-center py-4">
                                <i class="bi bi-compass display-1 text-muted"></i>
                                <p class="text-muted mt-3">暂无导航菜单</p>
                            </div>
                            <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php 
                                $active_navs = 0;
                                foreach ($config['custom_nav'] as $index => $nav): 
                                    if ($nav['status'] === 'active') $active_navs++;
                                ?>
                                <div class="list-group-item px-0 <?php echo $nav['status'] === 'inactive' ? 'inactive-nav' : ''; ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div style="flex: 1;">
                                            <div class="d-flex align-items-center mb-1">
                                                <h6 class="mb-0 me-2"><?php echo $nav['name']; ?></h6>
                                                <span class="badge <?php echo $nav['status'] === 'active' ? 'bg-success' : 'bg-secondary'; ?> status-badge">
                                                    <?php echo $nav['status'] === 'active' ? '活跃' : '禁用'; ?>
                                                </span>
                                                <span class="badge bg-info status-badge ms-1">
                                                    <?php echo $nav['type'] === 'category' ? '分类' : '自定义'; ?>
                                                </span>
                                                <span class="badge bg-warning status-badge ms-1">
                                                    <?php echo $nav['target'] === '_blank' ? '新窗口' : '当前窗口'; ?>
                                                </span>
                                            </div>
                                            <div class="text-muted small">
                                                <?php if ($nav['type'] === 'category'): ?>
                                                <i class="bi bi-folder"></i> 分类ID: <?php echo $nav['category_id']; ?>
                                                <?php else: ?>
                                                <i class="bi bi-link-45deg"></i> <?php echo $nav['url']; ?>
                                                <?php endif; ?>
                                            </div>
                                            <small class="text-muted">
                                                <i class="bi bi-clock"></i> 创建: <?php echo $nav['created_at'] ?? '未知'; ?>
                                            </small>
                                        </div>
                                        <div class="ms-3 d-flex flex-column gap-1">
                                            <a href="?toggle_status=<?php echo $index; ?>" class="btn btn-sm <?php echo $nav['status'] === 'active' ? 'btn-warning' : 'btn-success'; ?>" 
                                               title="<?php echo $nav['status'] === 'active' ? '禁用导航' : '启用导航'; ?>">
                                                <i class="bi bi-power"></i>
                                            </a>
                                            <a href="?delete=<?php echo $index; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定删除这个导航吗？')">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3 pt-3 border-top">
                                <small class="text-muted">
                                    <i class="bi bi-info-circle"></i> 
                                    总计: <?php echo count($config['custom_nav']); ?> 个导航, 
                                    活跃: <?php echo $active_navs; ?> 个, 
                                    禁用: <?php echo count($config['custom_nav']) - $active_navs; ?> 个
                                </small>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 使用说明放在功能后面 -->
            <div class="usage-guide">
                <h6>📝 导航使用说明</h6>
                <p><strong>模板调用方法：</strong></p>
                <div class="code-example">
                    {if $config.custom_nav}<br>
                    &nbsp;&nbsp;{foreach $config.custom_nav as $nav}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;{if $nav.type == 'category'}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;a href="{build_url mod='category' cate=$nav.category_id}"&gt;{$nav.name}&lt;/a&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;{else}<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;a href="{$nav.url}" target="{$nav.target}"&gt;{$nav.name}&lt;/a&gt;<br>
                    &nbsp;&nbsp;&nbsp;&nbsp;{/if}<br>
                    &nbsp;&nbsp;{/foreach}<br>
                    {/if}
                </div>
                <p><strong>导航类型说明：</strong></p>
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-link-45deg text-primary"></i> <strong>自定义链接</strong> - 可以设置任意URL地址</li>
                            <li><i class="bi bi-folder text-info"></i> <strong>分类链接</strong> - 自动链接到指定分类页面</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-unstyled">
                            <li><i class="bi bi-box-arrow-up-right text-success"></i> <strong>新窗口打开</strong> - 在新浏览器标签中打开链接</li>
                            <li><i class="bi bi-window text-warning"></i> <strong>当前窗口</strong> - 在当前浏览器标签中打开链接</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdmirror.com/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('navType').addEventListener('change', function() {
    const type = this.value;
    const customUrlGroup = document.getElementById('customUrlGroup');
    const categoryGroup = document.getElementById('categoryGroup');

    if (type === 'category') {
        customUrlGroup.classList.add('d-none');
        categoryGroup.classList.remove('d-none');
    } else {
        customUrlGroup.classList.remove('d-none');
        categoryGroup.classList.add('d-none');
    }
});

// 初始化显示状态
document.addEventListener('DOMContentLoaded', function() {
    const type = document.getElementById('navType').value;
    const customUrlGroup = document.getElementById('customUrlGroup');
    const categoryGroup = document.getElementById('categoryGroup');
    
    if (type === 'category') {
        customUrlGroup.classList.add('d-none');
        categoryGroup.classList.remove('d-none');
    }
});
</script>
</body>
</html>