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

// 列表页静态化可能耗时，放宽时间
@set_time_limit(300);

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

$domainId = isset($_POST['domain_id']) ? (int)$_POST['domain_id'] : 0;
if ($domainId <= 0) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => '域名 ID 无效。'), JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $domain = find_domain_by_id($domainId);
    if (!$domain) {
        throw new Exception('未找到该域名。');
    }
    ob_start();
    $written = publish_domain_archive_pages($domain);
    $stray = ob_get_clean();

    write_publish_log(array(
        'domain_id' => $domainId,
        'content_id' => 0,
        'publish_scope' => 'domain',
        'publish_action' => 'bulk_static_publish',
        'status' => 'success',
        'message' => '域名全量静态发布完成（弹窗模式）。',
        'meta_json' => json_encode(array('archive_pages' => count($written)), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    ));

    echo json_encode(array(
        'success' => true,
        'archive_pages' => $written,
        'count' => count($written)
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
