<?php
require_once __DIR__ . '/private/locale.php';
$config = is_readable(__DIR__ . '/private/config.php')
    ? require __DIR__ . '/private/config.php' : array();
$trustedProxies = is_array($config) && isset($config['trusted_proxies']) && is_array($config['trusted_proxies'])
    ? $config['trusted_proxies'] : array();
$queryLanguage = isset($_GET['lang']) && is_string($_GET['lang']) ? $_GET['lang'] : null;
$cookieLanguage = isset($_COOKIE['kaiyue_lang']) && is_string($_COOKIE['kaiyue_lang'])
    ? $_COOKIE['kaiyue_lang'] : null;
$explicit = kaiyue_valid_locale($queryLanguage);
$remembered = $queryLanguage === 'auto' ? null : kaiyue_valid_locale($cookieLanguage);
$country = null;
if ($explicit === null && $remembered === null) {
    $clientIp = kaiyue_client_ip($_SERVER, $trustedProxies);
    $country = kaiyue_country_for_ip(
        $clientIp,
        __DIR__ . '/private/geoip/country.mmdb',
        __DIR__ . '/private/maxmind/autoload.php'
    );
}
$acceptLanguage = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
$locale = kaiyue_resolve_locale($queryLanguage, $cookieLanguage, $country, $acceptLanguage);
$secure = (isset($_SERVER['HTTPS']) && in_array(strtolower((string) $_SERVER['HTTPS']), array('on', '1'), true))
    || (isset($_SERVER['SERVER_PORT']) && (string) $_SERVER['SERVER_PORT'] === '443');
$cookieOptions = array('expires' => 0, 'path' => '/', 'secure' => $secure,
    'httponly' => false, 'samesite' => 'Lax');
if ($explicit !== null) {
    setcookie('kaiyue_lang', $explicit, $cookieOptions);
} elseif ($queryLanguage === 'auto') {
    $cookieOptions['expires'] = time() - 3600;
    setcookie('kaiyue_lang', '', $cookieOptions);
}
$location = './' . $locale . '/';
header('Cache-Control: private, no-store, max-age=0');
header('Pragma: no-cache');
header('Vary: Cookie, Accept-Language');
header('Content-Type: text/html; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('Location: ' . $location, true, 302);
?>
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>凯悦畜牧 · KAIYUE LIVESTOCK</title></head>
<body><p><a href="<?= htmlspecialchars($location, ENT_QUOTES, 'UTF-8') ?>">Continue · 继续访问</a></p>
<nav aria-label="Language"><a href="./zh/" lang="zh">中文</a> · <a href="./en/" lang="en">English</a> · <a href="./es/" lang="es">Español</a> · <a href="./pt/" lang="pt">Português</a></nav></body></html>
