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

register_shutdown_function('track_spider_if_needed');

$_requestUri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';

function beeai_output_frontend_html($html, $maxAge = 60)
{
    $html = (string)$html;
    $etag = '"' . md5($html) . '"';
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: public, max-age=' . max(0, (int)$maxAge));
    header('ETag: ' . $etag);
    if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim((string)$_SERVER['HTTP_IF_NONE_MATCH']) === $etag) {
        http_response_code(304);
        exit;
    }
    echo $html;
    exit;
}

// 先处理 ads.txt（无需依赖域名是否已在系统中绑定）
$__reqPath = (string)parse_url($_requestUri, PHP_URL_PATH);
if ($__reqPath === '/ads.txt' || (isset($_GET['__ads_txt']) && (string)$_GET['__ads_txt'] === '1')) {
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    $cfg = function_exists('plugin_get_config') ? plugin_get_config('google-ads') : array();
    $hostNow = isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '';
    $hostNow = strtolower(trim((string)explode(':', $hostNow)[0]));
    $txt = '';
    if (isset($cfg['per_domain'][$hostNow]) && trim((string)$cfg['per_domain'][$hostNow]) !== '') {
        $txt = (string)$cfg['per_domain'][$hostNow];
    } elseif (isset($cfg['global_ads_txt'])) {
        $txt = (string)$cfg['global_ads_txt'];
    }
    echo $txt;
    exit;
}

// 拦截旧CMS遗留路径，直接返回 410 Gone 加速搜索引擎清除索引
$_pathCheck = strtolower(trim((string)parse_url($_requestUri, PHP_URL_PATH), '/'));
$_legacyPrefixes = array('wp-content/', 'wp-admin/', 'wp-includes/', 'wp-json/');
$_legacyExact = array('wp-login.php', 'xmlrpc.php', 'wp-cron.php', 'wp-config.php');
$_isLegacy = false;
foreach ($_legacyPrefixes as $_lp) {
    if (strpos($_pathCheck, $_lp) === 0) { $_isLegacy = true; break; }
}
if (!$_isLegacy) {
    foreach ($_legacyExact as $_le) {
        if ($_pathCheck === $_le) { $_isLegacy = true; break; }
    }
}
if ($_isLegacy) {
    http_response_code(410);
    header('Content-Type: text/plain; charset=utf-8');
    header('X-Robots-Tag: noindex');
    echo 'Gone - This resource no longer exists.';
    exit;
}

$host = isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '';
$slug = isset($_GET['slug']) ? trim((string)$_GET['slug']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);

if ($slug === '') {
    $requestPath = '';
    if (isset($_SERVER['PATH_INFO']) && trim((string)$_SERVER['PATH_INFO']) !== '') {
        $requestPath = trim((string)$_SERVER['PATH_INFO']);
    } elseif (isset($_SERVER['REQUEST_URI'])) {
        $requestPath = (string)parse_url((string)$_SERVER['REQUEST_URI'], PHP_URL_PATH);
    }

    $scriptName = isset($_SERVER['SCRIPT_NAME']) ? trim((string)$_SERVER['SCRIPT_NAME']) : '';
    $basePath = $scriptName !== '' ? str_replace('\\', '/', dirname($scriptName)) : '';
    if ($basePath === '/' || $basePath === '.') {
        $basePath = '';
    }

    $requestPath = str_replace('\\', '/', trim((string)$requestPath));
    if ($basePath !== '' && strpos($requestPath, $basePath) === 0) {
        $requestPath = substr($requestPath, strlen($basePath));
    }

    $requestPath = trim($requestPath, '/');
    if ($requestPath !== '' && strtolower($requestPath) !== 'index.php') {
        $slug = $requestPath;
    }
}

if ($slug !== '' && strtolower(substr($slug, -5)) === '.html' && strtolower($slug) !== 'sitemap.html') {
    $slug = substr($slug, 0, -5);
}

