<?php
require_once dirname(__DIR__) . '/config.php';

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

// 检查登录和权限
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

$id = intval($_POST['id'] ?? 0);
$version = trim($_POST['version'] ?? '');
$release_date = trim($_POST['release_date'] ?? '');
$content = trim($_POST['content'] ?? '');
$is_featured = isset($_POST['is_featured']) ? 1 : 0;
$status = intval($_POST['status'] ?? 1);

if (empty($version) || empty($release_date) || empty($content)) {
    echo json_encode(['success' => false, 'message' => '请填写完整信息']);
    exit;
}

$version = $db->escape($version);
$release_date = $db->escape($release_date);
$content = $db->escape($content);

if ($id > 0) {
    // 编辑
    $db->query("UPDATE changelog SET version='$version', release_date='$release_date', content='$content', is_featured=$is_featured, status=$status WHERE id=$id");
    echo json_encode(['success' => true, 'message' => '更新成功']);
} else {
    // 新增
    $check = $db->fetchOne("SELECT id FROM changelog WHERE version='$version'");
    if ($check) {
        echo json_encode(['success' => false, 'message' => '版本号已存在']);
        exit;
    }
    $db->query("INSERT INTO changelog (version, release_date, content, is_featured, status) VALUES ('$version', '$release_date', '$content', $is_featured, $status)");
    echo json_encode(['success' => true, 'message' => '添加成功']);
}
exit;
?>