<?php

/* Table SQL statement
 *
 * CREATE TABLE "sysconfig" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "key" VARCHAR(80), "value" VARCHAR(255) NOT NULL )
 *
 * */

class DefaultController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'section', 'sendTestMail', 'checkTestMail'),
                //'users'=>array('@'),
                'expression' => AccessManager::checkSessionPermission($this->module->name),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = Sysconfig::model();
        $sections = array_keys($model->getConfigItemsArray());

        // YII BUG &section => §ion
        $firstSectionUrl = $this->createUrl("section");
        $firstSectionUrl .= '&section=' . $sections[0];

        $this->redirect($firstSectionUrl);

        $dataProvider = new CPhonalisaDataProvider('Sysconfig');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'model' => $model
        ));
    }

    public function actionSave()
    {
        $models = Sysconfig::model()->findAll();
        $models[] = new Sysconfig();

        if (isset($_POST['Sysconfig'])) {
            // apply traslate mode immediately
            if (isset($_POST['Sysconfig']['TRANSLATE_MODE'])) {
                Yii::app()->user->setState(
                        'translateMode', $_POST['Sysconfig']['TRANSLATE_MODE'] === '1' ? true : false
                );
            }
            foreach ($_POST['Sysconfig'] as $modelId => $postAttributes) {
                $model = Sysconfig::model()->findByAttributes(array('key' => $modelId));
                if ($model == NULL) {
                    $model = new Sysconfig();
                }
                $model->key = $modelId;

                if ($modelId == 'BACKUP_CRON_JOB') {
                    $postAttributes = preg_replace('!\s+!', ' ', trim($postAttributes));
                }

                if ($modelId != 'NAME_PATTERN') {
                    $model->value = $postAttributes . "";
                } else {
                    $realPattern = '';
                    foreach ($postAttributes as $patternAttributes) {
                        $realPattern.=$patternAttributes . "\n";
                    }
                    $trimRealPattern = rtrim($realPattern);
                    $realPattern = str_replace('%NONE%', '', $trimRealPattern);
                    $model->value = $realPattern;
                }

                if ($modelId == 'SYSTEM_SSH_PUBLIC_KEYS') {
                    $data = array();
                    $data["key"] = $model->value;
                    PhonalisaCtrldConnector::writeSSHPublicKey($data);
                }

                if ($modelId == 'WEB_USER_MONITOR_ENABLED' && $postAttributes === "0") {
                    app()->user->setState('userMonitor', "false");
                }

                if (!$model->save()) {
                    Yii::app()->user->setFlash('error', '<strong data-translation-id="CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR">' . __("CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR") . '!</strong>');
                } else {
                    // test email temporary disabled
                    if ($_GET['section'] == 'MESSAGING') {
                        $emailForm = $this->renderPartial('testEmail', array(), true);
                        Yii::app()->user->setFlash('info', $emailForm);
                    } else {
                        Yii::app()->user->setFlash('success', '<strong data-translation-id="CHANGES_SAVED_SUCCSESSFULLY">' . __("CHANGES_SAVED_SUCCSESSFULLY") . '</strong>');
                    }
                }
            }

            $this->render(
                    'section', array(
                'model' => $model,
                'section' => Yii::app()->request->getParam("section"))
            );
        }
    }

    public function actionSection()
    {
        $model = Sysconfig::model();

        if ($_GET['section'] == 'MESSAGING') {
            $emailForm = $this->renderPartial('testEmail', array(), true);
            Yii::app()->user->setFlash('info', $emailForm);
        }

        if (Yii::app()->request->getParam('action') == 'save') {
            $this->actionSave();
        } else {
            $this->render('section', array('model' => $model, 'section' => Yii::app()->request->getParam("section")));
        }
        Yii::app()->end();
    }

    public function actionGlobalConfig()
    {
        $model = new Sysconfig;
        if (isset($_POST['Sysconfig'])) {
            $model->attributes = $_POST['Sysconfig'];
            if ($model->validate()) {
                // form inputs are valid, do something here
                return;
            }
        }
        $this->render('globalConfig', array('model' => $model));
    }

    public function actionSendTestMail()
    {
        // remove old mails
        $oldEmails = EMail::model()->findAllByAttributes(array('type' => EmailType::EmailTypeTest));
        if ($oldEmails != null) {
            foreach ($oldEmails as $oldMail) {
                $oldMail->delete();
            }
        }

        $date = new DateTime();
        $email = new EMail;
        $email->subject = 'Phonalisa test email';
        $email->recipient = @$GET[''];
        $email->text = 'Test';
        $email->type = EmailType::EmailTypeTest;

        if (isset($_POST['EMail'])) {
            $validationResult = CActiveForm::validate($email);
            if ($validationResult != '[]') {
                echo $validationResult;
            } else {
                if ($email->save()) {
                    http_response_code(202);
                    echo json_encode(array('id' => $email->id));
                }
            }
            Yii::app()->end();
        }
    }

    public function actionCheckTestMail($id)
    {
        $model = EMail::model()->findByPk($id);
        if ($model == null) {
            Yii::app()->end();
        }

        echo json_encode(array('state' => (int) $model->state, 'error' => $model->errortext));
        Yii::app()->end();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Sysconfig::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'sysconfig-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function renderValue(PhonalisaRecord $data, $row)
    {
        echo $this->renderPartial('_valueColumn', array('model' => $data), true);
    }

    public function renderDefaultValue(PhonalisaRecord $data, $row)
    {
        $this->renderPartial('_defaultValueColumn', array('model' => $data));
    }

    public function getSectionName($links)
    {
        foreach ($links as $item) {
            if ($item['active']) {
                return '-'.$item['name'];
            }
        }
    }
}