// 对非页面后缀的静态资源请求直接返回404（如 .jpg .png .webp .css .js .xml 等）
// 排除 sitemap.xml / sitemap.html 等系统动态路由
$_systemSlugs = array('sitemap.xml', 'sitemap.html', 'sitemap', 'robots.txt');
if ($slug !== '' && !in_array(strtolower($slug), $_systemSlugs, true)) {
    $_ext = strtolower(pathinfo($slug, PATHINFO_EXTENSION));
    $_staticExts = array('jpg','jpeg','png','gif','webp','bmp','ico','svg','css','js','xml','json','txt','pdf','zip','rar','mp3','mp4','woff','woff2','ttf','eot','map');
    if ($_ext !== '' && in_array($_ext, $_staticExts, true)) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Not Found';
        exit;
    }
}

if (!db_is_ready()) {
    http_response_code(503);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>蜜蜂AI建站 · 初始化安装</title><style>*{margin:0;padding:0;box-sizing:border-box}body{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#f0f4ff 0%,#e8ecf9 100%);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}.card{background:#fff;border-radius:24px;box-shadow:0 20px 60px rgba(15,23,42,.1);padding:48px 44px;max-width:460px;width:100%;text-align:center}.icon{width:72px;height:72px;margin:0 auto 24px;background:linear-gradient(135deg,#4f46e5,#6366f1);border-radius:18px;display:flex;align-items:center;justify-content:center;box-shadow:0 12px 30px rgba(79,70,229,.25)}.icon svg{width:36px;height:36px;fill:#fff}h1{font-size:22px;color:#0f172a;margin-bottom:10px}p{color:#64748b;font-size:15px;line-height:1.7;margin-bottom:28px}.btn{display:inline-block;padding:14px 36px;background:linear-gradient(135deg,#4f46e5,#6366f1);color:#fff;font-size:16px;font-weight:700;border-radius:14px;text-decoration:none;transition:all .2s;box-shadow:0 8px 24px rgba(79,70,229,.3)}.btn:hover{transform:translateY(-2px);box-shadow:0 12px 32px rgba(79,70,229,.4)}.hint{margin-top:20px;font-size:13px;color:#94a3b8}</style></head><body><div class="card"><div class="icon"><svg viewBox="0 0 24 24"><path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.48.48 0 0 0-.48-.41h-3.84a.48.48 0 0 0-.48.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.49.49 0 0 0-.59.22L2.74 8.87a.48.48 0 0 0 .12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.26.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6A3.6 3.6 0 1 1 12 8.4a3.6 3.6 0 0 1 0 7.2z"/></svg></div><h1>系统尚未初始化安装</h1><p>检测到数据库尚未配置，请先完成安装部署，配置数据库连接和管理员账号后即可使用。</p><a class="btn" href="/install.php">点击安装部署</a><div class="hint">蜜蜂AI建站 · 智能批量建站平台</div></div></body></html>';
    exit;
}

try {
    $domain = find_domain_by_host($host);
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>系统异常</title><style>*{margin:0;padding:0;box-sizing:border-box}body{min-height:100vh;display:flex;align-items:center;justify-content:center;background:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif}.card{background:#fff;border-radius:20px;box-shadow:0 12px 40px rgba(15,23,42,.08);padding:40px;max-width:440px;width:100%;text-align:center}h1{font-size:20px;color:#dc2626;margin-bottom:10px}p{color:#64748b;font-size:14px;line-height:1.7;margin-bottom:20px}.detail{background:#fef2f2;border:1px solid rgba(220,38,38,.15);border-radius:12px;padding:14px 18px;font-size:13px;color:#b91c1c;text-align:left;word-break:break-all}</style></head><body><div class="card"><h1>数据库连接失败</h1><p>系统无法连接到数据库，请检查配置是否正确。</p><div class="detail">' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div></div></body></html>';
    exit;
}

if (!$domain) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo '未找到与当前域名绑定的站点配置。';
    exit;
}

if (!isset($domain['status']) || $domain['status'] !== 'enabled') {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    echo '当前域名未启用访问。';
    exit;
}

// 动态 robots.txt —— 根据当前域名只输出本域名的 Sitemap
if (parse_url($_requestUri, PHP_URL_PATH) === '/robots.txt') {
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    echo get_robots_txt_content(isset($domain['domain']) ? (string)$domain['domain'] : $host);
    exit;
}

// 动态 ads.txt —— 由插件 google-ads 提供全局或按域名内容
if (isset($_GET['__ads_txt']) && (string)$_GET['__ads_txt'] === '1') {
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    $cfg = function_exists('plugin_get_config') ? plugin_get_config('google-ads') : array();
    $hostNow = isset($domain['domain']) ? (string)$domain['domain'] : $host;
    $txt = '';
    if (isset($cfg['per_domain'][$hostNow]) && trim((string)$cfg['per_domain'][$hostNow]) !== '') {
        $txt = (string)$cfg['per_domain'][$hostNow];
    } elseif (isset($cfg['global_ads_txt'])) {
        $txt = (string)$cfg['global_ads_txt'];
    }
    echo $txt;
    exit;
}

$homepageContent = null;
if ($slug !== '') {
    try {
        $homepageContent = find_homepage_published_content_by_domain((int)$domain['id']);
    } catch (Exception $e) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
        echo '页面读取失败：' . $e->getMessage();
        exit;
    }

    if ($homepageContent) {
        $legacyPath = content_legacy_redirect_path($homepageContent);
        if ($legacyPath !== '' && $legacyPath === normalize_content_path($slug)) {
            header('Location: /', true, 301);
            exit;
        }
    }
}

