<?php

class SiteController extends Controller
{

    public function __construct($id, $module = null)
    {
        // Set alias for widgets direcory
        //FIXME : can we set this Path of Alias in config ??
        Yii::setPathOfAlias('widgets', Yii::getPathOfAlias('application.extensions.widgets'));
        parent::__construct($id, $module);
    }

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            'oauth' => array(
                // the list of additional properties of this action is below
                'class' => 'ext.hoauth.HOAuthAction',
                // Yii alias for your user's model, or simply class name, when it already on yii's import path
                // default value of this property is: User
                'model' => 'User',
                // map model attributes to attributes of user's social profile
                // model attribute => profile attribute
                // the list of avaible attributes is below
                'attributes' => array(
                    'email' => 'email',
                    'fname' => 'firstName',
                    'lname' => 'lastName',
                    'gender' => 'genderShort',
                    'birthday' => 'birthDate',
                    // you can also specify additional values,
                    // that will be applied to your model (eg. account activation status)
                    'acc_status' => 1,
                ),
            ),
            // this is an admin action that will help you to configure HybridAuth
            // (you must delete this action, when you'll be ready with configuration, or
            // specify rules for admin role. User shouldn't have access to this action!)
            'oauthadmin' => array(
                'class' => 'ext.hoauth.HOAuthAdminAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {

        if (Yii::app()->user->isGuest) {
            $this->actionLogin();
        } else {

            $url = $this->createUrl("homeUCItem/default/index", array());

            $this->redirect($url);
        }

        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        //$this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        $this->layout = '//layouts/column2';

        if ($error = Yii::app()->errorHandler->error) {

            if (isset($_POST['ergophone'])) {
                echo $error['message'];
                die('error');
            }

            if (isset($_REQUEST['r']) && $_REQUEST['r'] == 'provisioningGeneral/default/dial') {
                echo $error['message'];
                die();
            }

            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                $this->render('error', $error);
            }
        }
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {

        $this->setDefaultLanguage();
        if ($this->showMobileVersion) {
            $this->layout = 'mobile';
        } else {
            $this->layout = 'clean';
        }

        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }

