<?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['id']) || !isset($_POST['title']) || !isset($_POST['url']) || !isset($_POST['category_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// 验证和清理输入
$id = intval($_POST['id']);
$title = trim($_POST['title']);
$url = trim($_POST['url']);
$category_id = intval($_POST['category_id']);
$description = isset($_POST['description']) ? trim($_POST['description']) : '';

// 验证URL格式
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid URL format']);
    exit;
}

$conn = db_connect();

// 首先检查记录是否存在
$check_stmt = $conn->prepare("SELECT icon FROM links WHERE id = ?");
if (!$check_stmt) {
    echo json_encode(['status' => 'error', 'message' => 'Error preparing check statement: ' . $conn->error]);
    exit;
}

$check_stmt->bind_param("i", $id);
$check_stmt->execute();
$result = $check_stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['status' => 'error', 'message' => 'Link not found']);
    exit;
}

$old_icon = $result->fetch_assoc()['icon'];
$check_stmt->close();

// 获取网站图标
$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;
            
            // 如果有旧图标且不同于新图标，则删除旧图标
            if (!empty($old_icon) && $old_icon !== $icon && file_exists('../../' . $old_icon)) {
                unlink('../../' . $old_icon);
            }
            break;
        }
    }
}

if (!isset($icon)) {
    $icon = $old_icon; // 如果没有获取到新图标，保留旧图标
}

// 更新数据
$stmt = $conn->prepare("UPDATE links SET category_id = ?, title = ?, url = ?, icon = ?, description = ? WHERE id = ?");
if (!$stmt) {
    echo json_encode(['status' => 'error', 'message' => 'Error preparing update statement: ' . $conn->error]);
    exit;
}

$stmt->bind_param("issssi", $category_id, $title, $url, $icon, $description, $id);

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

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