<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();
session_write_close();

header('Content-Type: application/json; charset=utf-8');

if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? (string)$_SERVER['REQUEST_METHOD'] : 'GET') !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => '仅允许 POST 请求。'), JSON_UNESCAPED_UNICODE);
    exit;
}

require_csrf();
$contentId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($contentId <= 0) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => '无效的内容ID。'), JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $content = find_content_by_id($contentId);
    if (!$content) {
        throw new Exception('内容不存在（ID: ' . $contentId . '）。');
    }
    if (!isset($content['status']) || $content['status'] !== 'draft') {
        throw new Exception('仅草稿状态的内容可批量发布（当前状态：' . (isset($content['status']) ? $content['status'] : 'unknown') . '）。');
    }
    update_content_status($contentId, 'published');
    echo json_encode(array(
        'success' => true,
        'id' => $contentId,
        'title' => isset($content['title']) ? (string)$content['title'] : '',
        'message' => '发布成功'
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    echo json_encode(array(
        'success' => false,
        'id' => $contentId,
        'message' => $e->getMessage()
    ), JSON_UNESCAPED_UNICODE);
}
