<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';

$contentId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($contentId <= 0) {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo '缺少内容ID。';
    exit;
}

try {
    $content = find_content_by_id($contentId);
    if (!$content) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo '未找到对应内容。';
        exit;
    }

    $domain = find_domain_by_id(isset($content['domain_id']) ? (int)$content['domain_id'] : 0);
    if ($domain) {
        $content['domain_name'] = isset($domain['domain']) ? (string)$domain['domain'] : '';
        $content['domain_site_name'] = isset($domain['site_name']) ? (string)$domain['site_name'] : '';
    }

    ensure_domains_table_has_template_pack();
    $packCode = $domain ? domain_template_pack($domain) : '';

    $variables = build_content_render_variables($content);

    if ($packCode !== '' && load_template_pack_manifest($packCode)) {
        $contentPath = isset($content['path']) ? (string)$content['path'] : '';
        $isHomepage = in_array($contentPath, array('index', 'home', ''), true);
        $pageType = $isHomepage ? 'homepage' : 'article';
        $html = render_template_pack_page($packCode, $pageType, $variables);
        if ($html !== '') {
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
    }

    $template = find_template_by_id(isset($content['template_id']) ? (int)$content['template_id'] : 0);
    if (!$template) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo '未找到内容绑定模板或模板套件。';
        exit;
    }

    $content['html_content'] = isset($template['html_content']) ? (string)$template['html_content'] : '';
    $content['css_content'] = isset($template['css_content']) ? (string)$template['css_content'] : '';
    $content['template_type'] = isset($template['type']) ? (string)$template['type'] : '';

    $html = render_template_html(
        $content['html_content'],
        $content['css_content'],
        $variables
    );

    header('Content-Type: text/html; charset=utf-8');
    echo $html;
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo '预览失败：' . $e->getMessage();
}
