<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use app\base\Common;
use app\models\Screening;
use app\base\Converter;

/**
 * This is the model class for table "{{%cd4}}".
 *
 * @property integer $vl_id
 * @property string $vl_survey
 * @property string $vl_loc
 * @property string $vl_part_id
 * @property integer $vl_q1
 * @property integer $vl_q2
 * @property integer $vl_q3
 * @property integer $vl_q4
 * @property integer $vl_q5
 * @property integer $vl_q6
 * @property string $status
 * @property integer $create_time
 * @property integer $create_user
 * @property integer $update_time
 * @property integer $update_user
 */
class Vl extends \yii\db\ActiveRecord
{
	
	public $q1 = [1 => 'Baseline cohort study visit', -1 => 'Follow-up cohort study visit - 1', -2 => 'Follow-up cohort study visit - 2',-3 => 'Follow-up cohort study visit - 3',-4 => 'Follow-up cohort study visit - 4',3 => 'Intervening data entry'];
	public $q2 = [1 => 'Yes, there are new VL measurements to record', 2 => 'No new visits occurred (confirmed by ART book/client still not linked to Government ART)', 4 => 'Additional information is needed to verify whether there were new visits'];
	public $q5 = [1 => 'Local lists for each site', 2 => 'ICC should probably never be answer here - unless we were doing our own test through outside lab'];
	public $q6 = [1 => 'Government ART book', 2 => 'Records reviewed at Government HIV clinic', 3 => 'Records from other HIV facility', 4 => 'Other?'];
	public $q1Dum = [1 => 'Baseline', -1 => 'Follow-up-1', -2 => 'Follow-up-2',-3 => 'Follow-up-3',-4 => 'Follow-up-4',3 => 'Intervening'];	
    public $q4a = [1 => 'Undetected', 2 => 'Detected'];	

	public function init()
	{
		$this->q5 = Common::getFieldvalue("3");
	}

	/**
	 * @inheritdoc
	 */
    public static function tableName()
	{
		return '{{%vl}}';
	}

