<?php
require_once '../config/config.php';

$page_title = '链接管理';
$active_page = 'link';

// 获取当前分类ID
$category_id = isset($_GET['category']) ? intval($_GET['category']) : null;

// 处理排序操作
if (isset($_POST['action']) && $_POST['action'] === 'reorder') {
    $order_file = '../data/link_order.json';
    $order_data = [];
    if (file_exists($order_file)) {
        $order_data = json_decode(file_get_contents($order_file), true) ?? [];
    }
    
    // 更新排序
    $ids = explode(',', $_POST['ids']);
    $order_data[$category_id ?? 'all'] = $ids;
    
    // 保存排序
    file_put_contents($order_file, json_encode($order_data));
    exit('success');
}

// 处理添加/编辑/删除操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = db_connect();
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $category_id = $_POST['category_id'] ?? 0;
                $title = $_POST['title'] ?? '';
                $url = $_POST['url'] ?? '';
                $description = $_POST['description'] ?? '';
                
                // 获取网站图标
                $icon = getFavicon($url);
                
                $stmt = $conn->prepare("INSERT INTO links (category_id, title, url, icon, description) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param("issss", $category_id, $title, $url, $icon, $description);
                $stmt->execute();
                break;
                
            case 'edit':
                $id = $_POST['id'] ?? 0;
                $category_id = $_POST['category_id'] ?? 0;
                $title = $_POST['title'] ?? '';
                $url = $_POST['url'] ?? '';
                $description = $_POST['description'] ?? '';
                
                // 获取网站图标
                $icon = getFavicon($url);
                
                $stmt = $conn->prepare("UPDATE links SET category_id = ?, title = ?, url = ?, icon = ?, description = ? WHERE id = ?");
                $stmt->bind_param("issssi", $category_id, $title, $url, $icon, $description, $id);
                $stmt->execute();
                break;
                
            case 'delete':
                $id = $_POST['id'] ?? 0;
                $conn->query("DELETE FROM links WHERE id = " . intval($id));
                break;
        }
    }
    
    $conn->close();
    header('Location: link.php' . ($category_id ? "?category=$category_id" : ''));
    exit;
}

include 'includes/header.php';

$conn = db_connect();
$where_clause = $category_id ? "WHERE category_id = " . intval($category_id) : "";
$links = $conn->query("SELECT * FROM links $where_clause");

// 获取保存的排序
$order_file = '../data/link_order.json';
$order_data = [];
if (file_exists($order_file)) {
    $order_data = json_decode(file_get_contents($order_file), true) ?? [];
}

// 获取当前分类的排序
$current_order = isset($order_data[$category_id ?? 'all']) ? $order_data[$category_id ?? 'all'] : [];
if (!is_array($current_order)) {
    $current_order = [];
}

// 将链接数据转换为数组
$links_array = [];
while ($link = $links->fetch_assoc()) {
    $links_array[$link['id']] = $link;
}

// 按保存的顺序排序链接
$sorted_links = [];
if (!empty($current_order)) {
    foreach ($current_order as $id) {
        if (isset($links_array[$id])) {
            $sorted_links[] = $links_array[$id];
            unset($links_array[$id]);
        }
    }
}

