<?php

namespace app\controllers;

use Yii;
use app\base\Model;
use app\models\Cd4;
use app\models\Cd4Search;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Hivlinkage;

/**
 * Cd4Controller implements the CRUD actions for Cd4 model.
 */
class Cd4Controller extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index', 'create', 'update', 'view', 'delete', 'getlist'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Cd4 models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Cd4Search();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if(Yii::$app->request->isAjax)
            $this->layout = "base";

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Cd4 model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->cd4_test_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    */
    
    public function actionCreate()
    {
        $model = new Cd4;
        $models = [new Cd4];
		$model->scenario = 'create';

        if ($model->load(Yii::$app->request->post())) {

            // if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            //     Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            //     return \yii\widgets\ActiveForm::validate($model);
            // }

            // ajax validation
            if (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $models = [];
                $models = Model::createMultiple(Cd4::classname());
                Model::loadMultiple($models, Yii::$app->request->post());
                // return ActiveForm::validateMultiple($models);
                $valids = ActiveForm::validateMultiple($models);
                $dt = [];
                foreach ($models as $key => $value) {
                    if(in_array($value->cd4_test_q3, $dt)) {
                        $valids["cd4-$key-cd4_test_q3"] = ["CD4 records already exists for this Date"];
                    } else {
                        $dt[] = $value->cd4_test_q3;
                    }
                }
                
                return ArrayHelper::merge(
                    $valids,
                    ActiveForm::validate($model)
                );
            }

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $models   = [];
            foreach($post[$formName] as $k => $p) {
                $models[] = new Cd4;
                $posts[$formName][$k] = array_merge($p, $formVars);
            }
            // print_r($models);
            // exit;
            
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

                    if ($flag) {
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', "Records Created Successful");
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->cd4_test_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            } else {
                print_r($valid);
            }
        }
        
        return $this->render('create', [
            'model' => $model,
            'models' => (empty($models)) ? [new Cd4] : $models,
        ]);
    }

    /**
     * Updates an existing Cd4 model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        // if ($model->load(Yii::$app->request->post()) && $model->save()) {
        if ($model->load(Yii::$app->request->post())) {

            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return \yii\widgets\ActiveForm::validate($model);
            }
            if($model->save())
                return $this->redirect(['view', 'id' => $model->cd4_test_id]);
            else
                return $this->render('update', ['model' => $model]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    public function actionUpdate1($id)
    {
        $model = $this->findModel($id);
        $models = $this->findModels($id);

        if ($model->load(Yii::$app->request->post())) {

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $recmodels = $models;
            $models   = [];
            foreach($post[$formName] as $k => $p) {
                if(empty($p["cd4_test_id"])) {
                    $models[] = new Cd4;
                    $p["create_user"] = $model->create_user;
                    $p["cd4_test_survey"] = $model->cd4_test_survey;
                }
                else
                    $models[] = $this->findModel($p["cd4_test_id"]);
                $posts[$formName][$k] = array_merge($p, $formVars);
            }
            
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);

            if(count($recmodels) > count($posts[$formName])) {
                $delid = substr(Yii::$app->request->post()[$formName]["delrec"], 0, -1);
                foreach (array_unique(explode(",", $delid)) as $key => $value) {
                    $this->findModel($value)->delete();
                }
            }

            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return \yii\widgets\ActiveForm::validateMultiple($models);
            }

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

                    if ($flag) {
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', "Records Updated Successful");
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->cd4_test_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        return $this->render('update', [
            'model' => $model,
            'models' => (empty($models)) ? [new Cd4] : $models,
        ]);
    }

    /**
     * Deletes an existing Cd4 model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['/'.Yii::$app->controller->id]);
    }

    /**
     * Finds the Cd4 model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Cd4 the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Cd4::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function findModels($id)
    {
        $model = Cd4::findOne($id);
        $sur_id = $model->cd4_test_survey;
        $p_id = $model->cd4_test_part_id;
        $r_date = $model->record_date;

        if (($models = Cd4::find()->where(['cd4_test_survey' => $sur_id, 'cd4_test_part_id' => $p_id, 'record_date' => $r_date])->all()) !== null) {
            return $models;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	public function actionGetlist()
    {
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('pid');
        if ($request->isPost)
            $id = $request->post('pid');
        $model = Hivlinkage::find()->where(["hiv_linkage_part_id" => $id])->andWhere(["IS", "hiv_linkage_q8", NULL])->one();
        $services = [];
        $index = 0;
        
         $services[$index]['title'] = "Date of earliest HIV test";
            $services[$index]['value'] = $model->hiv_linkage_q2;
                      $index++;

       // if($model->hiv_linkage_q3 != "") {
            $services[$index]['title'] = "Pre-ART Registration";
            $services[$index]['text'] = $model->hiv_linkage_q3;
            $services[$index]['value'] = $model->hiv_linkage_q4;
            $index++;
       // }

       // if($model->hiv_linkage_q5 != "") {
            $services[$index]['title'] = "ART Registration";
            $services[$index]['text'] = $model->hiv_linkage_q5;
            $services[$index]['value'] = $model->hiv_linkage_q6;
            $index++;
       // }

      /*  $services[$index]['title'] = "Most Recent HIV Test Result in ICC";
        $services[$index]['title'] = "Client HIV Status";
        $services[$index]['text'] = $model->q1[$model->hiv_linkage_q1];
        $services[$index]['value'] = $model->hiv_linkage_q2;
        $index++;

        $services[$index]['title'] = "Known HIV-Positive";
        $services[$index]['text'] = ($model->hiv_linkage_q1 == "9") ? "Yes" : "No";
        $services[$index]['value'] = "";
*/
        // return $services;
        $provider = new \yii\data\ArrayDataProvider([
            'allModels' => $services,
            // 'sort' => [
            //     'attributes' => ['service', 'status'],
            // ],
        ]);
        return \yii\grid\GridView::widget([
            'dataProvider' => $provider,
			'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => '-','dateFormat' => 'dd-MM-Y',],
            // 'layout' => '<div class="box"><div class="box-header with-border"><b>Service Entry Status</b>{summary}</div><div class="box-body">{items}</div><div class="box-footer clearfix">{pager}</div></div>',
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                /* 'title',				
                 'text',				 
               [
                    'attribute' => 'value',
                   'format' => 'raw',
                ], */
				
				[
                   'attribute' => 'title',
				   'label'=>'Client HIV Linkage Status',                   
                ],
				[
                   'attribute' => 'text',
				    'label'=>'Reg.No',                   
                ],
			
				[
                   'attribute' => 'value',
				   'label'=>'Reg.date',
                   'format' => 'date',				   
                ], 
				
            ],
        ]);
    }
}