	/**
	 * @inheritdoc
	 */
	public function behaviors()
	{
		return [
			[
				'class' => TimestampBehavior::className(),
				'createdAtAttribute' => 'create_time',
				'updatedAtAttribute' => 'update_time',
				'value' => date('U'),
			]
		];
	}

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['vl_survey', 'vl_loc', 'vl_part_id', 'vl_q1', 'vl_q2'], 'required', 'message' => 'Cannot be blank.'],
			[['vl_q1', 'vl_q2', 'vl_q4','vl_q4a','vl_q5', 'vl_q6', 'create_time', 'create_user', 'update_time', 'update_user'], 'integer', 'message' => 'Must be an integer'],
			
			
			[['vl_q3', 'vl_q4','vl_q4a','vl_q5', 'vl_q6'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->vl_q2 == 1);
			}, 'whenClient' => "function (attribute, value) {
				return ($('#vl-vl_q2').val() == '1');
			}"],
			
			[['vl_q3'], 'safe'],
			[['vl_q4'], 'string', 'max' => 10],
			[['vl_survey', 'vl_loc', 'vl_part_id'], 'string', 'max' => 11],			
			[['status'], 'string', 'max' => 1],
			[['record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],
			[['vl_part_id', 'vl_q1'], 'serviceValidate'],
			//[['vl_q1'], 'dataentryValidate'],
			[['vl_q1'], 'dataentryValidate','on' => 'create'],
			[['vl_q3'], 'dateValidate'],
		
		];
	}
	
	
	public function serviceValidate($attribute, $params) {
        if($this->vl_part_id != "" && ($this->vl_q1 == 1 || $this->vl_q1 == -1 || $this->vl_q1 == -2 || $this->vl_q1 == -3 || $this->vl_q1 == -4)) :
			$Master = Screening::find()->where(["mem_scrn_part_id" => $this->vl_part_id])->orderBy(["mem_scrn_id" => SORT_DESC])->one();
			if($Master !== null) {
				if($Master->mem_scrn_q25 != 1) {
	    			$this->addError($attribute, 'Not Enrolled in Cohort Group / Study');
	    		}
    		} else {
    			$this->addError($attribute, 'Not Part of Cohort Study');
    		}
        endif;
	}

	public function dataentryValidate($attribute, $params) {
        if($this->vl_part_id != "") :
			$Master = parent::find()->where(["vl_part_id" => $this->vl_part_id])->one();
			if($Master !== null) {
				if($this->vl_q1 == 1) {
					$Basecount = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q1" => 1])->count();
					if($Basecount >= 1) {
						$this->addError($attribute, "Baseline Already Exists");
		    		}
	    		} elseif($this->vl_q1 == -1) {
					$Followuponecount = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q1" => -1])->count();
					if($Followuponecount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 1 Already Exists");
		    		}
	    		}
				elseif($this->vl_q1 == -2) {
					$Followuptwocount = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q1" => -2])->count();
					if($Followuptwocount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 2 Already Exists");
		    		}
	    		}
				elseif($this->vl_q1 == -3) {
					$Followupthreecount = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q1" => -3])->count();
					if($Followupthreecount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 3 Already Exists");
		    		}
	    		}
				elseif($this->vl_q1 == -4) {
					$Followupfourcount = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q1" => -4])->count();
					if($Followupfourcount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 4 Already Exists");
		    		}
	    		}
    		}
        endif;
	}
	
	public function dateValidate($attribute, $params) {
        if($this->vl_part_id != "" && $this->vl_q3 != "") :
        	// if (!Yii::$app->request->isAjax)
        		$this->vl_q3 = Converter::toStore($this->vl_q3);
			$Query = parent::find()->where(["vl_part_id" => $this->vl_part_id, "vl_q3" => $this->vl_q3]);
			if($this->vl_id != "")
				$Query->andWhere(["!=", "vl_id", $this->vl_id]);
			$Master = $Query->count();
			if($Master !== null && $Master == 0) {	
			
              $Query = Hivlinkage::find()->where(["hiv_linkage_part_id" => $this->vl_part_id])->andWhere(["hiv_linkage_q8" => null]);
				$MasterCount = $Query->count();
				$Master = $Query->one();
				if($Master !== null && $MasterCount != 0 && $Master->hiv_linkage_q2 !== null)
					$Hiv_Date = Converter::toStore($Master->hiv_linkage_q2);
                if($Master !== null && $MasterCount != 0 && $Master->hiv_linkage_q4 !== null)
					$PreART_Date = Converter::toStore($Master->hiv_linkage_q4); 				
				
    			if($Master !== null && $MasterCount != 0 && $this->vl_q3 < $Hiv_Date) {
	        		$this->vl_q3 = Converter::toDisplay($this->vl_q3);	        		
					$this->addError($attribute, "VL Date cannot be prior to Date of earliest HIV test");					
	    		} 	
				
				
				if($Master !== null && $MasterCount != 0 && $this->vl_q3 < $PreART_Date) {
	        		$this->vl_q3 = Converter::toDisplay($this->vl_q3);
	        		$this->addError($attribute, "Vl Date cannot be prior to Pre-ART Registration Date");
	    		}
				
				$Query = VL::find()->where(["vl_part_id" => $this->vl_part_id,"vl_q2"=>1])->orderBy(["vl_q3" => SORT_DESC]);
				$MasterCount = $Query->count();
				$Master = $Query->one();
				if($Master !== null && $MasterCount != 0 && $Master->vl_q3 !== null)
					$Lastvisit_Date = Converter::toStore($Master->vl_q3);
				
				if($Master !== null && $MasterCount != 0 && $this->vl_q3 < $Lastvisit_Date) {
	        		$this->vl_q3 = Converter::toDisplay($this->vl_q3);	        	
					$this->addError($attribute, "VL Date cannot be prior to Last VL Date");		
                }					
				else {
					// $this->addError($attribute);
		        	$this->vl_q3 = Converter::toDisplay($this->vl_q3);
	    		}
    		}
			elseif($Master !== null && $Master != 0) {
        		$this->vl_q3 = Converter::toDisplay($this->vl_q3);
				$this->addError($attribute, "VL records already exists for this Date");
    		} else {
	        	// if (!Yii::$app->request->isAjax)
	    			$this->vl_q3 = Converter::toDisplay($this->vl_q3);
    		}
        endif;
	}

	
	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'vl_id' => Yii::t('app', 'Vl Test ID'),
			'vl_survey' => Yii::t('app', 'Survey'),
			'vl_loc' => Yii::t('app', 'Location'),
			'vl_part_id' => Yii::t('app', 'ICC Client ID'),
			'vl_q1' => Yii::t('app', '1. What is the reason for this data entry?'),
			'vl_q2' => Yii::t('app', '2. Are there new VL data to record that were drawn during the window period AND have not been recorded previously?'),
			'vl_q3' => Yii::t('app', 'VL measured ON'),
			'vl_q4' => Yii::t('app', 'VL result (value)'),
            'vl_q4a' => Yii::t('app', 'VL result'),			
			'vl_q5' => Yii::t('app', 'VL measured at'),
			'vl_q6' => Yii::t('app', 'Source'),
			'status' => Yii::t('app', 'Status'),
			'create_time' => Yii::t('app', 'Create Time'),
			'create_user' => Yii::t('app', 'Create User'),
			'update_time' => Yii::t('app', 'Update Time'),
			'update_user' => Yii::t('app', 'Update User'),
		];
	}

	public function beforeSave($insert)
	{
		// parent::beforeSave();
		if (parent::beforeSave($insert)) {
			if($this->vl_q3 != "")
				$this->vl_q3 = Converter::toStore($this->vl_q3);
	        return true;
	    } else {
	        return false;
	    }
	}

	public function afterFind()
	{
		parent::afterFind();
		if(Yii::$app->controller->action->id != "view") {
			if($this->vl_q3 != "")
				$this->vl_q3 = Converter::toDisplay($this->vl_q3);
		}
	}

	public function getDate()
	{
		if(!empty($this->vl_q3)) {
			return Converter::toDisplay($this->vl_q3);
		}
		else
			return "-";
	}

	public function getNextDate()
	{
		if($this->vl_q3 != "") {
			if(!is_integer($this->vl_q3))
				$date = Converter::toStore($this->vl_q3);
			else
				$date = $this->vl_q3;
			$date = strtotime("180 Days", $date);
			return Converter::toDisplay($date);
		} else
			return "-";
	}
	
	 public function getVisits()
	{
		return $this->q1Dum[$this->vl_q1];
	}	
	
}