<?php
/**
 * 加载站点 check_config 配置（define 常量）
 */
class ConfigLoader
{
    public static function loadFile($configFile)
    {
        if (file_exists($configFile)) {
            include $configFile;
        }
    }

    /**
     * @return string 实际加载的配置名
     */
    public static function loadByName($configName, $baseDir = null)
    {
        $baseDir    = $baseDir ?: dirname(__DIR__);
        $configName = self::sanitizeConfigName($configName);
        $configFile = $baseDir . '/check_config/' . $configName . '_config.php';
        if (file_exists($configFile)) {
            self::loadFile($configFile);
            return $configName;
        }
        self::loadFile($baseDir . '/check_config/index_config.php');
        return 'index';
    }

    /**
     * @return string 实际加载的配置名
     */
    public static function loadByHost($host, $baseDir = null)
    {
        $baseDir = $baseDir ?: dirname(__DIR__);
        if (!class_exists('DomainRepository', false)) {
            require_once dirname(__DIR__) . '/lib/Cloak/DomainRepository.php';
        }
        $name = DomainRepository::resolveConfigNameForHost((string) $host, $baseDir);
        return self::loadByName($name, $baseDir);
    }

    /**
     * 同域多落地页：入口脚本有独立配置时优先脚本名；否则按 HTTP Host（多站/宝塔）；再回退脚本名或 index
     *
     * @return string 实际加载的配置名
     */
    public static function loadForRequest($scriptBaseName, $host = null)
    {
        $host = $host ?? ($_SERVER['HTTP_HOST'] ?? '');
        $baseDir = dirname(__DIR__);
        $scriptSanitized = self::sanitizeConfigName((string) $scriptBaseName);
        $scriptConfigFile = $baseDir . '/check_config/' . $scriptSanitized . '_config.php';
        $scriptConfigExists = $scriptSanitized !== 'index'
            && $scriptSanitized !== 'ip_check'
            && file_exists($scriptConfigFile);
        if ($scriptConfigExists) {
            return self::loadByName($scriptSanitized);
        }
        if ($host !== '') {
            return self::loadByHost($host);
        }
        if ($scriptBaseName !== null && $scriptBaseName !== '') {
            return self::loadByName($scriptBaseName);
        }
        return self::loadByName('index');
    }

    public static function sanitizeConfigName($name)
    {
        $name = trim((string) $name);
        $name = str_replace('.php', '', $name);
        if ($name === '' || !preg_match('/^[a-zA-Z0-9_-]+$/', $name)) {
            return 'index';
        }
        return $name;
    }
}