// 动态 sitemap.xml / sitemap.html
if ($slug === 'sitemap.xml' || $slug === 'sitemap') {
    header('Content-Type: application/xml; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    echo build_sitemap_xml((int)$domain['id'], isset($domain['domain']) ? (string)$domain['domain'] : $host);
    exit;
}
if ($slug === 'sitemap.html') {
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: public, max-age=3600');
    echo build_sitemap_html((int)$domain['id'], isset($domain['domain']) ? (string)$domain['domain'] : $host, isset($domain['site_name']) ? (string)$domain['site_name'] : '');
    exit;
}

if ($slug === 'search') {
    $searchQuery = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
    $searchPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    beeai_output_frontend_html(build_search_results_page_html($domain, $searchQuery, $searchPage), 30);
}

// ── 静态文件优先（PHP 兜底，nginx 漏配时仍可命中静态）
//    带分页参数 / 搜索 / sitemap 等动态请求跳过；只对纯页面 GET 请求生效。
//    设计：伪静态开启时全部走动态渲染（菜单/文章等实时更新），静态文件不参与服务；
//    伪静态关闭时（纯静态模式），磁盘有静态文件就直接输出。
$_useStatic = !pseudo_static_enabled()
    && ($_SERVER['REQUEST_METHOD'] === 'GET')
    && empty($_GET['page'])
    && empty($_GET['q'])
    && $slug !== 'sitemap.xml' && $slug !== 'sitemap.html' && $slug !== 'sitemap'
    && $slug !== 'search';

    // 首页跳过静态文件，始终动态渲染，确保 {{latest_articles}} 等模板变量保持最新
    if ($slug === '' || strtolower($slug) === 'index') {
        $_useStatic = false;
    }
if ($_useStatic) {
    $_siteRoot = domain_static_site_root($domain);
    // 候选静态路径：先按文章规则 {slug}.html，再按列表页规则 {slug}/index.html
    $_candidates = array();
    if ($slug === '' || strtolower($slug) === 'index') {
        $_candidates[] = 'index.html';
    } else {
        $_candidates[] = $slug . '.html';
        $_candidates[] = $slug . '/index.html';
    }
    foreach ($_candidates as $_relPath) {
        $_staticFile = $_siteRoot . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $_relPath);
        if (is_file($_staticFile)) {
            header('Content-Type: text/html; charset=utf-8');
            header('X-Served-By: static');
            header('Cache-Control: public, max-age=300');
            readfile($_staticFile);
            exit;
        }
    }
}