        // display the login form
        $this->render('login', array('model' => $model));
    }

    public function actionResetPassword($id = null)
    {
        $this->setDefaultLanguage();
        $this->layout = 'clean';

        $model = new User();
        if (!$id) {
            $this->render('resetPassword', array('model' => $model, 'expiredLink' => false));
        } else {

            $recoveryLink = OneTimeLink::model()->findByPk($id);
            if (!$recoveryLink) {
                //throw Exeption ... link expired ...
                $this->render('resetPassword', array('model' => $model, 'expiredLink' => true));
            } else {
                $this->renderPasswordResetForm($recoveryLink);
            }
        }
    }

    private function setDefaultLanguage()
    {
        app()->language = cfg("GUI_LANGS");
        app()->user->setState("language", cfg("GUI_LANGS"));
    }

    private function renderPasswordResetForm($recoveryLink)
    {
        $model = User::model()->findByPk($recoveryLink->user_id);

        if (isset($_POST['User'])) {
            if ($this->saveNewPasword($model, $recoveryLink)) {
                $this->redirect(url('site/login'));
            }
        }
        $this->render('resetPasswordForm', array('model' => $model, 'expiredLink' => false));
    }

    private function saveNewPasword(&$model, $recoveryLink)
    {
        if (
                $_POST['User']['password'] != '' &&
                $_POST['User']['password'] == $_POST['User']['confirmPassword']
        ) {
            $model->password = $_POST['User']['password'];
            //NOTE : fix for User::beforSave()
            $model->scenario = 'firstUser';
            if ($model->save()) {
                return $recoveryLink->delete();
            }
        } else {
            if ($_POST['User']['password'] != '') {
                $error = __("USER_MODEL_PHONESETTINGS_CREDENTIALS_PASSWORD_REPEAT_ERROR_MESSAGE");
            } else {
                $error = __("RESET_PASSWORD_ERROR_NO_PASSWORD_DEFINED");
            }

            $model->addError('password', $error);
        }
        return false;
    }

    public function actionAjaxResetPassword()
    {

        $userName = $_POST['username'];
        $userModel = User::model()->findByAttributes(array('name' => $userName));
        if (!$userModel) {
            $alertText = "RESET_PASSWORD_USER_NOT_FOUND_ERROR";
            echo $this->alert($alertText, 'error', url('site/login'));
            app()->end();
        } else {
            if ($userModel->email) {

                // generate oneTimeLink ...
                $recoveryLink = new OneTimeLink();
                $recoveryLink->user_id = $userModel->id;
                $recoveryLink->type = OneTimeLink::TYPE_PASSWORD_RECOVERY;


                if (!$recoveryLink->save()) {
                    echo $this->alert(
                            'could not create recovery link, please ask your system administrator for help.', 'error', url('site/login')
                    );
                    app()->end();
                }

                $mail = new EMail();
                $mail->subject = __("RESET_PASSWORD_RECOVERY_EMAIL_SUBJECT");
                $mail->recipient = $userModel->email;
                $mail->text = str_replace("<br />", "\r\n", __("RESET_PASSWORD_RECOVERY_EMAIL_TEXT", true, 'messages', array("{recoveryLink}" => $recoveryLink->getLink(false))));
                $mail->type = EmailType::EmailTypePasswordRecovery;

                if ($mail->save()) {
                    $alertText = "RESET_PASSWORD_EMAIL_SEND_SUCCESS_MESSAGE";
                    echo $this->alert($alertText, 'success', url('site/login'));
                } else {
                    $alertText = "RESET_PASSWORD_EMAIL_SEND_FAILED_ERROR";
                    echo $this->alert($alertText, 'error', url('site/login'));
                }
            } else {
                $alertText = "RESET_PASSWORD_NO_EMAIL_ADDRESS_FOUND_ERROR";

                echo $this->alert($alertText, 'error', url('site/login'));
            }
        }
    }

    public function alert($message, $type, $url, $asJSON = true)
    {
        if ($asJSON) {
            return json_encode(array('message' => __($message), "translationId" => $message, 'type' => $type, 'url' => $url));
        } else {

            $html = "<div
                  data-translation-id =" . $message . "
		  class='alert alert-block alert-" . $type . "'
		  style='
			  margin-left:28px;
			  margin-right: 28px;
			  margin-top: -30px;
			  padding: 5px 0;
		  '>
		  " . __($message) . "
	      </div>";
            if ($url) {
                $html.=l(__("GLOBAL_BACK"), url('site/login'));
            }
            return $html;
        }
    }

    public function actionAjaxLogin()
    {

        $model = new LoginForm;

        if (isset($_POST['LoginForm'])) {

            $model->attributes = $_POST['LoginForm'];

            if ($model->validate() && $model->login()) {
                $this->deleteHostFromBlockedHostModel();
                $response['logedIn'] = true;
                $response['returnUrl'] = Yii::app()->user->returnUrl;
            } else {
                $this->writeLoginTryToBlockedHostModel($model->username);
                $response['logedIn'] = false;
            }
        }

        //Hacked by S.Spr - renderPartitial does not work any more cause of some bootstrap fuck'n output! FIXME!
        header('Content-type: application/json');
        Yii::app()->user->setState('fadePageIn', true);
        echo json_encode($response);

        //$this->renderPartial('loginAjax', array('loginResult'=>$response), false, true);
    }

    protected function writeLoginTryToBlockedHostModel($username)
    {
        $host = app()->request->getUserHostAddress();
        $model = BannedHost::model()->findByAttributes(array('host' => $host));
        if (!$model) {
            $model = new BannedHost();
            $model->host = $host;
        }
        $model->increaseFaildLoginCount();
        $logMsg = 'Host "' . $model->host . '" authentication with username "' . $username . '" failed! Attempt: ' . $model->count;
        Log::w($logMsg, 'PhonalisaFirewall');
        $model->save();
    }

    protected function deleteHostFromBlockedHostModel()
    {
        $host = app()->request->getUserHostAddress();
        $model = BannedHost::model()->findByAttributes(array('host' => $host));
        if ($model) {
            Log::w('Host "' . $model->host . '" authenticate after "' . $model->count . '" try/tries.', 'PhonalisaFirewall');
            $model->delete();
        }
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * gets back all module array definitions for the current logged in User if any
     *
     */
    public function getModulesForCurrentSession()
    {
        Yii::import('application.components.AccessManager.php');

        $userPermissions = Yii::app()->session['permissions'];
        if ($userPermissions == null) {
            $userPermissions = AccessManager::getUsersPermissions();
            Yii::app()->session['permissions'] = $userPermissions;
        }

        ///FIXME: Use the Modulefactory for getting this stuff
        return array();
    }

    public function actionChangeMobileView()
    {
        $showMobile = true;
        if (isset($_REQUEST['showMobile'])) {
            if ($_REQUEST['showMobile'] === 'false') {
                $showMobile = false;
            }
            Yii::app()->detectMobileBrowser->showMobile = $showMobile;
        }
        header('Content-type: application/json');
        echo json_encode("refresh");
    }

    public function actionReboot($redirect = '', $id = '')
    {
        $url = url('site/logout');
        if ($redirect !== '') {
            $url = url($redirect);
            if ($id !== '') {
                $url = $this->getNewIpUrl($id, $redirect);
                $this->layout = '//layouts/statusScreen';
                return $this->render('application.modules.wizard.views.default.wizard_phonalisaLink', array('url' => $url));
            }
        }
        $this->layout = '//layouts/statusScreen';
        $this->render('rebootScreen', array('url' => $url));
    }

    private function getNewIpUrl($id, $redirect)
    {
        $url = url('site/logout');
        $networkInterface = NetworkInterface::model()->findByPk($id);
        if ($networkInterface) {
            $protocol = 'http';
            if (app()->getRequest()->isSecureConnection) {
                $protocol = 'https';
            }
            $ip = $networkInterface->ip;
            $port = Yii::app()->getRequest()->serverPort;
            $url = $protocol . '://' . $ip . ':' . $port . url($redirect);
        }
        return $url;
    }

    public function actionShutdown()
    {
        $this->layout = '//layouts/statusScreen';
        $this->render('shutdownScreen');
    }
    
    public function actionContextHelp()
    {
        if (isset($_POST["translationKeys"])) {
            $translationKeys = $this->getValidatedTranslationKeys($_POST["translationKeys"]);
        } else {
            $translationKeys = array();
        }
        
        echo json_encode($translationKeys);
    }
    
    private function getValidatedTranslationKeys($keys) 
    {
        $parseDown = new Parsedown();
        $validatedKeys = array();
        
        if (!is_array($keys)) {
            $keys = array($keys);
        }
        
        foreach ($keys as $key) {
            $text = preg_replace("/<br\W*?\/>/", "\n", __($key));
            $validatedKeys[CHtml::encode($key)]  = $parseDown->text($text);
        }
        return $validatedKeys;
    } 
}
