<?php

class DefaultController extends Controller
{
    public $layout = 'application.modules.wizard.views.default.layout';
    public $currentStep = 0;
    public $skipLicense = NULL;
    public $agreeTOC = false;
    public $wizardModel;
    
    private $steps = 5;

    public function actionIndex()
    {
        /*
        $wizardModel = WizardHelper::getWizardModel();
        $wizardModel->step = 0;
        $wizardModel->save();
        setCfg("systemInitialized", "0");
        */
        
        try {
            $wizardModel = WizardHelper::getWizardModel();        
            $this->currentStep = $wizardModel->getStep();

            // Wiedereinsprungspunkt bei wiederaufnahme des Wizard, hier muss nach Step geprüft werden und die
            // entsprechende Action ausgeführt werden.
            $stepImpl = WizardStep::getStepImplementation($this->currentStep);
            if ($stepImpl->executeStep($this)) {
                
                if ($this->currentStep === WizardStep::LanguageAndStyle)
                {
                    WizardHelper::checkIfWizardWasAlreadyFinished();
                    if (!WizardHelper::isSystemInitialized()) {
                        if (!WizardHelper::initializeSystem()) {
                            throw new CHttpException(500, 'Internal Wizard Error init failed!');
                        }
                    }
                }
                
                $wizardModel->incrementStep();
                
                if ($wizardModel->getStep() > $this->getLastSteps()) {
                    setCfg("systemInitialized", "1");
                    $this->redirect(url('systemOverview'));
                }

                $this->actionIndex();
            }
        } catch (CHttpException $error) {
            $this->render("error", array("code" => $error->statusCode, "message" =>$error->getMessage() ));
        }
    }
    
    private function getLastSteps()
    {   
        if (PhonalisaLicenseManager::licenseIsValid()) {
            return (WizardStep::LastStep -1); // skip last step (license form)
        } 
        return WizardStep::LastStep;
    }