// 添加未排序的链接到末尾
$sorted_links = array_merge($sorted_links, array_values($links_array));
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <?php
                        if ($category_id) {
                            $category = $conn->query("SELECT name FROM categories WHERE id = " . intval($category_id))->fetch_assoc();
                            echo htmlspecialchars($category['name']) . ' - ';
                        }
                        ?>
                        链接管理
                    </h5>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addLinkModal">
                        添加链接
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th width="50">#</th>
                                    <th width="50">图标</th>
                                    <th>标题</th>
                                    <th>URL</th>
                                    <?php if (!$category_id): ?>
                                    <th>分类</th>
                                    <?php endif; ?>
                                    <th>描述</th>
                                    <th width="120">操作</th>
                                </tr>
                            </thead>
                            <tbody class="link-list">
                                <?php foreach ($sorted_links as $link): ?>
                                <tr data-id="<?php echo $link['id']; ?>">
                                    <td>
                                        <span class="drag-handle" style="cursor: move;"><i class="fas fa-grip-vertical"></i></span>
                                    </td>
                                    <td>
                                        <?php
                                        $domain = parse_url($link['url'], PHP_URL_HOST);
                                        $icon_urls = [
                                            "https://api.iowen.cn/favicon/{$domain}.png",
                                            "https://favicon.cccyun.cc/{$domain}",
                                            "https://{$domain}/favicon.ico",
                                            "https://{$domain}/favicon.png"
                                        ];
                                        ?>
                                        <img src="<?php echo $icon_urls[0]; ?>" 
                                             alt="<?php echo htmlspecialchars($link['title']); ?>" 
                                             style="width: 24px; height: 24px; border-radius: 4px;"
                                             onerror="if (this.src !== '<?php echo $icon_urls[1]; ?>') this.src = '<?php echo $icon_urls[1]; ?>'; 
                                                     else if (this.src !== '<?php echo $icon_urls[2]; ?>') this.src = '<?php echo $icon_urls[2]; ?>'; 
                                                     else if (this.src !== '<?php echo $icon_urls[3]; ?>') this.src = '<?php echo $icon_urls[3]; ?>'; 
                                                     else this.src='../assets/images/default-icon.png';">
                                    </td>
                                    <td><?php echo htmlspecialchars($link['title']); ?></td>
                                    <td>
                                        <a href="<?php echo htmlspecialchars($link['url']); ?>" target="_blank">
                                            <?php echo htmlspecialchars($link['url']); ?>
                                        </a>
                                    </td>
                                    <?php if (!$category_id): ?>
                                    <td><?php echo htmlspecialchars($link['category_name'] ?? '未分类'); ?></td>
                                    <?php endif; ?>
                                    <td><?php echo htmlspecialchars($link['description']); ?></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="editLink(<?php echo $link['id']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteLink(<?php echo $link['id']; ?>)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加链接模态框 -->
<div class="modal fade" id="addLinkModal" tabindex="-1" aria-labelledby="addLinkModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addLinkModalLabel">添加链接</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addLinkForm">
                    <div class="mb-3">
                        <label for="add_title" class="form-label">名称</label>
                        <input type="text" class="form-control" id="add_title" name="title" required>
                    </div>
                    <div class="mb-3">
                        <label for="add_url" class="form-label">URL</label>
                        <input type="url" class="form-control" id="add_url" name="url" required>
                    </div>
                    <div class="mb-3">
                        <label for="add_category_id" class="form-label">分类</label>
                        <select class="form-select" id="add_category_id" name="category_id" required>
                            <?php
                            $categories->data_seek(0);
                            while ($category = $categories->fetch_assoc()) {
                                $selected = ($category['id'] == $category_id) ? 'selected' : '';
                                echo '<option value="' . $category['id'] . '" ' . $selected . '>' . htmlspecialchars($category['name']) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="add_description" class="form-label">描述</label>
                        <textarea class="form-control" id="add_description" name="description"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitAddLink()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑链接模态框 -->
<div class="modal fade" id="editLinkModal" tabindex="-1" aria-labelledby="editLinkModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editLinkModalLabel">编辑链接</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editLinkForm">
                    <input type="hidden" id="edit_id" name="id">
                    <div class="mb-3">
                        <label for="edit_title" class="form-label">名称</label>
                        <input type="text" class="form-control" id="edit_title" name="title" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_url" class="form-label">URL</label>
                        <input type="url" class="form-control" id="edit_url" name="url" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_category_id" class="form-label">分类</label>
                        <select class="form-select" id="edit_category_id" name="category_id" required>
                            <?php
                            $categories->data_seek(0);
                            while ($category = $categories->fetch_assoc()) {
                                echo '<option value="' . $category['id'] . '">' . htmlspecialchars($category['name']) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_description" name="description"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitEditLink()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 提示模态框 -->
<div class="modal fade" id="alertModal" tabindex="-1" aria-labelledby="alertModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="alertModalLabel">提示</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="alertMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<script>
// 存储所有链接数据
const linksData = <?php echo json_encode($sorted_links); ?>;

// 编辑链接
function editLink(id) {
    const link = linksData.find(l => parseInt(l.id) === parseInt(id));
    if (link) {
        document.getElementById('edit_id').value = link.id;
        document.getElementById('edit_title').value = link.title;
        document.getElementById('edit_url').value = link.url;
        document.getElementById('edit_category_id').value = link.category_id;
        document.getElementById('edit_description').value = link.description || '';
        
        const editModal = new bootstrap.Modal(document.getElementById('editLinkModal'));
        editModal.show();
    }
}

// 提交编辑
function submitEditLink() {
    const form = document.getElementById('editLinkForm');
    const formData = new FormData(form);
    
    fetch('api/edit_link.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            location.reload();
        } else {
            showAlert('错误', data.message);
        }
    })
    .catch(error => {
        showAlert('错误', '保存失败：' + error.message);
    });
}

