<?php

function init_site_theme(?string $theme_name = null)
{
    require('sites.php');

    if (! $theme_name) {
        $theme_name = array_keys($sites)[0];
    }

    $site_id = 1;
    if (isset($sites[$theme_name]['site_id'])) {
        $site_id = (int)$sites[$theme_name]['site_id'];
    }

    define('SITE', $theme_name);
    define('THEME_PATH', '/sites/' . $theme_name);
    define('DEFAULT_THEME_PATH', '/sites/default');
    define('THEME_URL', THEME_PATH);
    define('SITE_ID', $site_id);
}


// CLI?
if (php_sapi_name() == "cli") {
    $theme_name = array_keys($sites)[0];
    init_site_theme($theme_name);

    return;
}

$host = '';
if (count($sites) == 1) {
    // If only one host, use this as default.
    $hosts = array_keys($sites);
    $host = reset($hosts);
} else {
    if (isset($_SERVER['HTTP_HOST'])) {
        $host = $_SERVER['HTTP_HOST'];
    } else {
        // Check to see if --site="ASDF" has been added to script
        $opts = getopt('', ['site:']);
        if (is_array($opts) && array_key_exists('site', $opts)) {
            $host = $opts['site'];
        }
    }
}
if ($host == '') {
    throw new Exception('No host defined');
}


// Cookie set?
$cookie_selected_theme = $_COOKIE['selected_theme'] ?? '';
if (array_key_exists($cookie_selected_theme, $sites)) {
    init_site_theme($cookie_selected_theme);

    return;
}


// From URL?
foreach ($sites as $site_id => $site) {
    foreach ($site['urls'] as $url) {
        if ($host == $url || $host == 'www.'.$url || $host == $site_id) {
            init_site_theme($site_id);

            return;
        }
    }
}

// Load the first one
init_site_theme();
