<?php
declare(strict_types=1);
/**
 * 前台入口：按访问域名匹配站点，解析展示语言，记录访问统计，渲染落地页。
 */
define('APP_RUNNING', true);
define('APP_CONTEXT', 'front');
require __DIR__ . '/includes/bootstrap.php';

$host = current_host();
$fallbackLang = default_language();
if ($host === '') {
    app_error_page(400, tr('err_bad_request_title', $fallbackLang), tr('err_bad_request_message', $fallbackLang));
}

$site = site_by_host($host);
if ($site === null) {
    $known = site_by_host_any($host);
    if (is_array($known)) {
        app_error_page(503, tr('err_unavailable_title', $fallbackLang), tr('err_unavailable_message', $fallbackLang));
    }
    app_error_page(404, tr('err_not_found_title', $fallbackLang), tr('err_not_found_message', $fallbackLang));
}

$siteId = (int) $site['id'];
set_language_config(isset($site['language_config']) ? (string) $site['language_config'] : null);

/** 把一个查询参数处理完就回到干净 URL，避免同页多份地址影响收录与统计 */
$stripQuery = static function (array $drop): never {
    $query = is_array($_GET) ? $_GET : [];
    foreach ($drop as $key) unset($query[$key]);
    $qs = http_build_query($query);
    redirect_to(site_url() . ($qs !== '' ? '?' . $qs : ''));
};

// 访客手动切换语言：?lang=xx
if (isset($_GET['lang'])) {
    $wanted = normalize_lang_code((string) $_GET['lang']);
    if ($wanted !== '' && language_available($wanted)) language_cookie_store($wanted);
    $stripQuery(['lang']);
}

// 像素同意结果：?pixel_consent=granted|declined
if (isset($_GET['pixel_consent'])) {
    pixel_consent_store(strtolower((string) $_GET['pixel_consent']));
    $stripQuery(['pixel_consent']);
}

$lang = resolve_language($site, null, language_cookie_value());
$links = site_links($siteId, true);
$pixels = site_pixels($siteId, true);

stats_track($siteId, 'pageview');

$canonical = (is_https() ? 'https://' : 'http://') . $host . site_url();
render_landing($site, $links, $pixels, $lang, $canonical);