    public function getAdminUser()
    {
        $admin = User::model()->findByAttributes(array("isSystemAdmin" => "1"));
        if (!$admin) {
            throw new CHttpException(500, "Internel server Error: unable to load admin user!");
        }
        return $admin;
    }

/*


    /// ALTER SCHEISS:

    public function actionUpdateAdmin()
    {
        $model = $this->loadAdminModel();
        $this->performAjaxValidation($model);
    }

    protected function loadAdminModel()
    {
        $model = User::model()->findAllByAttributes(array('isSystemAdmin' => '1'));

        if (!isset($model[0]) || $model[0] === null || empty($model)) {
            $initializer = new PhonalisaInitializer();

            if ($initializer->runInit() === true) {
                $model = User::model()->findAllByAttributes(array('isSystemAdmin' => '1'));
            } else {
                die('Can not init database');
            }
        }

        return $model[0];
    }

    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'admin-user') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    private function skipLicenseForm()
    {
        if (PhonalisaLicenseManager::licenseIsValid()) {
            $this->steps = 4;
            $this->skipLicense = 'skip';
        }
    }



    public function _actionIndex()
    {


        $this->setLanguage();
        $this->skipLicenseForm();

        if (isset($_POST['WizardForm']['colorTheme']) && $_POST['WizardForm']['colorTheme'] != '') {
            setCfg('UI_THEME', $_POST['WizardForm']['colorTheme']);
        }

        if (isset($_GET['reset'])) {
            $this->resetProgress();
            $this->redirect('wizard/test');
        }

        // get the step. If a previous step has been posted, the step is
        // found in this previous form's fields. Otherwise we set it to 1
        $this->layout = 'application.views.wizard.layout';

        $step = isset($_POST['WizardForm']) && isset($_POST['WizardForm']['step']) ? $_POST['WizardForm']['step'] : 1;

        if (isset($_POST['WizardForm']['prev'])) {
            $step--;
        }


        $model = new WizardForm('step' . $step);

        // restore
        if ($model->restoreFromDatabase() && !isset($_POST['WizardForm'])) {
            if ($model->step != $this->steps) {
                $step = $model->step + 1;
            }
            $model->scenario = 'step' . $step;
        }

        $form = new CForm('application.views.wizard.wizard_step' . $step, $model);
        $dataIsValide = false;
        // validate the previous step
        if (isset($_POST['WizardForm'])) {

            $ipHasChanged = 'false';
            if (isset($_POST['WizardForm']['ipHasChanged'])) {
                $ipHasChanged = $_POST['WizardForm']['ipHasChanged'];
                unset($_POST['WizardForm']['ipHasChanged']);
            }

            $isNetworkStep = false;
            if (isset($_POST['WizardForm']['networkInterfaceID'])) {
                $isNetworkStep = true;
            }

            if (isset($_POST['WizardForm']['skip']) && !isset($this->skipLicense)) {
                $this->skipLicense = $_POST['WizardForm']['skip'];
            }

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

            if ($form->validate() && ($step != 3 || ($model->skipNetworkCheck == "1" || $this->checkAPIConnection($model) ))) {
                $dataIsValide = true;

                $oldScenario = $model->scenario;
                $this->setProvInitNetwork($model);

                if (app()->params->applianceMode && $step !== 2 && $isNetworkStep) {
                    if ($model->enableDHCP === '1') {
                        if ($this->setDhcpSettings($model)) {
                            $model->lastEnableDHCPServer = true;
                            if (!NetworkSettings::writeDhcpConfigsToCtrld()) {
                                if (!$this->deleteDHCPSettings()) {
                                    $step = $model->step = 2;
                                }
                                $step = $model->step = 2;
                            }
                        } else {
                            $step = $model->step = 2;
                        }
                    } else if ($model->lastEnableDHCPServer == 'true') {
                        if (!$this->changeNetworkInterfaceSettings($model)) {
                            $step = $model->step = 2;
                        } else {
                            if (!$this->deleteDHCPSettings()) {
                                $step = $model->step = 2;
                            }
                            if (!NetworkSettings::writeDhcpConfigsToCtrld()) {
                                $step = $model->step = 2;
                            }
                        }
                    }
                    $model->scenario = $oldScenario;
                }

                if (app()->params->applianceMode && $step !== 2 && $isNetworkStep) {
                    if ($model->enableDNSServer === '1') {
                        if ($this->setDnsSettings($model)) {
                            $model->lastEnableDNSServer = true;
                            if (!$this->writeDataToCtrld()) {
                                $step = $model->step = 2;
                            }
                        } else {
                            $step = $model->step = 2;
                        }
                    } else if ($model->lastEnableDNSServer == 'true') {
                        if (!$this->deleteDnsSettings()) {
                            $step = $model->step = 2;
                        }
                        if (!$this->writeDataToCtrld()) {
                            $step = $model->step = 2;
                        }
                    }
                    $model->scenario = $oldScenario;
                }

                if (app()->params->applianceMode) {
                    if ($ipHasChanged === 'true') {
                        if (PhonalisaCtrldConnector::hasConnection() && $this->updateNetworkInterface($model)) {
                            $this->showNewPhonalisaLink($model->ip);
                            $this->storeProgress($model);
                            $this->rebootPhonalisa();
                        } else {
                            if (!app()->user->hasFlash('error')) {
                                app()->user->setErrorFlashMessage('NETWORK_SETTINGS_WRITE_TO_CTRLD_ERROR');
                            }
                            $step = $model->step = 2;
                        }
                    } else if ($step !== 2 && $isNetworkStep) {
                        if (!$this->changeNetworkInterfaceSettings($model)) {
                            $step = $model->step = 2;
                        }
                    }
                }

                $this->storeProgress($model);

                // The previous step has validated

                if ($step < $this->steps) {
                    // build the current step form if we're
                    // not at the last step
                    if (isset($_POST['WizardForm']['next'])) {
                        $step++;
                    }

                    $model = new WizardForm('step' . $step);
                    $model->restoreFromDatabase();
                    $model->attributes = $_POST['WizardForm'];
                } else {
                    if ($this->activateLicense($model)) {
                        $this->storeDataToConfig($model);
                    }
                }
            } else if (isset($this->skipLicense) && $model->validate()) {
                $step++;
                if ($step > $this->steps) {
                    $this->storeDataToConfig($model);
                } else {
                    $dataIsValide = true;
                    $model = new WizardForm('step' . $step);
                    $model->restoreFromDatabase();
                    $model->attributes = $_POST['WizardForm'];
                }
            }
        }
        $preview = '';
        $form = new CForm('application.views.wizard.wizard_step' . $step, $model);
        $this->render('application.views.wizard.index', array('form' => $form, 'preview' => $preview, 'step' => $step, 'model' => $model));
    }

    private function getModelFromDatabase()
    {
        $model = Wizard::model()->findAll();

        if (count($model) > 0) {
            return $model[0];
        }
        return new Wizard;
    }

    private function storeProgress($model)
    {
        $dbModel = $this->getModelFromDatabase();
        foreach ($model->attributes as $attribute => $value) {
            if ($value !== null) {
                $dbModel->$attribute = $value;
            }
        }
        if (!$dbModel->save()) {
            throw new CHttpException(404, 'Can not save input');
        }
    }

    private function reStoreProgress()
    {
        return $this->getModelFromDatabase();
    }

    private function resetProgress()
    {
        setCfg('UI_THEME_FULL', 'default');
        setCfg('systemInitialized', '0');
        $model = $this->getModelFromDatabase();
        $model->delete();
    }

    private function activateLicense($model)
    {
        if (!isset($this->skipLicense)) {
            $license = new Licence();
            // get relevant attributes and Values for license activation :
            $license->license_code = $model->license_code;

            foreach ($model->attributes as $key => $value) {
                if (strpos($key, 'customer_') !== false) {
                    $license->$key = $value;
                }
            }

            $result = LicenseServer::activateLicense($license);
            if ($result === true) {
                return true;
            }

            Yii::app()->user->setFlash('error', "<strong>Error " . $result['errorCode'] . ": </strong>" . $result['errorMessage']);
            return false;
        }
        return true;
    }

    private function storeDataToConfig($model)
    {
        $this->updateAdminUser($model);
        setCfg('DP_DROPTARGET', $model->userExtension);
        setCfg('systemInitialized', '1');
        $this->setNetworkCfgs($model);
        setCfg('CALL_SERVICE_AUTHTOKEN', PasswordGenerator::generateToken());

        $model = $this->getModelFromDatabase();
        $model->delete();
        $this->loginUser($model);
    }

    private function setNetworkCfgs($model)
    {
        setCfg('PROV_HOST', $model->ip);
        setCfg('SIP_HOST', $model->ip);
        setCfg('NTP_HOST', $model->ip);
        $globalConfigDefault = Yii::app()->params->globalConfigDefault;
        $port = '80';
        if (is_array($globalConfigDefault) && array_key_exists('PROV_PORT', $globalConfigDefault)) {
            $port = $globalConfigDefault['PROV_PORT'];
        }
        setCfg('PROV_PORT', $port);

        $securePort = '443';
        if (is_array($globalConfigDefault) && array_key_exists('PROV_PORT_SECURE', $globalConfigDefault)) {
            $securePort = $globalConfigDefault['PROV_PORT_SECURE'];
        }
        setCfg('PROV_PORT_SECURE', $securePort);
    }

    private function updateNetworkInterface($model)
    {
        $interfaceID = @$model->networkInterfaceID;
        $result = false;

        if (!empty($interfaceID)) {
            $networkInterface = NetworkInterface::model()->findByPK($interfaceID);
            if ($networkInterface) {
                $oldIP = $networkInterface->ip;
                $oldNetmask = $networkInterface->netmask;
                $oldGateway = $networkInterface->gateway;
                $oldDNS = $networkInterface->dns;
                $oldNTP = cfg('NTP_HOST');
                setCfg('NTP_HOST', $model->ip);
                $networkInterface->ip = $model->ip;
                $networkInterface->netmask = $model->subnet;
                $networkInterface->gateway = $model->gateway;
                $networkInterface->dns = $model->dns;
                $networkInterface->isPrimary = '1';
                $networkInterface->scenario = 'wizard';
                $networkInterface->save();

                if (NetworkInterface::writeNetworkConfigsToCtrld()) {
                    if ($networkInterface->changeDhcpWithPrimaryNetworkAdapterSettings()) {
                        if (NetworkSettings::writeDhcpConfigsToCtrld()) {
                            $result = true;
                        } else {
                            $this->resetNetworkAdapter($networkInterface, $oldIP, $oldNetmask, $oldGateway, $oldDNS, $oldNTP);
                        }
                    } else {
                        $this->resetNetworkAdapter($networkInterface, $oldIP, $oldNetmask, $oldGateway, $oldDNS, $oldNTP);
                    }
                } else {
                    $this->resetNetworkAdapter($networkInterface, $oldIP, $oldNetmask, $oldGateway, $oldDNS, $oldNTP);
                }
            }
        }
        return $result;
    }

    private function resetNetworkAdapter($networkInterface, $oldIP, $oldNetmask, $oldGateway, $oldDNS, $oldNTP)
    {
        $networkInterface->ip = $oldIP;
        $networkInterface->netmask = $oldNetmask;
        $networkInterface->gateway = $oldGateway;
        $networkInterface->dns = $oldDNS;
        $networkInterface->scenario = 'wizard';
        $networkInterface->save();
        setCfg('NTP_HOST', $oldNTP);
    }

    private function setProvInitNetwork($model)
    {
        $interfaceID = @$model->networkInterfaceID;
        if (!empty($interfaceID)) {
            $networkInterface = NetworkInterface::model()->findByPK($interfaceID);
            if ($networkInterface) {
                setCfg('PROV_INIT_FROM_NET', $networkInterface->getIpAsCIDR());
            }
        }
    }

    private function setDhcpSettings($model)
    {
        $oldScenario = $model->scenario;
        $model->scenario = 'useDHCP';
        if (!$model->validate()) {
            app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $model->getFormatedErrors());
            return false;
        }
        $model->scenario = $oldScenario;

        $this->setNetworkCfgs($model);
        if (!PhonalisaCtrldConnector::hasConnection()) {
            app()->user->setErrorFlashMessage('NETWORK_SETTINGS_WRITE_TO_CTRLD_ERROR');
            return false;
        }

        if (!$this->changeNetworkInterfaceSettings($model)) {
            return false;
        }

        $networkInterface = NetworkInterface::model()->findByAttributes(array('ip' => $model->ip));
        if (!$networkInterface) {
            app()->user->setErrorFlashMessage('WIZARD_NO_NETWORK_INTERFACE_FOUND');
            return false;
        }

        $settings = array();
        $settings['ENABLE_DCHPD'] = $model->enableDHCP;
        $settings['GLOBAL_SUBNET_MASK'] = $networkInterface->netmask;
        $settings['GLOBAL_SUBNET'] = $networkInterface->getIpAsCIDR();
        $settings['GLOBAL_BROADCAST_ADDRESS'] = $networkInterface->getBroadcast();
        $settings['GLOBAL_ROUTER'] = $networkInterface->gateway;
        $settings['GLOBAL_DNS'] = $networkInterface->dns;
        $settings['GLOBAL_NTP'] = cfg('NTP_HOST');
        $settings['RANGE_FROM'] = $model->dhcpRangeFrom;
        $settings['RANGE_TO'] = $model->dhcpRangeTo;

        foreach ($settings as $key => $value) {
            if (!$this->saveNetworkSettings($key, $value)) {
                return false;
            }
        }
        return true;
    }

    private function saveNetworkSettings($key, $value)
    {
        $model = NetworkSettings::model()->findByAttributes(array('key' => $key));
        if (!$model) {
            $model = new NetworkSettings();
        }
        $model->key = $key;
        $model->value = $value;
        if (!$model->save()) {
            app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $model->getFormatedErrors());
            return false;
        }
        return true;
    }

    private function changeNetworkInterfaceSettings($model)
    {
        $networkInterface = NetworkInterface::model()->findByAttributes(array('ip' => $model->ip));
        if (!$networkInterface) {
            app()->user->setErrorFlashMessage('WIZARD_NO_NETWORK_INTERFACE_FOUND');
            return false;
        }

        $networkInterface->isPrimary = '1';
        $networkInterface->dns = $model->dns;
        $networkInterface->gateway = $model->gateway;
        $networkInterface->scenario = 'wizard';
        if (!$networkInterface->save()) {
            app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $networkInterface->getFormatedErrors());
            return false;
        }
        return true;
    }

    private function deleteDHCPSettings()
    {
        $dhcpSettings = NetworkSettings::model()->findAll();
        foreach ($dhcpSettings as $dhcpSetting) {
            $dhcpSetting->value = '';
            if (!$dhcpSetting->save()) {
                app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $dhcpSetting->getFormatedErrors());
                return false;
            }
        }
        return true;
    }

    private function setDnsSettings($model)
    {
        $oldScenario = $model->scenario;
        $model->scenario = 'useDns';
        if (!$model->validate()) {
            app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $model->getFormatedErrors());
            return false;
        }
        $model->scenario = $oldScenario;

        if (!$this->changeNetworkInterfaceSettings($model)) {
            return false;
        }

        $dnsModel = DNSServer::model()->findByAttributes(array('position' => '0'));
        if (!$dnsModel) {
            $dnsModel = new DNSServer();
        }
        $dnsModel->enableDNSServer = $model->enableDNSServer;
        $dnsModel->upstreamDNSServer = $model->dns;
        $dnsModel->position = 0;
        if (!$dnsModel->save()) {
            return false;
        }

        $dnsZone = DNSZone::model()->findByAttributes(array('position' => '0'));
        if (!$dnsZone) {
            $dnsZone = new DNSZone();
        }
        $dnsZone->fqdn = $model->phonalisaDomain;
        $dnsZone->position = 0;
        if (!$dnsZone->save()) {
            return false;
        }
        return true;
    }

    private function writeDataToCtrld()
    { 
        $data = DNSServer::getDnsDataForCtrld();
        $ctrld = PhonalisaCtrldConnector::writeDnsConfig($data);

        $ctrldStatus = @$ctrld->status;
        $ctrldErrorTxt = @$ctrld->errorText;

        if (empty($ctrldStatus)) {
            app()->user->setErrorFlashMessage('GLOBAL_WRITE_TO_CTRLD_ERROR');
            return false;
        } else if ($ctrldStatus == 'error' && !empty($ctrldErrorTxt)) {
            app()->user->setErrorFlashMessage($ctrldErrorTxt);
            return false;
        }
        return true;
    }

    private function deleteDnsSettings()
    {
        $dnsModels = DNSServer::model()->findAll();
        foreach ($dnsModels as $dnsModel) {
            if (!$dnsModel->delete()) {
                app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $dnsModel->getFormatedErrors());
                return false;
            }
        }

        $dnsZones = DNSZone::model()->findAll();
        foreach ($dnsZones as $dnsZone) {
            if (!$dnsZone->delete()) {
                app()->user->setErrorFlashMessage('CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $dnsZone->getFormatedErrors());
                return false;
            }
        }
        return true;
    }

    private function showNewPhonalisaLink($ip)
    {
        $protocol = 'http';
        if (app()->getRequest()->isSecureConnection) {
            $protocol = 'https';
        }
        $port = Yii::app()->getRequest()->serverPort;
        $url = $protocol . '://' . $ip . ':' . $port;
        $this->render('application.views.wizard.wizard_phonalisaLink', array('url' => $url));
    }

    private function rebootPhonalisa()
    {
        PhonalisaCtrldConnector::rebootSystem();
    }

    private function _loginUser($model)
    {
        $loginForm = new LoginForm;
        $loginForm->username = $model->userName;
        $loginForm->password = $model->userPassword;

        if ($loginForm->validate() && $loginForm->login()) {
            Yii::app()->user->setState('fadePageIn', true);
            $this->redirect(url('systemOverview'));
        } else {
            throw new CHttpException(404, 'Login failed.');
        }
    }

    private function updateAdminUser($model)
    {
        $admin = $this->loadAdminModel();

        // Update internal addressbook
        $contact = Addresses::model()->findByPk($admin->addressReferece);

        if ($contact != null) {
            $contact->n_given = $model->userFirstname != null ? $model->userFirstname : $model->userName;
            $contact->n_family = $model->userLastname != null ? $model->userLastname : "";
        } else {
            throw new CHttpException(500, "could not find Contact");
        }

        $contact->contact_email = $model->userEmail;
        $contact->tel_work = $model->userExtension;

        $admin->name = $model->userName;
        $admin->password = $model->userPassword;
        $admin->firstname = $model->userFirstname;
        $admin->lastname = $model->userLastname;
        $admin->extension = $model->userExtension;
        $admin->email = $model->userEmail;
        $admin->pin = $model->userPin;


        Yii::app()->user->id = $admin->id;

        setCfg('EMAIL_NAME', $model->installationName);
        setCfg('PHONALISA_NAME', $model->installationName);
        setCfg('GUI_LANGS', $_POST['WizardForm']['language']);

        if (!$contact->save()) {
            throw new CHttpException(404, 'Can not save admin contact, please restart initializer.');
        }

        if (!$admin->validate()) {
            throw new CHttpException(404, 'Can not save admin user, please restart initializer.');
        } else {
            $admin->save(false);
        }

        $sipAccount = SipAccounts::generateSipAccountForUser($admin);
        if (!$sipAccount->save()) {
            throw new CHttpException(404, 'Can not save admin sipaccount, please restart initializer.');
        }
    }

    private function setLanguage()
    {
        if (isset($_POST['WizardForm']['language'])) {
            Yii::app()->language = $_POST['WizardForm']['language'];
        }
    }

    private function storeProxyConfigs($model)
    {
        setCfg('HTTP_PROXY_IP_ADDRESS', $model->httpProxyIp);
        setCfg('HTTP_PROXY_PORT', $model->httpProxyPort);
        setCfg('HTTP_PROXY_USERNAME', $model->httpProxyUser);
        setCfg('HTTP_PROXY_PASSWORD', $model->httpProxyPassword);
        setCfg('HTTPS_PROXY_IP_ADDRESS', $model->httpProxyIp);
        setCfg('HTTPS_PROXY_PORT', $model->httpsProxyPort);
        setCfg('HTTPS_PROXY_USERNAME', $model->httpsProxyUser);
        setCfg('HTTPS_PROXY_PASSWORD', $model->httpsProxyPassword);
    }

    private function checkAPIConnection($model)
    {
        $this->storeProxyConfigs($model);
        $result = LicenseServer::checkConnection();

        if ($result === true) {
            return true;
        }

        ob_start();
        $this->widget('bootstrap.widgets.TbButton', array(
            'label' => __('WIZARD_SKIP_NETWORK_CONNECTON_CHECK_BTN'),
            'type' => 'danger',
            //'size'=>'mini', // null, 'large', 'small' or 'mini'
            'icon' => 'warning-sign',
            'htmlOptions' => array(
                'data-translation-id' => 'WIZARD_SKIP_NETWORK_CONNECTON_CHECK_BTN',
                'id' => 'skipNetworkCheckBtn'
            )
        ));
        $skipNetworkCheckBtn = ob_get_clean();


        Yii::app()->user->setFlash('error', "<strong>Error " . $result['httpCode'] . ": </strong>" . $result['errmsg'] . '<br><br>' . $skipNetworkCheckBtn);
        return false;
    }

*/
}

