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

header('Content-Type: application/json');

if (!isset($_POST['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing id parameter']);
    exit;
}

$id = intval($_POST['id']);
$conn = db_connect();

// 删除链接
$stmt = $conn->prepare("DELETE FROM links WHERE id = ?");
$stmt->bind_param("i", $id);

if ($stmt->execute()) {
    // 删除成功后，也要更新排序文件
    $order_file = '../../data/link_order.json';
    if (file_exists($order_file)) {
        $order_data = json_decode(file_get_contents($order_file), true) ?? [];
        
        // 从所有分类的排序中移除该链接ID
        foreach ($order_data as $category_id => &$order) {
            $order = array_values(array_diff($order, [$id]));
        }
        
        file_put_contents($order_file, json_encode($order_data));
    }
    
    // 删除图标文件
    $result = $conn->query("SELECT icon FROM links WHERE id = " . $id);
    if ($result && $row = $result->fetch_assoc()) {
        $icon_path = '../../' . $row['icon'];
        if (file_exists($icon_path)) {
            unlink($icon_path);
        }
    }
    
    echo json_encode(['status' => 'success']);
} else {
    echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}

$stmt->close();
$conn->close();