// ── URL 规范化（伪静态 OFF 时拒绝软命中）
//    场景：开关 OFF + 无磁盘静态文件，但 nginx 伪静态规则仍把 /foo.html 重写到 PHP，
//    导致 .html 形式的 URL 被静默渲染。这违反 OFF 模式的语义（应当强制走动态 URL）。
//    策略：当原始请求路径以 .html 结尾时，301 跳转到 /index.php?slug=... 规范化 URL。
if (!pseudo_static_enabled()
    && $_SERVER['REQUEST_METHOD'] === 'GET'
    && $slug !== ''
    && $slug !== 'sitemap.xml' && $slug !== 'sitemap.html' && $slug !== 'sitemap' && $slug !== 'search') {
    $_origPath = (string)parse_url($_requestUri, PHP_URL_PATH);
    if (preg_match('#\.html$#i', $_origPath) || preg_match('#/page/\d+/?$#', $_origPath)) {
        // 检查该 slug 是否已发布静态文件（必须 DB 标记 + 磁盘真实存在）；若任一不满足 → 301 到动态 URL
        $_hasStaticOnDisk = false;
        try {
            $_probe = find_published_content_by_domain_and_path((int)$domain['id'], $slug);
        } catch (Exception $_e) { $_probe = null; }
        if ($_probe && !empty($_probe['static_file_path'])) {
            $_diskRoot = domain_static_site_root($domain);
            $_diskFile = $_diskRoot . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $slug) . '.html';
            $_hasStaticOnDisk = is_file($_diskFile);
        }
        if (!$_hasStaticOnDisk) {
            $_target = '/index.php?slug=' . rawurlencode($slug);
            if (!empty($_GET['page'])) {
                $_target .= '&page=' . (int)$_GET['page'];
            }
            header('Location: ' . $_target, true, 301);
            exit;
        }
    }
}

try {
    $content = resolve_frontend_content_by_domain((int)$domain['id'], $slug, $page);
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo '页面读取失败：' . $e->getMessage();
    exit;
}

if (!$content) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo $slug !== '' ? '未找到对应的已发布页面。' : '当前域名下暂无已发布内容。';
    exit;
}

ensure_domains_table_has_template_pack();
$packCode = domain_template_pack($domain);

if (is_array($content) && isset($content['__page_type']) && $content['__page_type'] === 'article_archive') {
    beeai_output_frontend_html(build_default_article_list_page_html($domain), 60);
}

if (is_array($content) && isset($content['__page_type']) && $content['__page_type'] === 'menu_archive') {
    $menu = find_menu_by_id(isset($content['menu_id']) ? (int)$content['menu_id'] : 0);
    if (!$menu) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo '未找到对应栏目。';
        exit;
    }
    beeai_output_frontend_html(build_default_menu_archive_page_html($domain, $menu, isset($content['page']) ? (int)$content['page'] : $page), 60);
}

if (is_array($content) && isset($content['__page_type']) && $content['__page_type'] === 'tag_archive') {
    $tag = find_tag_by_domain_and_slug((int)$domain['id'], isset($content['tag_slug']) ? (string)$content['tag_slug'] : '');
    if (!$tag || (isset($tag['status']) && $tag['status'] !== 'enabled')) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo '未找到对应标签。';
        exit;
    }
    beeai_output_frontend_html(build_default_tag_archive_page_html($domain, $tag, isset($content['page']) ? (int)$content['page'] : $page), 60);
}

$variables = build_content_render_variables($content);

$templateType = isset($content['template_type']) ? trim((string)$content['template_type']) : '';
$isArticle = $templateType === 'article' || is_article_source_type(isset($content['source_type']) ? (string)$content['source_type'] : '');
$pageType = $isArticle ? 'article' : 'homepage';

// 如果内容绑定了页面模板，优先使用页面模板渲染（不注入站点地图）
$pageTemplatePack = isset($content['page_template_pack']) ? trim((string)$content['page_template_pack']) : '';
if ($pageTemplatePack !== '' && load_template_pack_manifest($pageTemplatePack)) {
    $GLOBALS['beeai_skip_sitemap_injection'] = true;
    $html = render_template_pack_page($pageTemplatePack, 'page', $variables);
    unset($GLOBALS['beeai_skip_sitemap_injection']);
    if ($html !== '') {
        beeai_output_frontend_html($html, 60);
    }
}

if ($packCode !== '' && load_template_pack_manifest($packCode)) {
    $html = render_template_pack_page($packCode, $pageType, $variables);
    if ($html !== '') {
        beeai_output_frontend_html($html, 60);
    }
}

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

beeai_output_frontend_html($html, 60);
