<?php

namespace app\controllers;

use Yii;
use app\models\Screening;
use app\models\Hivlinkage;
use app\models\HivlinkageSearch;
use app\models\ScreeningSearch;
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\Applicationsettings;

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

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

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

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

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

        if ($model->load(Yii::$app->request->post())) {
            // ajax validation
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            
            if($model->save())
                return $this->redirect(['view', 'id' => $model->mem_scrn_id]);
            else
                return $this->render('create', ['model' => $model]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Screening 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())) {
            // ajax validation
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            
            if($model->save())
                return $this->redirect(['view', 'id' => $model->mem_scrn_id]);
            else
                return $this->render('create', ['model' => $model]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

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

    public function actionAjax()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('id');
        if ($request->isPost)
            $id = $request->post('id');
        $model = Hivlinkage::find()->where(["hiv_linkage_part_id" => $id])->andWhere(["IS", "hiv_linkage_q8", NULL])->one();
        if($model !== null)
            return $model->attributes;
        else
            return null;
    }

    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',				   
                ], 
				
            ],
        ]);
    }
	
	 public function actionControlsite()
    {
        $request = Yii::$app->request;
        if ($request->isPost)
            $id = $request->post('id');

        $model = Applicationsettings::find()->orderBy("create_time DESC")->one();
        if ($model !== null) {		
          return $model->app_control_site;
			
        } 
    }
}
