<?php
/*
*

 ______   _______  __   __  _______  _______  ___   _______ 
|      | |       ||  |_|  ||       ||       ||   | |       |
|  _    ||    ___||       ||   _   ||_     _||   | |       |
| | |   ||   |___ |       ||  | |  |  |   |  |   | |       |
| |_|   ||    ___||       ||  |_|  |  |   |  |   | |      _|
|       ||   |___ | ||_|| ||       |  |   |  |   | |     |_ 
|______| |_______||_|   |_||_______|  |___|  |___| |_______|
 _______  __   __  _______                                  
|       ||  |_|  ||       |                                 
|       ||       ||  _____|                                 
|       ||       || |_____                                  
|      _||       ||_____  |                                 
|     |_ | ||_|| | _____| |                                 
|_______||_|   |_||_______|                                                   
                                              
                                           
*
*
*/

/**
 * Demotic CMS is a fork of ImpressPages.
 * AUTHOR: Demotic
 * @package Demotic
 */
 
namespace Demotic\Gebtu\Admin;

class SiteController extends \Demotic\Controller
{

    public function login()
    {
        if (\Demotic\Gebtu\Admin\Backend::userId()) {
            //user has already been logged in
            \Demotic\Gebtu\Content\Service::setManagementMode(1);
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }

        // If none of the administrator exist, we create default one and log in user
        $administrators = \Demotic\Gebtu\Administrators\Model::getAll();
        if (empty($administrators)) {
            $adminUsername = 'admin';
            $adminEmail = ipGetOptionLang('Config.websiteEmail');
            $adminPassword = Model::randString(8);

            $adminId = \Demotic\Gebtu\Administrators\Service::add($adminUsername, $adminEmail, $adminPassword);
            \Demotic\Gebtu\AdminPermissionsModel::addPermission('Super admin', $adminId);

            // Set variable to know that user is autogenerated
            ipStorage()->set('Demotic', 'adminIsAutogenerated', $adminPassword);

            // Logging in new admin
            $model = Model::instance();
            if ($model->login($adminUsername, $adminPassword)) {
                \Demotic\Gebtu\System\Model::sendUsageStatistics(array('action' => 'Install.adminIsAutogenerated'));
                $redirectUrl = ipHomeUrl();
                return new \Demotic\Response\Redirect($redirectUrl);
            } else {
                \Demotic\Gebtu\System\Model::sendUsageStatistics(array('action' => 'Install.adminIsAutogeneratedFailed'));
                // todo: handle errors
                // $errors = $model->getErrors();
            }
        }

        $content = ipView('view/login.php', array('loginForm' => FormHelper::getLoginForm()));
        ipAddJs('Demotic/Gebtu/Admin/assets/login.js');
        $response = ipResponse();
        $response->setLayout('Demotic/Gebtu/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());

        return $response;
    }

    public function passwordResetForm()
    {
        if (\Demotic\Gebtu\Admin\Backend::userId()) {
            //user has already been logged in
            \Demotic\Gebtu\Content\Service::setManagementMode(1);
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordReset.php', array('passwordResetForm' => FormHelper::getPasswordResetForm1()));
        ipAddJs('Demotic/Gebtu/Admin/assets/passwordReset1.js');

        $response = ipResponse();
        $response->setLayout('Demotic/Gebtu/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordResetInfo()
    {
        if (\Demotic\Gebtu\Admin\Backend::userId()) {
            //user has already been logged in
            \Demotic\Gebtu\Content\Service::setManagementMode(1);
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordResetInfo.php');

        $response = ipResponse();
        $response->setLayout('Demotic/Gebtu/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordResetSuccess()
    {
        if (\Demotic\Gebtu\Admin\Backend::userId()) {
            //user has already been logged in
            \Demotic\Gebtu\Content\Service::setManagementMode(1);
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordResetSuccess.php');

        $response = ipResponse();
        $response->setLayout('Demotic/Gebtu/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordReset()
    {
        if (\Demotic\Gebtu\Admin\Backend::userId()) {
            //user has already been logged in
            \Demotic\Gebtu\Content\Service::setManagementMode(1);
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordReset2.php', array('passwordResetForm' => FormHelper::getPasswordResetForm2()));
        ipAddJs('Demotic/Gebtu/Admin/assets/passwordReset2.js');

        $response = ipResponse();
        $response->setLayout('Demotic/Gebtu/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;
    }

    public function loginAjax()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getLoginForm();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $username = ipRequest()->getPost('login');

        if (empty($errors)) {
            $model = Model::instance();
            if (!$model->login($username, ipRequest()->getPost('password'))) {
                $errors = $model->getErrors();
            }
        }

        $redirectUrl = ipHomeUrl();

        $model = Model::instance();
        $adminMenuItems = $model->getAdminMenuItems(null);
        if (!empty($adminMenuItems)) {
            //redirect user to the first module
            $firstMenuItem = $adminMenuItems[0];
            $redirectUrl = $firstMenuItem->getUrl();
        }

        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => $redirectUrl
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
            $usageStatistics = array(
                'action' => 'Admin.loginFailed',
                'data' => array(
                    'admin' => $username,
                    'errors' => $errors
                )
            );
            \Demotic\Gebtu\System\Model::sendUsageStatistics($usageStatistics);
        }

        if (ipRequest()->getPost('ajax', 1)) {
            $response = new \Demotic\Response\Json($answer);
            return $response;
        } else {
            //MultiSite autologin
            return new \Demotic\Response\Redirect($redirectUrl);
        }
    }

    public function passwordResetAjax()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getPasswordResetForm1();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $username = ipRequest()->getPost('username');

        if (empty($errors)) {
            $user = \Demotic\Gebtu\Administrators\Service::getByEmail($username);
            if (!$user) {
                $user = \Demotic\Gebtu\Administrators\Service::getByUsername($username);
            }

            if ($user) {
                \Demotic\Gebtu\Administrators\Service::sendResetPasswordLink($user['id']);
            } else {
                $errors['username'] = __('Following administrator doesn\'t exist', 'Demotic-admin', false);
            }

        }

        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => ipActionUrl(array('sa' => 'Admin.passwordResetInfo'))
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
        }

        $response = new \Demotic\Response\Json($answer);
        return $response;
    }

    public function passwordResetAjax2()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getPasswordResetForm2();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $userId = ipRequest()->getPost('userId');
        $secret = ipRequest()->getPost('secret');
        $password = ipRequest()->getPost('password');


        try {
            \Demotic\Gebtu\Administrators\Service::resetPassword($userId, $secret, $password);
        } catch (\Demotic\Exception $e) {
            $user['global_error'] = $e->getMessage();
        }


        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => ipActionUrl(array('sa' => 'Admin.passwordResetSuccess'))
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
        }

        $response = new \Demotic\Response\Json($answer);
        return $response;
    }

    public function logout()
    {
        Model::instance()->logout();
        if (ipRequest()->isAjax()) {
            return new \Demotic\Response\Json([]);
        } else {
            return new \Demotic\Response\Redirect(ipHomeUrl());
        }
    }



    public function changeLanguage()
    {
        $locale = ipRequest()->getPost('languageCode', 'en');
        $hour = 60 * 60;
        $day = $hour * 24;
        setcookie("ipAdminLocale", $locale, time() + $day * ipGetOption('Config.adminLocaleCookieExpire', 10 * 365));
        return new \Demotic\Response\Json(array('success' => 1));
    }


}
