<?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();

$rawIds = isset($_POST['ids']) ? $_POST['ids'] : '';
if (is_string($rawIds)) {
    $ids = array_values(array_unique(array_filter(array_map('intval', explode(',', $rawIds)), function ($v) { return $v > 0; })));
} elseif (is_array($rawIds)) {
    $ids = array_values(array_unique(array_filter(array_map('intval', $rawIds), function ($v) { return $v > 0; })));
} else {
    $ids = array();
}

if (empty($ids)) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => '无效的内容ID列表。'), JSON_UNESCAPED_UNICODE);
    exit;
}

if (count($ids) > 20) {
    $ids = array_slice($ids, 0, 20);
}

$results = array();

foreach ($ids as $contentId) {
    try {
        $content = find_content_by_id($contentId);
        if (!$content) {
            throw new Exception('内容不存在');
        }
        if (!isset($content['status']) || $content['status'] !== 'draft') {
            throw new Exception('非草稿状态');
        }
        update_content_status($contentId, 'published');
        $results[] = array(
            'success' => true,
            'id' => $contentId,
            'title' => isset($content['title']) ? (string)$content['title'] : ''
        );
    } catch (Exception $e) {
        $results[] = array(
            'success' => false,
            'id' => $contentId,
            'title' => isset($content['title']) ? (string)$content['title'] : '',
            'message' => $e->getMessage()
        );
    }
}

echo json_encode(array('success' => true, 'results' => $results), JSON_UNESCAPED_UNICODE);
