<?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;
    }

    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;


        $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')
                )
            )
        );
        // --- 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);
        if ($requested_language) {
            $language = $requested_language;
            $languages_id = $requested_lng_id;
        }
        // Load Smarty .conf file: prefer effective language, otherwise fall back to session language
        $confDir = $smarty->getConfigDir(0);
        if ($language && file_exists($confDir . $language . '.conf')) {
            $smarty->configLoad($language . '.conf');
        } elseif ($language_session && file_exists($confDir . $language_session . '.conf')) {
            $language = $language_session;
            $languages_id = $languages_id_session;
            $smarty->configLoad($language . '.conf');
        }

        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;
    }
}