<?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;
}

ob_start();
try {
    $content = find_content_by_id($contentId);
    if (!$content) {
        throw new Exception('内容不存在（ID: ' . $contentId . '）。');
    }
    if (!isset($content['status']) || $content['status'] !== 'published') {
        throw new Exception('仅已发布内容可静态化。');
    }
    publish_content_static($contentId);
    $strayOutput = ob_get_clean();
    echo json_encode(array(
        'success' => true,
        'id' => $contentId,
        'title' => isset($content['title']) ? (string)$content['title'] : '',
        'message' => '发布成功'
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    $strayOutput = ob_get_clean();
    $errorMsg = $e->getMessage();
    if ($strayOutput !== '' && $strayOutput !== false) {
        $errorMsg .= ' [PHP: ' . strip_tags(substr($strayOutput, 0, 300)) . ']';
    }
    echo json_encode(array(
        'success' => false,
        'id' => $contentId,
        'message' => $errorMsg
    ), JSON_UNESCAPED_UNICODE);
}
