<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{

    public $showMobileVersion = false;

    public function __construct($id, $module = null)
    {
        $url = @$_REQUEST['url'];
        if (!isset($url)) {
            $url = '';
        }
        $secureCon = Yii::app()->request->getIsSecureConnection();
        if (!($secureCon && startsWith($url, 'DeploymentService'))) {
            if (Yii::app()->detectMobileBrowser->showMobile) {
                $this->showMobileVersion = true;
                $this->layout = '//layouts/mobile';
            }
        }
        parent::__construct($id, $module);
        
        $this->checkFirstRun();
        // If there is a post-request, redirect the application to the provided url of the selected language

        if (Yii::app()->getRequest()->getParam('switchUser')) {
            // Get new user id
            $newUserId = $_POST['switchUser'];
            $this->setNewSudoUser($newUserId);
        }

        $this->setUserLanguage();

        if (isset($_GET['pageSize']) && is_array($_GET['pageSize'])) {
            $pageSizes = Yii::app()->user->getState('pageSize', array());

            foreach ($_GET['pageSize'] as $gridId => $value) {
                $pageSizes[$gridId] = (int) $value;

                Yii::app()->user->setState('pageSize', $pageSizes);
                unset($_GET['pageSize']);
            }
        }
    }

    public function render($view, $data = null, $return = false)
    {
        $notMobileViews = array('error', 'rebootScreen', 'statusScreen', 'shutdownScreen');
        if ($this->showMobileVersion) {
            if (!in_array($view, $notMobileViews)) {
                $view = "mobile_" . $view;
            }
        }

        return parent::render($view, $data, $return);
    }

    public function renderPartialWithContextHelp($view, $data = null, $return = false, $processOutput = false)
    {
        $translatemode = Yii::app()->user->translateMode ? "true" : "false";
        cs()->registerScript('ContextHelp', "
        $(function()
        {
            contextHelper = $.ContextHelp({
                translateMode:$translatemode
            });
        });", CClientScript::POS_END);

        $content = $this->renderPartial($view, $data, true, $processOutput);
        $html = CHtml::tag('div', array('class' => 'modalContent-container'), $content);
        $contextHelpContent = CHtml::tag('div', array('class' => 'contextHelp-content'));
        $html.= CHtml::tag('div', array('class' => 'contextHelp-container contextHelp-siteBar'), $contextHelpContent);
        if ($return) {
            return $html;
        } else {
            echo $html;
        }
    }

    public function checkFirstRun()
    {
        if (app()->params->applianceMode && app()->urlManager->parseUrl(app()->request) === 'site/reboot') {
            return;
        }
        
        $isRequestToWizard = !isset($this->module) ? false : $this->module->id == 'wizard';
        
        // redirect to wizard if system not initialized an user is not allredy on wizard
        if (cfg('systemInitialized') != '1' && !$isRequestToWizard && $this->id != 'translation') {
            
            $this->redirect(url('wizard'));
        }
    }

    private function setNewSudoUser($newUserId)
    {
        $sudoUserList = AccessManager::getSudoUsersListData();
        foreach ($sudoUserList as $value) {
            if (key_exists($newUserId, $value)) {
                Yii::app()->user->setState('sudoUser', $newUserId);
            }
        }
    }

    private function setUserLanguage()
    {
        // set default language
        app()->language = cfg("GUI_LANGS");

        if (Yii::app()->getRequest()->getParam('language')) {
            $lang = Yii::app()->getRequest()->getParam('language');

            Yii::app()->language = $lang;
            Yii::app()->user->setState('language', $lang);
            $cookie = new CHttpCookie('language', $lang);
            $cookie->expire = time() + (60 * 60 * 24 * 365); // (1 year)
            Yii::app()->request->cookies['language'] = $cookie;

            $this->redirect(Yii::app()->request->urlReferrer);
        } else if (Yii::app()->user->hasState('language')) {
            Yii::app()->language = Yii::app()->user->getState('language');
        } else if (isset(Yii::app()->request->cookies['language'])) {
            if (!isset($this->module) || $this->module->id !== "wizard") {
                Yii::app()->language = Yii::app()->request->cookies['language']->value;
            }
        }
    }

    public function sessionIsValide()
    {
        if (isset($_SESSION) && !empty($_SESSION)) {
            return true;
        }

        return false;
    }

    public function createMultilanguageReturnUrl($lang = 'en_us')
    {
        if (count($_GET) > 0) {
            $arr = $_GET;
            $arr['language'] = $lang;
        } else {
            $arr = array('language' => $lang);
        }
        return $this->createUrl('', $arr);
    }

    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout = '//layouts/column1';

    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();

    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();

    public function getHelpUrl($key = null, $modal = false)
    {
        if ($key == null) {
            $key = $this->module->id . '-' . $this->action->id;
        }
        $addModal = "";
        if ($modal) {
            $addModal = "-modal";
        }

        // FIXME ! check the rewrite rules from nginx (in my case the old return value was not working ...)
        $currentLanguage = app()->language;
        $lang = $currentLanguage != "de_de" ? "en" : "de"; // FIXME get list of supported languages ...
        $version = PhonalisaLicenseManager::getVersion(true);

        return Yii::app()->params->helpBaseUrl . "/$version/$lang/#" . $key . $addModal;
    }

    public function getHelpLink($key = null)
    {
        if (!Yii::app()->params->helpBaseUrl) {
            return '';
        }
        $url = Yii::app()->controller->getHelpUrl($key);
        // ?lang=de&version=6.0.5.1&id=
        return l('', $url, array('class' => 'help', 'target' => '_blank'));
    }
}