// 显示提示
function showAlert(title, message) {
    const alertModal = new bootstrap.Modal(document.getElementById('alertModal'));
    document.getElementById('alertModalLabel').textContent = title;
    document.getElementById('alertMessage').textContent = message;
    alertModal.show();
}

// 添加链接
function submitAddLink() {
    const form = document.getElementById('addLinkForm');
    const formData = new FormData(form);
    formData.append('action', 'add');
    
    fetch('api/add_link.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            location.reload();
        } else {
            showAlert('错误', data.message);
        }
    })
    .catch(error => {
        showAlert('错误', '添加失败：' + error.message);
    });
}

// 删除链接
function deleteLink(id) {
    if (confirm('确定要删除这个链接吗？此操作不可恢复。')) {
        fetch('api/delete_link.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                location.reload();
            } else {
                showAlert('错误', data.message);
            }
        })
        .catch(error => {
            showAlert('错误', '删除失败：' + error.message);
        });
    }
}
</script>

<?php include 'includes/footer.php'; ?>

<script src="../assets/js/Sortable.min.js"></script>
<script>
// 初始化拖拽排序
new Sortable(document.querySelector('.link-list'), {
    handle: '.drag-handle',
    animation: 150,
    onEnd: function() {
        const ids = [];
        document.querySelectorAll('.link-list tr').forEach(row => {
            ids.push(row.dataset.id);
        });
        
        fetch('api/reorder_links.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'ids=' + ids.join(',')
        })
        .then(response => response.text())
        .then(result => {
            if (result !== 'success') {
                showAlert('保存排序失败：' + result);
            }
        })
        .catch(error => {
            showAlert('保存排序失败：' + error);
        });
    }
});
</script>

<?php
// 获取网站图标函数
function getFavicon($url) {
    $parsed = parse_url($url);
    if (!isset($parsed['scheme'])) {
        $url = 'https://' . ltrim($url, '/');
        $parsed = parse_url($url);
    }
    $domain = $parsed['host'];

    // 首先尝试使用第三方服务
    $third_party_services = [
        "https://api.iowen.cn/favicon/{$domain}.png",
        "https://favicon.cccyun.cc/{$domain}"
    ];

    foreach ($third_party_services as $service) {
        $headers = get_headers($service, 1);
        if (strpos($headers[0], '200') !== false) {
            return $service;
        }
    }

    // 如果第三方服务失败，尝试直接从网站获取
    $direct_paths = [
        "https://{$domain}/favicon.ico",
        "https://{$domain}/favicon.png",
        "https://{$domain}/apple-touch-icon.png",
        "https://{$domain}/apple-touch-icon-precomposed.png"
    ];

    foreach ($direct_paths as $path) {
        $headers = get_headers($path, 1);
        if (strpos($headers[0], '200') !== false) {
            return $path;
        }
    }

    // 如果直接获取失败，尝试从HTML中查找
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'timeout' => 3,
        ]
    ]);

    $html = @file_get_contents($url, false, $context);
    if ($html !== false) {
        if (preg_match('/<link[^>]+(?:rel=["\'](icon|shortcut icon|apple-touch-icon)["\'][^>]+href=["\'](.*?)["\']|href=["\'](.*?)["\'][^>]+rel=["\'](icon|shortcut icon|apple-touch-icon)["\'])[^>]*>/i', $html, $matches)) {
            $favicon = !empty($matches[2]) ? $matches[2] : $matches[3];
            if (strpos($favicon, 'http') !== 0) {
                if (strpos($favicon, '//') === 0) {
                    $favicon = 'https:' . $favicon;
                } elseif (strpos($favicon, '/') === 0) {
                    $favicon = 'https://' . $domain . $favicon;
                } else {
                    $favicon = 'https://' . $domain . '/' . $favicon;
                }
            }
            $headers = get_headers($favicon, 1);
            if (strpos($headers[0], '200') !== false) {
                return $favicon;
            }
        }
    }
    
    // 如果都失败了，返回默认图标
    return '../assets/images/default-icon.png';
}
?>
