<?php
requireAdmin();

$action = $_GET['action'] ?? 'list';
$link_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// SVG 图标配置
$svg_icons = [
    'add'       => 'https://api.iconify.design/mdi:plus-circle.svg?color=%23667eea',
    'edit'      => 'https://api.iconify.design/mdi:pencil.svg?color=%23f59e0b',
    'delete'    => 'https://api.iconify.design/mdi:delete.svg?color=%23ef4444',
    'link'      => 'https://api.iconify.design/mdi:link.svg?color=%23667eea',
    'header'    => 'https://api.iconify.design/mdi:menu.svg?color=%233b82f6',
    'friend'    => 'https://api.iconify.design/mdi:account-group.svg?color=%2310b981',
    'dropdown'  => 'https://api.iconify.design/mdi:chevron-down.svg?color=%238b5cf6',
    'back'      => 'https://api.iconify.design/mdi:arrow-left.svg?color=%236b7280',
    'save'      => 'https://api.iconify.design/mdi:content-save.svg?color=%2310b981',
    'cancel'    => 'https://api.iconify.design/mdi:close.svg?color=%236b7280',
    'active'    => 'https://api.iconify.design/mdi:check-circle.svg?color=%2310b981',
    'inactive'  => 'https://api.iconify.design/mdi:close-circle.svg?color=%23ef4444',
    'child'     => 'https://api.iconify.design/mdi:subdirectory-arrow-right.svg?color=%239ca3af',
    'home'      => 'https://api.iconify.design/mdi:home.svg?color=%23667eea',
];

// 处理删除
if ($action == 'delete' && $link_id > 0) {
    // 同时删除子菜单
    $db->query("DELETE FROM links WHERE id = $link_id OR parent_id = $link_id");
    redirect('?page=links');
}

