<?php
/**
 * 根据标题生成文章封面图（复用 generate_article_cover_image 逻辑）
 * 输入：POST { title }
 * 输出：JSON { ok, url, error }
 */
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

@ini_set('display_errors', '0');
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

ob_start();

$title = isset($_POST['title']) ? trim((string)$_POST['title']) : '';

try {
    if ($title === '') {
        throw new Exception('请先填写标题再生成封面图。');
    }

    $relativePath = generate_article_cover_image($title, array('width' => 1200, 'height' => 630));
    if ($relativePath === '') {
        throw new Exception('封面图生成失败，请确认服务器已启用 GD 扩展。');
    }
    $url = normalize_public_asset_url($relativePath);
    if ($url === '') {
        $url = '/' . ltrim($relativePath, '/');
    }

    ob_end_clean();
    echo json_encode(array(
        'ok' => true,
        'url' => $url
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode(array(
        'ok' => false,
        'error' => $e->getMessage()
    ), JSON_UNESCAPED_UNICODE);
}
