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

$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('未找到该域名。');
    }
    if (!isset($domain['status']) || $domain['status'] !== 'enabled') {
        throw new Exception('仅启用状态的域名支持全量静态发布。');
    }
    ensure_content_storage_ready();
    $contents = list_published_contents_by_domain($domainId);
    $ids = array();
    foreach ($contents as $c) {
        if (isset($c['id'])) {
            $ids[] = (int)$c['id'];
        }
    }

    echo json_encode(array(
        'success' => true,
        'domain' => array(
            'id' => (int)$domain['id'],
            'domain' => isset($domain['domain']) ? (string)$domain['domain'] : '',
            'site_name' => isset($domain['site_name']) ? (string)$domain['site_name'] : ''
        ),
        'content_ids' => $ids,
        'total' => count($ids)
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