// 处理编辑/添加
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $url = trim($_POST['url'] ?? '');
    $type = $_POST['type'] ?? 'header';
    $parent_id = intval($_POST['parent_id'] ?? 0);
    $sort = intval($_POST['sort'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    if ($action == 'edit' && $link_id > 0) {
        $db->query("
            UPDATE links SET 
                name = '" . $db->escape($name) . "',
                url = '" . $db->escape($url) . "',
                type = '" . $db->escape($type) . "',
                parent_id = $parent_id,
                sort = $sort,
                status = $status
            WHERE id = $link_id
        ");
        redirect('?page=links');
    } elseif ($action == 'add') {
        $db->query("
            INSERT INTO links (name, url, type, parent_id, sort, status) 
            VALUES (
                '" . $db->escape($name) . "',
                '" . $db->escape($url) . "',
                '" . $db->escape($type) . "',
                $parent_id,
                $sort,
                $status
            )
        ");
        redirect('?page=links');
    }
}

// 获取所有链接
$all_links = $db->fetchAll("SELECT * FROM links ORDER BY parent_id ASC, sort ASC, id ASC");

// 构建树形结构
function buildLinkTree($links, $parent_id = 0) {
    $tree = [];
    foreach ($links as $link) {
        if ($link['parent_id'] == $parent_id) {
            $link['children'] = buildLinkTree($links, $link['id']);
            $tree[] = $link;
        }
    }
    return $tree;
}

$link_tree = buildLinkTree($all_links);

// 获取可选的父菜单（仅头部导航的顶级菜单）
$parent_options = $db->fetchAll("
    SELECT id, name FROM links 
    WHERE parent_id = 0 AND type = 'header' AND status = 1
    ORDER BY sort ASC
");

// 编辑模式获取数据
$edit_link = null;
if ($action == 'edit' && $link_id > 0) {
    $edit_link = $db->fetchOne("SELECT * FROM links WHERE id = $link_id");
}
?>

<style>
    .links-manager { padding: 20px; }
    .page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
    .page-header h2 { font-size: 24px; font-weight: 600; display: flex; align-items: center; gap: 10px; }
    .page-header h2 img { width: 28px; height: 28px; }
    .btn { display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; border-radius: 10px; text-decoration: none; font-weight: 500; transition: all 0.2s; border: none; cursor: pointer; }
    .btn-primary { background: #667eea; color: white; }
    .btn-primary:hover { background: #5a67d8; }
    .btn-secondary { background: #f3f4f6; color: #374151; }
    .btn-secondary:hover { background: #e5e7eb; }
    .btn-icon { padding: 8px 12px; background: transparent; border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-secondary); text-decoration: none; display: inline-flex; align-items: center; gap: 6px; font-size: 13px; margin-right: 6px; }
    .btn-icon:hover { background: var(--bg-secondary); }
    .btn-icon img { width: 18px; height: 18px; }
    .section-box { background: var(--bg-primary); border-radius: 16px; padding: 24px; margin-bottom: 24px; border: 1px solid var(--border-color); }
    .section-box h3 { font-size: 18px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
    .section-box h3 img { width: 24px; height: 24px; }
    .data-table { width: 100%; border-collapse: collapse; }
    .data-table th { text-align: left; padding: 12px; border-bottom: 1px solid var(--border-color); color: var(--text-secondary); font-weight: 500; font-size: 13px; }
    .data-table td { padding: 14px 12px; border-bottom: 1px solid var(--border-color); color: var(--text-primary); }
    .data-table tr:last-child td { border-bottom: none; }
    .status-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-size: 12px; }
    .status-badge.active { background: #d1fae5; color: #059669; }
    .status-badge.inactive { background: #f3f4f6; color: #6b7280; }
    .status-badge img { width: 16px; height: 16px; }
    .child-indent { margin-left: 24px; display: inline-flex; align-items: center; gap: 8px; }
    .child-indent img { width: 16px; height: 16px; opacity: 0.5; }
    .type-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-size: 12px; }
    .type-badge.header { background: #e0f2fe; color: #0369a1; }
    .type-badge.friend { background: #fce7f3; color: #be185d; }
    .type-badge img { width: 16px; height: 16px; }
    
    /* 表单样式 */
    .form-container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .form-card { background: var(--bg-primary); border-radius: 20px; padding: 30px; border: 1px solid var(--border-color); }
    .form-group { margin-bottom: 20px; }
    .form-group label { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; font-weight: 500; color: var(--text-primary); }
    .form-group label img { width: 20px; height: 20px; }
    .form-group input, .form-group select { width: 100%; padding: 12px 16px; border: 1px solid var(--border-color); border-radius: 10px; background: var(--bg-primary); color: var(--text-primary); font-size: 15px; }
    .form-group input:focus, .form-group select:focus { outline: none; border-color: #667eea; }
    .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    .form-actions { display: flex; gap: 12px; margin-top: 30px; }
    .form-actions .btn { flex: 1; justify-content: center; }
    
    .tip { color: var(--text-muted); font-size: 13px; margin-left: 15px; }
</style>

<?php if ($action == 'add' || ($action == 'edit' && $edit_link)): ?>
    <!-- 添加/编辑表单 -->
    <div class="form-container">
        <div class="page-header">
            <h2>
                <img src="<?php echo $svg_icons[$action == 'add' ? 'add' : 'edit']; ?>" alt="">
                <?php echo $action == 'add' ? '添加链接' : '编辑链接'; ?>
            </h2>
            <a href="?page=links" class="btn btn-secondary">
                <img src="<?php echo $svg_icons['back']; ?>" alt="" style="width:18px">
                返回列表
            </a>
        </div>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label><img src="<?php echo $svg_icons['link']; ?>" alt=""> 链接名称 *</label>
                    <input type="text" name="name" required value="<?php echo htmlspecialchars($edit_link['name'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label><img src="<?php echo $svg_icons['link']; ?>" alt=""> 链接地址 *</label>
                    <input type="text" name="url" required value="<?php echo htmlspecialchars($edit_link['url'] ?? ''); ?>" placeholder="/ 或 https://">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>类型</label>
                        <select name="type">
                            <option value="header" <?php echo (isset($edit_link['type']) && $edit_link['type'] == 'header') ? 'selected' : ''; ?>>头部导航</option>
                            <option value="friend" <?php echo (isset($edit_link['type']) && $edit_link['type'] == 'friend') ? 'selected' : ''; ?>>友情链接</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>排序</label>
                        <input type="number" name="sort" value="<?php echo $edit_link['sort'] ?? 0; ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>父菜单</label>
                    <select name="parent_id">
                        <option value="0">无（顶级菜单）</option>
                        <?php foreach ($parent_options as $p): ?>
                            <?php if (($edit_link['id'] ?? 0) != $p['id']): ?>
                            <option value="<?php echo $p['id']; ?>" <?php echo (isset($edit_link['parent_id']) && $edit_link['parent_id'] == $p['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($p['name']); ?>
                            </option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status">
                        <option value="1" <?php echo (isset($edit_link['status']) && $edit_link['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                        <option value="0" <?php echo (isset($edit_link['status']) && $edit_link['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <img src="<?php echo $svg_icons['save']; ?>" alt="" style="width:18px;filter:brightness(0)invert(1)">
                        保存
                    </button>
                    <a href="?page=links" class="btn btn-secondary">
                        <img src="<?php echo $svg_icons['cancel']; ?>" alt="" style="width:18px">
                        取消
                    </a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 链接列表 -->
    <div class="links-manager">
        <div class="page-header">
            <h2>
                <img src="<?php echo $svg_icons['link']; ?>" alt="">
                链接管理
                <span class="tip">支持父子菜单，子菜单将显示在下拉中</span>
            </h2>
            <a href="?page=links&action=add" class="btn btn-primary">
                <img src="<?php echo $svg_icons['add']; ?>" alt="" style="width:20px;filter:brightness(0)invert(1)">
                添加链接
            </a>
        </div>
        
        <!-- 头部导航链接（树形） -->
        <div class="section-box">
            <h3>
                <img src="<?php echo $svg_icons['header']; ?>" alt="">
                头部导航链接
            </h3>
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>名称</th>
                            <th>地址</th>
                            <th>类型</th>
                            <th>排序</th>
                            <th>状态</th>
                            <th>操作</th>
                        </thead>
                    <tbody id="sortable-list">
                        <?php 
                        function renderLinkRow($link, $svg_icons, $level = 0) {
                            $indent = $level * 24;
                            ?>
                            <tr data-id="<?php echo $link['id']; ?>">
                                <td>
                                    <?php if ($level > 0): ?>
                                        <span class="child-indent" style="margin-left: <?php echo $indent; ?>px;">
                                            <img src="<?php echo $svg_icons['child']; ?>" alt="">
                                            <?php echo htmlspecialchars($link['name']); ?>
                                        </span>
                                    <?php else: ?>
                                        <strong><?php echo htmlspecialchars($link['name']); ?></strong>
                                    <?php endif; ?>
                                </td>
                                <td><code><?php echo htmlspecialchars($link['url']); ?></code></td>
                                <td>
                                    <span class="type-badge <?php echo $link['type']; ?>">
                                        <img src="<?php echo $svg_icons[$link['type']]; ?>" alt="">
                                        <?php echo $link['type'] == 'header' ? '导航' : '友链'; ?>
                                    </span>
                                </td>
                                <td><?php echo $link['sort']; ?></td>
                                <td>
                                    <span class="status-badge <?php echo $link['status'] ? 'active' : 'inactive'; ?>">
                                        <img src="<?php echo $svg_icons[$link['status'] ? 'active' : 'inactive']; ?>" alt="">
                                        <?php echo $link['status'] ? '启用' : '禁用'; ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="?page=links&action=edit&id=<?php echo $link['id']; ?>" class="btn-icon">
                                        <img src="<?php echo $svg_icons['edit']; ?>" alt="">
                                        编辑
                                    </a>
                                    <a href="?page=links&action=delete&id=<?php echo $link['id']; ?>" class="btn-icon" onclick="return confirm('确定删除吗？子菜单也会被删除')">
                                        <img src="<?php echo $svg_icons['delete']; ?>" alt="">
                                        删除
                                    </a>
                                </td>
                            </tr>
                            <?php
                            if (!empty($link['children'])) {
                                foreach ($link['children'] as $child) {
                                    renderLinkRow($child, $svg_icons, $level + 1);
                                }
                            }
                        }
                        
                        foreach ($link_tree as $link) {
                            renderLinkRow($link, $svg_icons);
                        }
                        ?>
                        <?php if (empty($link_tree)): ?>
                            <tr><td colspan="6" style="text-align: center; padding: 40px; color: var(--text-muted);">暂无导航链接，点击"添加链接"创建</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>