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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

if (!isset($_POST['title']) || !isset($_POST['url']) || !isset($_POST['category_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

$title = $_POST['title'];
$url = $_POST['url'];
$category_id = intval($_POST['category_id']);
$description = isset($_POST['description']) ? $_POST['description'] : '';

// 获取网站图标
$domain = parse_url($url, PHP_URL_HOST);
if ($domain) {
    // 创建icons目录（如果不存在）
    $icon_dir = '../../data/icons/';
    if (!file_exists($icon_dir)) {
        mkdir($icon_dir, 0777, true);
    }
    
    // 保存图标文件
    $icon_filename = md5($domain) . '.png';
    $icon_path = $icon_dir . $icon_filename;
    
    // 尝试多个图标源
    $icon_urls = [
        "https://{$domain}/favicon.ico",
        "http://{$domain}/favicon.ico",
        "https://api.iowen.cn/favicon/{$domain}.png",
        "https://favicon.cccyun.cc/{$domain}"
    ];
    
    $icon_content = false;
    $context = stream_context_create([
        'http' => [
            'timeout' => 3,
            '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'
        ]
    ]);
    
    foreach ($icon_urls as $icon_url) {
        $icon_content = @file_get_contents($icon_url, false, $context);
        if ($icon_content !== false && strlen($icon_content) > 100) {
            file_put_contents($icon_path, $icon_content);
            $icon = 'data/icons/' . $icon_filename;
            break;
        }
    }
}

if (!isset($icon)) {
    $icon = '';
}

// 连接数据库
$conn = db_connect();

// 插入数据
$stmt = $conn->prepare("INSERT INTO links (category_id, title, url, icon, description) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $category_id, $title, $url, $icon, $description);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success']);
} else {
    echo json_encode(['status' => 'error', 'message' => $stmt->error]);
}

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