<?php

class mailbeez_frontmatter
{
    static $frontmatter_path = 'undefined';

    /**
     * Resolve a languages_id to a language directory (e.g. "english", "german").
     * This is request-local logic and must NOT mutate session state.
     *
     * @param mixed $lng_id
     * @return string|null
     */
    static function _resolve_language_directory_by_id($lng_id)
    {
        $requested_lng_id = (int) $lng_id;
        if ($requested_lng_id <= 0) {
            return null;
        }

        if (!function_exists('mh_get_languages')) {
            return null;
        }

        $languagesArray = mh_get_languages();
        if (!is_array($languagesArray)) {
            return null;
        }

        foreach ($languagesArray as $l) {
            $id = isset($l['id']) ? (int) $l['id'] : (int) ($l['languages_id'] ?? 0);
            if ($id === $requested_lng_id) {
                $dir = isset($l['directory']) ? (string) $l['directory'] : null;
                return ($dir !== '') ? $dir : null;
            }
        }

        return null;
    }

    /**
     * Resolve a language directory (e.g. "english", "german") to a languages_id.
     * This is request-local logic and must NOT mutate session state.
     *
     * @param string|null $dir
     * @return int|null
     */
    static function _resolve_language_id_by_directory($dir)
    {
        if ($dir === '' || $dir === null) {
            return null;
        }

        if (!function_exists('mh_get_languages')) {
            return null;
        }

        $languagesArray = mh_get_languages();
        if (!is_array($languagesArray)) {
            return null;
        }

        foreach ($languagesArray as $l) {
            $directory = isset($l['directory']) ? (string) $l['directory'] : null;
            if ($directory === $dir) {
                return isset($l['id']) ? (int) $l['id'] : (int) ($l['languages_id'] ?? 0);
            }
        }

        return null;
    }

    static function _init_dialog($frontmatter_path, $view)
    {
        $smarty = new mh_Smarty;
        $smarty->setTemplateDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . $frontmatter_path . "views/$view/templates/");
        $smarty->setConfigDir(MH_DIR_FS_CATALOG . MH_ROOT_PATH . $frontmatter_path . "views/$view/languages/");
        $smarty->setCompileCheck(true);
        $smarty->setCompileId(md5($frontmatter_path) . $view);
        $smarty->setCaching(false);

        // Session language (storefront/admin share session state)
        $language_session = isset($_SESSION['language']) ? (string) $_SESSION['language'] : 'english';
        $languages_id_session = isset($_SESSION['languages_id']) ? (int) $_SESSION['languages_id'] : null;

        // Effective language for THIS request (may be overridden by ?lng_id=...)
        $language = $language_session ?: 'english';
        $languages_id = $languages_id_session;

        // --- Session-independent language override: ?lng_id=<languages_id> ---
        // This must affect ONLY the current request and must not persist to the session.
        $requested_lng_id = (int) mh_get('lng_id');
        $requested_language = self::_resolve_language_directory_by_id($requested_lng_id);

        $confDir = $smarty->getConfigDir(0);
        $language_found = false;

        // 1. Try ?lng_id=<languages_id> override
        if ($requested_language && file_exists($confDir . $requested_language . '.conf')) {
            $language = $requested_language;
            $languages_id = $requested_lng_id;
            $language_found = true;
        }
        // 2. Try current $language (already set from session or fallback 'english')
        elseif ($language && file_exists($confDir . $language . '.conf')) {
            $language_found = true;
        }
        // 3. Try session language if it differs from current effective language
        elseif ($language_session && $language_session !== $language && file_exists($confDir . $language_session . '.conf')) {
            $language = $language_session;
            $languages_id = $languages_id_session;
            $language_found = true;
        }

        // 4. Fallback to english if not already using it and it exists
        if (!$language_found && $language !== 'english' && file_exists($confDir . 'english.conf')) {
            $language = 'english';
            $languages_id = self::_resolve_language_id_by_directory($language);
            $language_found = true;
        }

        // 5. Last resort: if still no match, pick the first available .conf file to avoid Smarty error
        if (!$language_found && !file_exists($confDir . $language . '.conf')) {
            $available_confs = glob($confDir . '*.conf');
            if (!empty($available_confs)) {
                $language = basename($available_confs[0], '.conf');
                $languages_id = self::_resolve_language_id_by_directory($language);
                $language_found = true;
            } else {
                // If NO .conf files exist at all, we fall back to english name and hope for the best
                $language = 'english';
                $languages_id = self::_resolve_language_id_by_directory($language);
            }
        }

        if ($language_found) {
            $smarty->configLoad($language . '.conf');
        }

        $mh_url = mh_cfg('MH_CATALOG_SERVER') . mh_cfg('MH_DIR_WS_CATALOG') . mh_cfg('MH_ROOT_PATH');
        $resource_root = $mh_url . 'common/';

        $smarty->assign('mailhive_path', $mh_url);
        $smarty->assign('privacy_policy_url', mh_cfg('MAILBEEZ_CONFIG_SITEBEEZ_PRIVACY_POLICY_URL', 'https://' . $_SERVER['SERVER_NAME']));

        if (stristr(MAILBEEZ_MAILHIVE_URL_DIRECT, '.php')) {
            // mailhive.php/api/public/v1.0/newsletter/add/
            $smarty->assign('entrypoint_url', MAILBEEZ_MAILHIVE_URL_DIRECT . '/');
        } else {
            // /m/api/public/v1.0/newsletter/add/
            $smarty->assign('entrypoint_url', MAILBEEZ_MAILHIVE_URL_DIRECT);
        }

        $smarty->assign(array(
                'js' => array(
                    'micromodal' => $resource_root . 'vendor/ghosh/micromodal/micromodal.min.js?ver=' . mh_cfg('MAILBEEZ_VERSION'),
                ),
                'css' => array(
                    'bootstrap' => $resource_root . 'vendor/bootstrap/css/bootstrap.min.css?ver=' . mh_cfg('MAILBEEZ_VERSION'),
                    'bootstrap_v3' => $resource_root . 'vendor/bootstrap/css/bootstrap.min.css?ver=' . mh_cfg('MAILBEEZ_VERSION'),
                    'bootstrap_v4' => $resource_root . 'vendor/bootstrap-4.1.1/css/bootstrap.min.css?ver=' . mh_cfg('MAILBEEZ_VERSION'),
                    'fontawesome' => $resource_root . 'css/font-awesome/css/font-awesome.min.css?ver=' . mh_cfg('MAILBEEZ_VERSION')
                )
            )
        );

        if (mh_get('language')) {
            $setLng = mh_get('language');
            $smarty->assign('setLanguage', mh_get('language')); // url parameter
            $smarty->assign('lngUrl', "&language={$setLng}"); // url to set language
        }

        if ($requested_lng_id > 0) {
            $smarty->assign('setLngId', $requested_lng_id); // url parameter
            // Default language-preserving URL param for links within the dialog
            if (!mh_get('language')) {
                $smarty->assign('lngUrl', "&lng_id={$requested_lng_id}");
            }
            $smarty->assign('lngIdUrl', "&lng_id={$requested_lng_id}");
        }

        $smarty->assign('language', $language); // available .conf file language
        $smarty->assign('language_session', $language_session); // original
        $smarty->assign('language_effective', $language); // effective for this request
        $smarty->assign('languages_id', $languages_id); // effective for this request
        $smarty->assign('languages_id_session', $languages_id_session); // original
        return $smarty;
    }
}