<?php

class QuestionnaireQuestionController extends RController {

    public $defaultAction = 'admin';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'rights',
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionQuickUpdate() {
        $es = new EditableSaver('QuestionnaireQuestion');
        $es->update();
    }

    public function actionOptions() {

        if (isset($_POST['QuestionnaireQuestion'])) {
            if (isset($_POST['QuestionnaireQuestion']['type'])) {
                $type = $_POST['QuestionnaireQuestion']['type'];
                $types = QuestionnaireQuestion::getTypes();

                if (isset($types[$type])) {
                    switch ($type) {
                        case QuestionnaireQuestion::TYPE_TEXT:
                            $this->renderPartial('types/_text', array('options' => array()), false, true);
                            break;
                        case QuestionnaireQuestion::TYPE_RANGE:
                            $this->renderPartial('types/_range', array('options' => array()), false, true);
                            break;
                        case QuestionnaireQuestion::TYPE_MULTIPLE_CHOICES:
                            $this->renderPartial('types/_multiple_choices', array('options' => array()), false, true);
                            break;
                        case QuestionnaireQuestion::TYPE_CHECKBOXES:
                            $this->renderPartial('types/_multiple_choices', array('options' => array()), false, true);
                            break;
                         case QuestionnaireQuestion::TYPE_FACE:
                             $this->renderPartial('types/_text', array('options' => array()), false, true);
                             break;
                        case QuestionnaireQuestion::TYPE_NUMBER:
                             $this->renderPartial('types/_text', array('options' => array()), false, true);
                             break;
                        case QuestionnaireQuestion::TYPE_DROPDOWN:
                            $this->renderPartial('types/_multiple_choices', array('options' => array()), false, true);
                            break;
                    }
                }
            }
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($questionnaire_id) {
        $model = new QuestionnaireQuestion;
        $model->questionnaire_id = $questionnaire_id;

        $this->performAjaxValidation($model);

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

            $model->attributes = $_POST['QuestionnaireQuestion'];
            $this->parseQuestionType($model);

            if ($model->save()) {
                $this->redirect(array('admin', 'questionnaire_id' => $questionnaire_id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function parseQuestionType(&$model) {
        $types = QuestionnaireQuestion::getTypes();
        if (isset($types[$model->type])) {

            if ($model->type == QuestionnaireQuestion::TYPE_TEXT) {
                $model->options = CJSON::encode(array());
            }elseif ($model->type == QuestionnaireQuestion::TYPE_FACE) {
                $model->options = CJSON::encode(array());
            }elseif ($model->type == QuestionnaireQuestion::TYPE_NUMBER) {
                $model->options = CJSON::encode(array());
            }elseif ($model->type == QuestionnaireQuestion::TYPE_RANGE) {
                if (isset($_POST['Range'])) {
                    $model->options = CJSON::encode($_POST['Range'],JSON_UNESCAPED_UNICODE);
                }
            } elseif ($model->type == QuestionnaireQuestion::TYPE_CHECKBOXES) {
                if (isset($_POST['Choice'])) {
                    $x=$_POST['Choice'];
                    $model->options = CJSON::encode($x,JSON_UNESCAPED_UNICODE);
                }
            } elseif ($model->type == QuestionnaireQuestion::TYPE_MULTIPLE_CHOICES) {
                if (isset($_POST['Choice'])) {
                    $multi=$_POST['Choice'];
                    $model->options = CJSON::encode($multi,JSON_UNESCAPED_UNICODE);
                }
            }elseif ($model->type == QuestionnaireQuestion::TYPE_DROPDOWN) {
                if (isset($_POST['Choice'])) {
                    $multi=$_POST['Choice'];
                    $model->options = CJSON::encode($multi,JSON_UNESCAPED_UNICODE);
                }
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id, $questionnaire_id) {
        $model = $this->loadModel($id);

        // If the question has been used in answer, it mustn't be updated
        $criteria = new CDbCriteria;
        $criteria->condition = 'question_id = ' . $id;
        $answer = QuestionnaireAnswer::model()->find($criteria);
        if($answer){
            $this->redirect(['admin', 'questionnaire_id' => $questionnaire_id]);
        }

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

        if (isset($_POST['QuestionnaireQuestion'])) {
            $model->attributes = $_POST['QuestionnaireQuestion'];

            $this->parseQuestionType($model);

            if ($model->save()) {
                $this->redirect(array('admin', 'questionnaire_id' => $questionnaire_id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id, $questionnaire_id) {
        $this->loadModel($id)->delete();

// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax'])) {
            Yii::app()->user->setFlash('alert-success', Yii::t('admin', 'Item has been successfully deleted.'));
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin', 'questionnaire_id' => $questionnaire_id));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex($questionnaire_id) {
        $dataProvider = new CActiveDataProvider('QuestionnaireQuestion');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin($questionnaire_id) {


        $model = new QuestionnaireQuestion('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['QuestionnaireQuestion']))
            $model->attributes = $_GET['QuestionnaireQuestion'];

        $model->questionnaire_id = $questionnaire_id;

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * 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 $id the ID of the model to be loaded
     * @return QuestionnaireQuestion the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = QuestionnaireQuestion::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

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

}
