<?php

class QuestionnaireAnswerController 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('QuestionnaireAnswer');
        $es->update();
    }

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

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

        if (isset($_POST['QuestionnaireAnswer'])) {
            $model->attributes = $_POST['QuestionnaireAnswer'];
            if ($model->save())
                $this->redirect(array('admin'));
        }

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

    /**
     * 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) {
        $model = $this->loadModel($id);

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

        if (isset($_POST['QuestionnaireAnswer'])) {
            $model->attributes = $_POST['QuestionnaireAnswer'];
            if ($model->save())
                $this->redirect(array('admin'));
        }

        $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) {
        $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'));
        }
    }

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

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        // $model = new QuestionnaireAnswer('search');

        // $model->unsetAttributes();  // clear any default values
        // if (isset($_GET['QuestionnaireAnswer'])){
        //     $model->attributes = $_GET['QuestionnaireAnswer'];
        // }

        $questionnaire_id = $_GET['questionnaire_id'];

        // Get questionnaire questions_IDs
        $criteria = new CDbCriteria;
        $criteria->condition = 'questionnaire_id = ' . $questionnaire_id;
        $questions = QuestionnaireQuestion::model()->findAll($criteria);

        // Get unique_IDs of submissions that are related to questionnaire questions
        $criteria = new CDbCriteria;
        $criteria->select = 'uniq_id';
        $criteria->distinct = true;
        $criteria->addInCondition('question_id', array_column($questions, 'id'));
        $submissions_IDs = QuestionnaireAnswer::model()->findAll($criteria);
        $submissions_IDs = array_column($submissions_IDs, 'uniq_id');
        
        $questions_data = [];
        if($questions){
            foreach($questions as $questions){
                $questions_data[$questions->id] = $questions->title;
            }
        }

        $answers_data = [];
        if($submissions_IDs){
            foreach($submissions_IDs as $submissions_id){
                $answers_data[$submissions_id] = [];
                foreach($questions_data as $question_id => $_){
                    $criteria = new CDbCriteria;
                    $criteria->condition = 'uniq_id = "' . $submissions_id . '" AND question_id = ' . $question_id;
                    $answers = QuestionnaireAnswer::model()->findAll($criteria);
                    if($answers){
                        if(count($answers) > 1){
                            $merged_answer = '';
                            foreach($answers as $index => $answer){
                                $merged_answer .= $answer->data;
                                if($index != count($answers) - 1){
                                    $merged_answer .= ', ';
                                }
                            }
                            $answers_data[$submissions_id][] = $merged_answer;
                        }
                        else{
                            $answers_data[$submissions_id][] = $answers[0]->data;
                        }
                    }
                    else{
                        $answers_data[$submissions_id][] = null;
                    }
                }
            }
        }
        
        $dataProvider = new CArrayDataProvider($answers_data, [
            'id' => 'ansers',
            'pagination' => [
                'pageSize' => 100
            ]
        ]);

        $this->render('admin', array(
            'dataProvider' => $dataProvider,
            'questions_data' => $questions_data,
            '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 QuestionnaireAnswer the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = QuestionnaireAnswer::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param QuestionnaireAnswer $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'questionnaire-answer-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
/////////////////////////////////////////////EXPORT QUESTIONNAIRER RESULT/////////////////////////////////////////
    public function actionResult_questionnaire($questionnaire_id)
    {
        $Questionnaire=Questionnaire::model()->findByAttributes(array('id'=>$questionnaire_id)); 
        $fileName=$Questionnaire->title;
            Yii::import ( 'ext.phpexcel.XPHPExcel' );
		// create excel object
		    $objPHPExcel = XPHPExcel::createPHPExcel ();
		    $sheet = $objPHPExcel->setActiveSheetIndex ( 0 );
		    if (Yii::app ()->getLocale ( Yii::app ()->getLanguage () )->getOrientation () == 'rtl')
			$sheet->setRightToLeft ( true );
            $questionsMap=array();
            $questions=QuestionnaireQuestion::model()->findAllByAttributes(array('questionnaire_id'=>$questionnaire_id),array('order'=>'id'));
            $i=0;
            foreach($questions as $question)
            {
                $questionsMap[$question->id]=$i;
                $sheet->setCellValueByColumnAndRow ( $i, 1, $question->title );
                $sheet->getColumnDimensionByColumn ( $i )->setWidth ( 20 );
                $sheet->getStyleByColumnAndRow ( $i, 1 )->applyFromArray ( [ 
                        'fill' => [ 
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array (
                                        'rgb' => 'CCCCCC' 
                                ) 
                        ] 
                ] );
		        $sheet->setCellValueByColumnAndRow ( $i, 1, $question->title );
            $i++;
            }
            $distinct_answers=QuestionnaireAnswer::model()->findAllByAttributes(array('question_id'=>array($question->id)),array('distinct'=>true,'group'=>'uniq_id',));
            
            $row_index = 2;
            
            foreach($distinct_answers as $question_answer)
            {
                $answearMap=array();
               
                $answears=QuestionnaireAnswer::model()->findAllByAttributes(array('uniq_id'=>$question_answer->uniq_id),array('order'=>'question_id'));
                foreach($answears as $answear)
                {
                  
                    if (array_key_exists($answear->question_id,$questionsMap))
                    {
                            if(array_key_exists($answear->question_id,$answearMap))
                            {
                                $prevValue=$sheet->getCellByColumnAndRow ( $questionsMap[$answear->question_id], $row_index)->getValue ();
                                $sheet->setCellValueByColumnAndRow ( $questionsMap[$answear->question_id], $row_index, $prevValue.",".$answear->data );
                            }
                               
                            else 
                            $sheet->setCellValueByColumnAndRow ( $questionsMap[$answear->question_id], $row_index, $answear->data );
                    }
                    $answearMap[$answear->question_id]=$answear->id;
                   
                   
                }
                $row_index++;
            }
  
            header ( 'Content-type: application/vnd.ms-excel' );
		    header ( 'Content-Disposition: attachment; filename="' . $fileName . '.xlsx"' );
		    $writer = PHPExcel_IOFactory::createWriter ( $objPHPExcel, 'Excel2007' );
		    $writer->save ( 'php://output' );
		    Yii::app ()->end ();
            die;
          

    }

    public function actionExportResults($questionnaire_id){
        Yii::import('ext.phpexcel.XPHPExcel');
        $questionnaire = Questionnaire::model()->findByPk($questionnaire_id);
        $excel_obj = XPHPExcel::createPHPExcel();
        $sheet = $excel_obj->setActiveSheetIndex(0);
        $sheet->setRightToLeft(true);

        $questions = QuestionnaireQuestion::model()->findAllByAttributes(['questionnaire_id' => $questionnaire_id]);
        if($questions){
            foreach($questions as $index => $question){
                $sheet->setCellValueByColumnAndRow($index, 1, $question->title);
                $sheet->getStyleByColumnAndRow($index, 1 )->applyFromArray([
                    'fill' => [ 
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => [
                            'rgb' => 'CCCCCC'
                        ]
                    ] 
                ]);
            }

            // Get unique_IDs of submissions that are related to questionnaire questions
            $criteria = new CDbCriteria;
            $criteria->select = 'uniq_id';
            $criteria->distinct = true;
            $criteria->addInCondition('question_id', array_column($questions, 'id'));
            $submissions_IDs = QuestionnaireAnswer::model()->findAll($criteria);
            $submissions_IDs = array_column($submissions_IDs, 'uniq_id');
            
            $answers_data = [];
            if($submissions_IDs){
                foreach($submissions_IDs as $row => $submissions_id){
                    $answers_data[$submissions_id] = [];
                    foreach($questions as $col => $question){
                        $criteria = new CDbCriteria;
                        $criteria->condition = 'uniq_id = "' . $submissions_id . '" AND question_id = ' . $question->id;
                        $answers = QuestionnaireAnswer::model()->findAll($criteria);
                        if($answers){
                            if(count($answers) > 1){
                                $merged_answer = '';
                                foreach($answers as $index => $answer){
                                    $merged_answer .= $answer->data;
                                    if($index != count($answers) - 1){
                                        $merged_answer .= "\n";
                                    }
                                }
                                $sheet->setCellValueByColumnAndRow($col, $row + 2, $merged_answer);
                                $sheet->getStyleByColumnAndRow($col, $row + 2)->applyFromArray([
                                    'alignment' => [
                                        'wrap' => true
                                    ]
                                ]);
                            }
                            else{
                                $sheet->setCellValueByColumnAndRow($col, $row + 2, $answers[0]->data);
                            }
                        }
                        else{
                            $sheet->setCellValueByColumnAndRow($col, $row + 2, '');
                        }
                    }
                }
            }
        }

        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $questionnaire->title . '_' . time() . '.xlsx"');
        $writer = PHPExcel_IOFactory::createWriter($excel_obj, 'Excel2007');
        $writer->save('php://output');
        Yii::app()->end();
        die;
    }

}
