<?php

namespace app\models;

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

/**
 * This is the model class for table "{{%hivvisit}}".
 *
 * @property integer $hiv_visit_id
 * @property string $hiv_visit_survey
 * @property string $hiv_visit_loc
 * @property string $hiv_visit_part_id
 * @property integer $hiv_visit_q1
 * @property integer $hiv_visit_q2
 * @property integer $hiv_visit_q3
 * @property integer $hiv_visit_q4
 * @property integer $hiv_visit_q5
 * @property integer $hiv_visit_q6
 * @property integer $hiv_visit_q6a
 * @property integer $hiv_visit_q7
 * @property integer $hiv_visit_q7a
 * @property integer $hiv_visit_q8
 * @property integer $hiv_visit_q8a
 * @property integer $hiv_visit_q9
 * @property integer $hiv_visit_q9a
 * @property integer $hiv_visit_q10
 * @property integer $hiv_visit_q11
 * @property string $status
 * @property integer $create_time
 * @property integer $create_user
 * @property integer $update_time
 * @property integer $update_user
 */
class Hivvisit extends \yii\db\ActiveRecord
{
	public $yes_no = [0 => "No", 1 => "Yes"];
	public $yes_no_dk = [0 => "No", 1 => "Yes", 997 => "Don't Know"];
	/*public $q1 = [1 => "Baseline study visit", 2 => "Follow-up study visit", 3 => "Intervening data entry"];
	public $q1 = [1 => 'Baseline cohort study visit', 2 => 'Follow-up cohort study visit - 1', 4 => 'Follow-up cohort study visit - 2',5 => 'Follow-up cohort study visit - 3',6 => 'Follow-up cohort study visit - 4',3 => 'Intervening data entry'];
	public $q2 = [1 => 'Yes, there are new visits to record', 2 => 'No new visits occurred (confirmed by ART book)', 3 => 'No new visits occurred (no pre-ART registration)', 4 => 'Additional information is needed to verify whether there were new visits'];
	*/
	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 visits 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 $q10 = [1 => '[Local lists of govt. clinics for each site]', 2 => 'ICC'];
	public $q11 = [1 => 'Government ART book', 2 => 'Records reviewed at Government HIV clinic', 3 => 'Visit occurred at ICC and documented here', 4 => 'Other'];
	public $hivlink7a, $hivlink7b, $hivlink7c, $hivlink7d;
	public $cid;
	public $q1Dum = [1 => 'Baseline', -1 => 'Follow-up-1', -2 => 'Follow-up-2',-3 => 'Follow-up-3',-4 => 'Follow-up-4',3 => 'Intervening'];

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

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

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

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['hiv_visit_survey', 'hiv_visit_loc', 'hiv_visit_part_id', 'hiv_visit_q1', 'hiv_visit_q2'], 'required', 'message' => 'Cannot be blank.'],
			[['hiv_visit_q3', 'hiv_visit_q4', 'hiv_visit_q11'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q2 == 1);
			}, 'whenClient' => "function (attribute, value) {
				return ($('#hivvisit-hiv_visit_q2').val() == 1);
			}"],
			// [['hiv_visit_q6a', 'hiv_visit_q7a', 'hiv_visit_q8a', 'hiv_visit_q9a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
			// 	return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q5 == 1);
			// }, 'whenClient' => "function (attribute, value) {
			// 	// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q5').val() == 1);
			// }"],
			
			[['hiv_visit_q6a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1);
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1);
			}"],
			
		  /*
			[['hiv_visit_q6a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q7a == '' && $model->hiv_visit_q8a == '' && $model->hiv_visit_q9a == '' );
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q7a').val() == '' && $('#hivvisit-hiv_visit_q8a').val() == '' && $('#hivvisit-hiv_visit_q9a').val() == '');
			}"],
			
			
			[['hiv_visit_q7a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q6a == '' && $model->hiv_visit_q8a == '' && $model->hiv_visit_q9a == '' );
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q6a').val() == '' && $('#hivvisit-hiv_visit_q8a').val() == '' && $('#hivvisit-hiv_visit_q9a').val() == '');
			}"],
			
			[['hiv_visit_q8a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q6a == '' && $model->hiv_visit_q7a == '' && $model->hiv_visit_q9a == '' );
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q6a').val() == '' && $('#hivvisit-hiv_visit_q7a').val() == '' && $('#hivvisit-hiv_visit_q9a').val() == '');
			}"],
			
			[['hiv_visit_q9a'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q6a == '' && $model->hiv_visit_q7a == '' && $model->hiv_visit_q8a == '' );
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q6a').val() == '' && $('#hivvisit-hiv_visit_q7a').val() == '' && $('#hivvisit-hiv_visit_q8a').val() == '');
			}"],
			*/
			
			[['hiv_visit_q6'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q6a != '');
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q6a').val() != '');
			}"],
			
			[['hiv_visit_q7'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q7a != '');
			}, 'whenClient' => "function (attribute, value) {
				return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q7a').val() != '');
			}"],
			[['hiv_visit_q8'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q8a != '');
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q8a').val() != '');
			}"],
			[['hiv_visit_q9'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1 && $model->hiv_visit_q9a != '');
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1 && $('#hivvisit-hiv_visit_q9a').val() != '');
			}"],
			
			[['hiv_visit_q5', 'hiv_visit_q10'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->hiv_visit_q4 == 1);
			}, 'whenClient' => "function (attribute, value) {
				// return ($('#hivvisit-hiv_visit_q4').val() == 1);
			}"],
			
			[['hiv_visit_q1', 'hiv_visit_q2', 'hiv_visit_q4', 'hiv_visit_q5', 'hiv_visit_q6', 'hiv_visit_q7', 'hiv_visit_q8', 'hiv_visit_q9', 'hiv_visit_q10', 'hiv_visit_q11', 'create_time', 'create_user', 'update_time', 'update_user'], 'integer', 'message' => 'Must be an integer'],
			// [['hiv_visit_q3', 'hiv_visit_q6a', 'hiv_visit_q7a', 'hiv_visit_q8a', 'hiv_visit_q9a'], 'safe'],
			[['hiv_visit_q6', 'hiv_visit_q7', 'hiv_visit_q8', 'hiv_visit_q9', 'hiv_visit_q6a', 'hiv_visit_q7a', 'hiv_visit_q8a', 'hiv_visit_q9a'], 'string', 'max' => 3],
			[['hiv_visit_survey', 'hiv_visit_loc', 'hiv_visit_part_id'], 'string', 'max' => 11],
			[['status'], 'string', 'max' => 1],
			[['record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],
			[['hiv_visit_part_id', 'hiv_visit_q1'], 'serviceValidate'],
			[['hiv_visit_q1'], 'dataentryValidate','on' => 'create'],
			[['hiv_visit_q3'], 'dateValidate'],
			[['hiv_visit_q4'], 'arvDispense'],
			// [['hiv_visit_part_id', 'hiv_visit_q3'], 'unique', 'targetAttribute' => ['hiv_visit_part_id', 'hiv_visit_q3'], 'message' => 'The combination of Survey, Test Name and Specimen has already been taken.'],
		];
	}

	/*
	public function serviceValidate($attribute, $params) {
        if($this->hiv_visit_part_id != "" && ($this->hiv_visit_q1 == 1 || $this->hiv_visit_q1 == 2 || $this->hiv_visit_q1 == 4 || $this->hiv_visit_q1 == 5 || $this->hiv_visit_q1 == 6)) :
			$Master = Screening::find()->where(["mem_scrn_part_id" => $this->hiv_visit_part_id])->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 serviceValidate($attribute, $params) {
        if($this->hiv_visit_part_id != "" && ($this->hiv_visit_q1 == 1 || $this->hiv_visit_q1 == -1 || $this->hiv_visit_q1 == -2 || $this->hiv_visit_q1 == -3 || $this->hiv_visit_q1 == -4)) :
			$Master = Screening::find()->where(["mem_scrn_part_id" => $this->hiv_visit_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 arvDispense($attribute, $params) {
        if($this->hiv_visit_part_id != "" && $this->hiv_visit_q4 != '' && $this->hiv_visit_q4 == 1) :
			$Query = Hivlinkage::find()->where(["hiv_linkage_part_id" => $this->hiv_visit_part_id])->andWhere(["hiv_linkage_q8" => null]);
			$MasterCount = $Query->count();
			$Master = $Query->one();
			if($Master !== null) {
				if($Master->hiv_linkage_q5 == "") {
	    			$this->addError($attribute, 'Please update ART ID in HIV Linkage form.');
	    		}
    		}
        endif;
	}
 /*
	public function dataentryValidate($attribute, $params) {
        if($this->hiv_visit_part_id != "") :
			$Master = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id])->one();
			if($Master !== null) {
				if($this->hiv_visit_q1 == 1) {
					$Basecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 1])->count();
					if($Basecount >= 1) {
						$this->addError($attribute, "Baseline Already Exists");
		    		}
	    		} elseif($this->hiv_visit_q1 == 2) {
					$Followupnoecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 2])->count();
					if($Followuponecount >= 4) {
						$this->addError($attribute, "Follow-up cohort study visit 1 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == 4) {
					$Followuptwocount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 4])->count();
					if($Followuptwocount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 2 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == 5) {
					$Followupthreecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 5])->count();
					if($Followupthreecount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 3 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == 6) {
					$Followupfourcount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 6])->count();
					if($Followupfourcount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 4 Already Exists");
		    		}
	    		}
    		}
        endif;
	}
	*/
	
	public function dataentryValidate($attribute, $params) {
        if($this->hiv_visit_part_id != "") :
			$Master = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id])->one();
			if($Master !== null) {
				if($this->hiv_visit_q1 == 1) {
					$Basecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => 1])->count();
					if($Basecount >= 1) {
						$this->addError($attribute, "Baseline Already Exists");
		    		}
	    		} elseif($this->hiv_visit_q1 == -1) {
					$Followuponecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => -1])->count();
					if($Followuponecount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 1 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == -2) {
					$Followuptwocount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => -2])->count();
					if($Followuptwocount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 2 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == -3) {
					$Followupthreecount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q1" => -3])->count();
					if($Followupthreecount >= 1) {
						$this->addError($attribute, "Follow-up cohort study visit 3 Already Exists");
		    		}
	    		}
				elseif($this->hiv_visit_q1 == -4) {
					$Followupfourcount = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_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->hiv_visit_part_id != "" && $this->hiv_visit_q3 != "") :
        	// if (!Yii::$app->request->isAjax)
        		$this->hiv_visit_q3 = Converter::toStore($this->hiv_visit_q3);
			$Query = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q3" => $this->hiv_visit_q3]);
			if($this->hiv_visit_id != "")
				$Query->andWhere(["!=", "hiv_visit_id", $this->hiv_visit_id]);
			$Master = $Query->count();
			if($Master !== null && $Master == 0) {
				$Query = Hivlinkage::find()->where(["hiv_linkage_part_id" => $this->hiv_visit_part_id])->andWhere(["hiv_linkage_q8" => null]);
				$MasterCount = $Query->count();
				$Master = $Query->one();
				if($Master->hiv_linkage_q6 !== null && $this->hiv_visit_q4 == "1")
					$ART_Date = Converter::toStore($Master->hiv_linkage_q6);
				else
					$ART_Date = Converter::toStore($Master->hiv_linkage_q4);
				// echo $this->hiv_visit_q3." = ".$ART_Date."<br>";
    			if($Master !== null && $MasterCount != 0 && $this->hiv_visit_q3 < $ART_Date) {
	        		$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
	        		if($this->hiv_visit_q4 == "1")
						$this->addError($attribute, "HIV Visit Date cannot be prior to ART Registration Date");
					else
						$this->addError($attribute, "HIV Visit Date cannot be prior to Pre-ART Registration Date");
	    		} else {
					// $this->addError($attribute);
		        	$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
	    		}
    		} elseif($Master !== null && $Master != 0) {
        		$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
				$this->addError($attribute, "HIV Visit records already exists for this Date");
    		} else {
	        	// if (!Yii::$app->request->isAjax)
	    			$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
    		}
        endif;
	} 
	*/
	
	public function dateValidate($attribute, $params) {
        if($this->hiv_visit_part_id != "" && $this->hiv_visit_q3 != "") :
        	// if (!Yii::$app->request->isAjax)
        		$this->hiv_visit_q3 = Converter::toStore($this->hiv_visit_q3);
			$Query = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q3" => $this->hiv_visit_q3]);
			if($this->hiv_visit_id != "")
				$Query->andWhere(["!=", "hiv_visit_id", $this->hiv_visit_id]);
			$Master = $Query->count();
			if($Master !== null && $Master == 0) {
				$Query = Hivlinkage::find()->where(["hiv_linkage_part_id" => $this->hiv_visit_part_id])->andWhere(["hiv_linkage_q8" => null]);
				$MasterCount = $Query->count();
				$Master = $Query->one();
				if($Master->hiv_linkage_q6 !== null && $this->hiv_visit_q4 == "1")
					$ART_Date = Converter::toStore($Master->hiv_linkage_q6);
				else
					$ART_Date = Converter::toStore($Master->hiv_linkage_q4);
				 //echo $this->hiv_visit_q3." = ".$ART_Date."<br>";
				// print_r ($ART_Date);
    			if($Master !== null && $MasterCount != 0 && $this->hiv_visit_q3 < $ART_Date) {
	        		$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
	        		if($this->hiv_visit_q4 == "1")
						$this->addError($attribute, "HIV Visit Date cannot be prior to ART Registration Date");
					else
						$this->addError($attribute, "HIV Visit Date cannot be prior to Pre-ART Registration Date");
	    		} 				
				$Query = Hivvisit::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id,"hiv_visit_q2" =>1])->orderBy(["hiv_visit_q3" => SORT_DESC]);
				$MasterCount = $Query->count();
				$Master = $Query->one();
				if($Master !== null && $MasterCount != 0 && $Master->hiv_visit_q3 !== null)
					$Lastvisit_Date = Converter::toStore($Master->hiv_visit_q3);
				
				if($Master !== null && $MasterCount != 0 && $this->hiv_visit_q3 < $Lastvisit_Date) {
	        		$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);	        	
					$this->addError($attribute, "HIV Visit Date cannot be prior to Last Visit Date");		
                }					
				else {
					// $this->addError($attribute);
		        	$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
	    		}
    		} elseif($Master !== null && $Master != 0) {
        		$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
				$this->addError($attribute, "HIV Visit records already exists for this Date");
    		} else {
	        	// if (!Yii::$app->request->isAjax)
	    			$this->hiv_visit_q3 = Converter::toDisplay($this->hiv_visit_q3);
    		}
        endif;
	}

	public function attributes()
	{
	    $attrs = parent::attributes();
	    $attrs[] = 'hivlink7a';
	    $attrs[] = 'hivlink7b';
	    $attrs[] = 'hivlink7c';
	    $attrs[] = 'hivlink7d';
	    return $attrs;
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'hiv_visit_id' => Yii::t('app', 'Hiv Visit ID'),
			'hiv_visit_survey' => Yii::t('app', 'Survey'),
			'hiv_visit_loc' => Yii::t('app', 'Location'),
			'hiv_visit_part_id' => Yii::t('app', 'ICC Client ID'),
			'hiv_visit_q1' => Yii::t('app', '1. What is the reason for this data entry'),
			'hiv_visit_q2' => Yii::t('app', '2. Are there new HIV doctor visits to record that occurred during the window period AND have not been recorded previously?'),
			'hiv_visit_q3' => Yii::t('app', '3. Date of the HIV visit'),
			'hiv_visit_q4' => Yii::t('app', '4. ARV dispensed (Y/N)'),
			'hiv_visit_q5' => Yii::t('app', '5. Has the ARV changed since the last refill.'),
			'hiv_visit_q6a' => Yii::t('app', 'ARV1 Pills'),
			'hiv_visit_q6' => Yii::t('app', '6. ARV1'),
			'hiv_visit_q7a' => Yii::t('app', 'ARV2 Pills'),
			'hiv_visit_q7' => Yii::t('app', '7. ARV2'),
			'hiv_visit_q8a' => Yii::t('app', 'ARV3 Pills'),
			'hiv_visit_q8' => Yii::t('app', '8. ARV3'),
			'hiv_visit_q9a' => Yii::t('app', 'ARV4 Pills'),
			'hiv_visit_q9' => Yii::t('app', '9. ARV4'),
			'hiv_visit_q10' => Yii::t('app', '10. ARV dispensed at'),
			'hiv_visit_q11' => Yii::t('app', '11. Data 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->hiv_visit_q3 != "")
				$this->hiv_visit_q3 = Converter::toStore($this->hiv_visit_q3);

			$IncMaster = Incentivesmaster::find()->where(["incentive_master_part_id" => $this->hiv_visit_part_id])->one();
			$Master = Hivlinkage::find()->where(["hiv_linkage_part_id" => $this->hiv_visit_part_id])->andWhere(["hiv_linkage_q8" => null])->one();
			//$ScrMaster = Screening::find()->where(["mem_scrn_part_id" => $this->hiv_visit_part_id])->one();
			$ScrMaster = Screening::find()->where(["mem_scrn_part_id" => $this->hiv_visit_part_id])->orderBy(['record_date' => SORT_ASC])->one();

			if($IncMaster === null || $Master === null || $ScrMaster === null)
				return true;

			if($Master->hiv_linkage_q6 != "" && !is_integer($Master->hiv_linkage_q6))
				$Master->hiv_linkage_q6 = Converter::toStore($Master->hiv_linkage_q6);
			if($IncMaster !== null && $IncMaster->incentive_master_q1 == "1" && $Master !== null && $Master->hiv_linkage_q2a == "1" && $ScrMaster->mem_scrn_q28 == "1" && ($Master->hiv_linkage_q5 == "" || ($Master->hiv_linkage_q5 != "" && $this->hiv_visit_q3 < $Master->hiv_linkage_q6))) {
				$PreARTIncMaster = Preartincenmaster::find()->where(["preart_inc_part_id" => $this->hiv_visit_part_id])->orderBy(["preart_inc_id" => SORT_DESC])->one();
				if($PreARTIncMaster !== null) {
					if($PreARTIncMaster->preart_inc_visitdate == $this->hiv_visit_q3)
						return true;

				 	if(!is_integer($PreARTIncMaster->preart_inc_visitdate))
						$lastvisitDate = Converter::toStore($PreARTIncMaster->preart_inc_visitdate);
					else
						$lastvisitDate = $PreARTIncMaster->preart_inc_visitdate;

					$date = strtotime("150 Days", $lastvisitDate);
					if($this->hiv_visit_q3 < $date)
						return true;
				}

				$PreARTIncMaster = new Preartincenmaster();
				if($this->hiv_visit_q3 >= $ScrMaster->record_date) {
					$PreARTIncMaster->preart_inc_survey = $this->hiv_visit_survey;
					$PreARTIncMaster->preart_inc_part_id = $this->hiv_visit_part_id;
					$PreARTIncMaster->preart_inc_visitdate = $this->hiv_visit_q3;
					$PreARTIncMaster->preart_inc_q1 = 0;
					$PreARTIncMaster->preart_inc_q2 = 250;
					if(!$PreARTIncMaster->save())
						print_r($PreARTIncMaster->errors);
				}
			} elseif($this->hiv_visit_q4 == "1" && $IncMaster !== null && $IncMaster->incentive_master_q2 == "1" && $Master !== null && $Master->hiv_linkage_q2a == "1" && $ScrMaster->mem_scrn_q28 == "1" && $Master->hiv_linkage_q5 != "" && $ScrMaster->record_date <= $Master->hiv_linkage_q6 ) {
				if($IncMaster !== null && $IncMaster->incentive_master_q2 == 1)
				{
					$IncMaster->incentive_master_q1 = 0;
					$IncMaster->incentive_master_q2 = 0;
					$IncMaster->incentive_master_q4 = 1;

					$Art_Inc_Model = Artinitiationincentmaster::find()->where(['art_init_inc_part_id' => $this->hiv_visit_part_id])->one();
					if($Art_Inc_Model === null)
						$Art_Inc_Model = new Artinitiationincentmaster();

					$Art_Inc_Model->art_init_inc_survey = $this->hiv_visit_survey;
					$Art_Inc_Model->art_init_inc_part_id = $this->hiv_visit_part_id;
					$Art_Inc_Model->art_init_inc_visitdate = $this->hiv_visit_q3;
					$Art_Inc_Model->art_init_inc_q1 = 0;
					$Art_Inc_Model->art_init_inc_q2 = 500;

					if($Art_Inc_Model->save())
						$IncMaster->save();
				}
			} elseif($this->hiv_visit_q4 == "1" && $IncMaster !== null && $IncMaster->incentive_master_q4 == "1" && $Master !== null && $Master->hiv_linkage_q2a == "1" && $Master->hiv_linkage_q5 != "" && $ScrMaster->mem_scrn_q28 == "1") {
				$today = $this->hiv_visit_q3;
				$prevtoday = strtotime("-30 Days", $today);

				// echo Converter::toDisplay($today)." > ".Converter::toDisplay($prevtoday)."<br>";
				$ARTIncMaster = Artincenmaster::find()->where(["art_inc_part_id" => $this->hiv_visit_part_id])->andWhere(["BETWEEN", "art_inc_visitdate", $prevtoday, $today])->orderBy(["art_inc_id" => SORT_DESC]);
				$ARTIncMasterCount = $ARTIncMaster->count();
				if($ARTIncMasterCount >= 2)
					return true;
				else
				  $ARTIncMaster = Artincenmaster::find()->where(["art_inc_part_id" => $this->hiv_visit_part_id])->orderBy(["art_inc_id" => SORT_DESC])->one();
				
				  // $ARTIncMaster = Artincenmaster::find()->where(["art_inc_part_id" => $this->hiv_visit_part_id,"art_inc_visitdate" => $this->hiv_visit_q3])->orderBy(["art_inc_id" => SORT_DESC])->one();

				if($ARTIncMaster !== null) {
					//if($ARTIncMaster->art_inc_visitdate == $this->hiv_visit_q3)
					//	return true;
				  
				   $ARTIncMaster2 = Artincenmaster::find()->where(["art_inc_part_id" => $this->hiv_visit_part_id,"art_inc_visitdate" => $this->hiv_visit_q3])->orderBy(["art_inc_id" => SORT_DESC])->one();
				     if($ARTIncMaster2 !== null) {
						return true;
				   }

					// 	$ARVModel = $this->getARV($this->hiv_visit_q6a, "all");
					// 	$div = 1;
					// 	if($ARVModel->arv_mstr_dose == "OD")
					// 		$div = 1;
					// 	elseif($ARVModel->arv_mstr_dose == "BD")
					// 		$div = 2;
					// 	elseif($ARVModel->arv_mstr_dose == "2BD")
					// 		$div = 4;

					// 	$days = ($this->hiv_visit_q6 / $div) + ceil(($this->hiv_visit_q6 / $div) * 10/100);
					if(!is_integer($ARTIncMaster->art_inc_visitdate))
						$lastIncDate = Converter::toStore($ARTIncMaster->art_inc_visitdate);
					else
						$lastIncDate = $ARTIncMaster->art_inc_visitdate;

					$Model = $this->getLastPills($this->hiv_visit_part_id, $lastIncDate);
					$lastvisitDate = $Model['lastvisitDate'];
					$days = $Model['days'];

					$date = strtotime($days." Days", $lastvisitDate);
					// echo Converter::toDisplay($lastvisitDate)." ".Converter::toDisplay($this->hiv_visit_q3)." > ".Converter::toDisplay($date)." ".$days."<br>";
					if($this->hiv_visit_q3 > $date) {
						// $Model = self::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id, "hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC])->one();
						// $ARVModel = $this->getARV($Model->hiv_visit_q6a, "all");
						// $div = 1;
						// if($ARVModel->arv_mstr_dose == "OD")
						// 	$div = 1;
						// elseif($ARVModel->arv_mstr_dose == "BD")
						// 	$div = 2;
						// elseif($ARVModel->arv_mstr_dose == "2BD")
						// 	$div = 4;
						
						// $days = ($Model->hiv_visit_q6 / $div) + ceil(($Model->hiv_visit_q6 / $div) * 10/100);
						// if(!is_integer($Model->hiv_visit_q3))
						// 	$lastvisitDate = Converter::toStore($Model->hiv_visit_q3);
						// else
						// 	$lastvisitDate = $Model->hiv_visit_q3;
						$Model = $this->getLastPills($this->hiv_visit_part_id);
						$lastvisitDate = $Model['lastvisitDate'];
						$days = $Model['days'];

						$date = strtotime($days." Days", $lastvisitDate);
						// echo "2. ".Converter::toDisplay($lastvisitDate)." ".Converter::toDisplay($this->hiv_visit_q3)." > ".Converter::toDisplay($date)." ".$days."<br>";
						if($this->hiv_visit_q3 > $date)
							return true;
					}					
					
    				$Hivvisitmodel = $this->getLastPills($this->hiv_visit_part_id);
					    $lastvisitDate = $Hivvisitmodel['lastvisitDate'];	
                        $days = $Hivvisitmodel['days'];
                        $actualvisitdate = strtotime($days." Days", $lastvisitDate);									
												
						if($this->hiv_visit_q3 > $actualvisitdate)
					     return true;
                   					 
				} else {
					$HivvisitMaster =self::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id])->andWhere(["hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC]);
					if($HivvisitMaster !== null) {
    					$Hivvisitmodel = $this->getLastPills($this->hiv_visit_part_id);
					    $lastvisitDate = $Hivvisitmodel['lastvisitDate'];						
						$days = $Hivvisitmodel['days'];
                        $actualvisitdate = strtotime($days." Days", $lastvisitDate);						
											
						if($this->hiv_visit_q3 > $actualvisitdate)
					     return true;
					}
				
					$Art_Inc_Model = Artinitiationincentmaster::find()->where(['art_init_inc_part_id' => $this->hiv_visit_part_id])->one();
					if($Art_Inc_Model !== null) {
						$Model = $this->getLastPills($this->hiv_visit_part_id);
						$lastvisitDate = $Model['lastvisitDate'];
						$days = $Model['days'];
						$date = strtotime($days." Days", $lastvisitDate);
						if($this->hiv_visit_q3 > $date)
							return true;
					}
				}

				$ARTIncMaster = new Artincenmaster();
				if($this->hiv_visit_q3 >= $ScrMaster->record_date) {
					$ARTIncMaster->art_inc_survey = $this->hiv_visit_survey;
					$ARTIncMaster->art_inc_part_id = $this->hiv_visit_part_id;
					$ARTIncMaster->art_inc_visitdate = Converter::toDisplay($this->hiv_visit_q3);
					$ARTIncMaster->art_inc_q1 = 0;
					$ARTIncMaster->art_inc_q2 = 150;
					if(!$ARTIncMaster->save())
						print_r($ARTIncMaster->errors);
				}
			}

	        return true;
	    } else {
	        return false;
	    }
	}

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

	public function getLastPills($pid = "", $date = "")
	{
		if($date == "")
			$Model = self::find()->where(["hiv_visit_part_id" => $pid, "hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC])->one();
		else
			$Model = self::find()->where(["hiv_visit_part_id" => $pid, "hiv_visit_q3" => $date, "hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC])->one();
		if($Model !== null) {
	 	$ARVModel = $this->getARV($Model->hiv_visit_q6a, "all");
	 	$div = 1;
	 	if($ARVModel->arv_mstr_dose == "OD")
	 		$div = 1;
	 	elseif($ARVModel->arv_mstr_dose == "BD")
	 		$div = 2;
	 	elseif($ARVModel->arv_mstr_dose == "2BD")
	 		$div = 4;
	 	if(!is_integer($Model->hiv_visit_q3))
			$lastvisitDate = Converter::toStore($Model->hiv_visit_q3);
		else
			$lastvisitDate = $Model->hiv_visit_q3;
		$days = round(($Model->hiv_visit_q6 / $div)) + ceil(($Model->hiv_visit_q6 / $div) * 10/100);

		$Values["lastvisitDate"] = $lastvisitDate;
		$Values["days"] = $days;
		return $Values;
	}
	else
		 $Values["lastvisitDate"] = strtotime(date('Y/m/d'));
	     $Values["days"] = 0;
		 return $Values;		
	}

	public function getARV($id, $data = "")
	{
		$Gmodel = \app\models\Arvmaster::find()->where(["arv_mstr_code" => $id])->one();
		if($Gmodel !== null) {
			if($data == "all")
				return $Gmodel;
			else
				return $Gmodel->arv_mstr_name;
		} else
			return "-";
	}
	
	public function getVisits()
	{
		return $this->q1Dum[$this->hiv_visit_q1];
	}	
	
	public function getIncvisit()
	{
		//->andWhere(["!=","inctype",'Motivational Counseling Incentive')
		
		$Gmodel = Allincvoucherreport::find()->where(["pid" => $this->hiv_visit_part_id])->andWhere(["!=","inctype",'Motivational Counseling Incentive'])->andWhere(["visitdate" => Converter::toStore($this->hiv_visit_q3)])->one();
		if($Gmodel !== null) 
          	return $Gmodel->inctype;
		 else
			return "-";
	}
	
	public function getScrdate()
	{		
	  $model = Screening::find()->where(["mem_scrn_part_id" => $this->hiv_visit_part_id])->orderBy(['record_date' => SORT_ASC])->one();
	   if ($model !== null && $model->record_date !== null) {
	   if(!is_integer($model->record_date))
		$date = Converter::toStore($model->record_date);
       else
		$date = $model->record_date;
	
	   return $date;	
		
	 }
	}
	
	public function getPreartlIncdate()
	{
		
		$Gmodel = Allincvoucherreport::find()->where(["pid" => $this->hiv_visit_part_id])->andWhere(["=","inctype",'Pre-ART Incentive'])->andWhere(["visitdate" => Converter::toStore($this->hiv_visit_q3)])->one();
		if($Gmodel !== null) 
          	return $Gmodel->visitdate;
		 else
			return "-";
	}
	
	public function getArtinitIncdate()
	{
		
		$Gmodel = Allincvoucherreport::find()->where(["pid" => $this->hiv_visit_part_id])->andWhere(["=","inctype",'ART Initiation Incentive'])->andWhere(["visitdate" => Converter::toStore($this->hiv_visit_q3)])->one();
		if($Gmodel !== null) 
          	return $Gmodel->visitdate;
		 else
			return "-";
	}
	
	public function getArtrefilIncdate()
	{
		
		$Gmodel = Allincvoucherreport::find()->where(["pid" => $this->hiv_visit_part_id])->andWhere(["=","inctype",'ART Refill Incentive'])->andWhere(["visitdate" => Converter::toStore($this->hiv_visit_q3)])->one();
		if($Gmodel !== null) 
          	return $Gmodel->visitdate;
		 else
			return "-";
	}
	
	public function getLastPillsMissed($pid = "", $date = "")
	{
		if($date == "")
			$Model = self::find()->where(["hiv_visit_part_id" => $pid, "hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC])->one();
		else
			$Model = self::find()->where(["hiv_visit_part_id" => $pid, "hiv_visit_q3" => $date, "hiv_visit_q4" => 1])->orderBy(["hiv_visit_id" => SORT_DESC])->one();
		if($Model !== null) {
	 	$ARVModel = $this->getARV($Model->hiv_visit_q6a, "all");
	 	$div = 1;
	 	if($ARVModel->arv_mstr_dose == "OD")
	 		$div = 1;
	 	elseif($ARVModel->arv_mstr_dose == "BD")
	 		$div = 2;
	 	elseif($ARVModel->arv_mstr_dose == "2BD")
	 		$div = 4;
	 	if(!is_integer($Model->hiv_visit_q3))
			$lastvisitDate = Converter::toStore($Model->hiv_visit_q3);
		else
			$lastvisitDate = $Model->hiv_visit_q3;
		$days = ($Model->hiv_visit_q6 / $div);

		$Values["lastvisitDate"] = $lastvisitDate;
		$Values["days"] = $days;
		return $Values;
	}
	else
		 $Values["lastvisitDate"] = strtotime(date('Y/m/d'));
	     $Values["days"] = 0;
		 return $Values;		
	}

	
	public function getIntervaldays($date)
	{		
	  $model = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id,"hiv_visit_q4" => 1])->andWhere(["=",'hiv_visit_q3',Converter::toStore($date)])->orderBy(['hiv_visit_q3' => SORT_DESC])->one();
	  
	  $dmodel = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id,"hiv_visit_q4" => 1])->andWhere(["<",'hiv_visit_q3',Converter::toStore($date)])->orderBy(['hiv_visit_q3' => SORT_DESC])->one();	  
	  
	  if ($model !== null && $dmodel !== null) {		   
	  
	   $date2 = date_create(Converter::toDisplay($model->hiv_visit_q3));				
	   $date1 = date_create(Converter::toDisplay($dmodel->hiv_visit_q3));
	   $diff = date_diff($date1, $date2);
	   $dtdiff = $diff->format("%a");
	   return $dtdiff;	
       
	  //$Hivvisitmodel = $this->getLastPills( $dmodel->hiv_visit_part_id, $dmodel->hiv_visit_q3);
	   //$lastvisitDate = $Hivvisitmodel['lastvisitDate'];					
	  // $days = $Hivvisitmodel['days'];
	 
	}
	}
	
	public function getMisseddays($date)
	{		
	  $model = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id,"hiv_visit_q4" => 1])->andWhere(["=",'hiv_visit_q3',Converter::toStore($date)])->orderBy(['hiv_visit_q3' => SORT_DESC])->one();
	  
	  $dmodel = parent::find()->where(["hiv_visit_part_id" => $this->hiv_visit_part_id,"hiv_visit_q4" => 1])->andWhere(["<",'hiv_visit_q3',Converter::toStore($date)])->orderBy(['hiv_visit_q3' => SORT_DESC])->one();	  
	  
	  if ($model !== null && $dmodel !== null) {		   
	  
	   $date2 = date_create(Converter::toDisplay($model->hiv_visit_q3));				
	   $date1 = date_create(Converter::toDisplay($dmodel->hiv_visit_q3));
	   $diff = date_diff($date1, $date2);
	   $dtdiff = $diff->format("%a");
	   //$dtdiff=$dtdiff; 
	   
	  // $Hivmodel = $this->getLastPillsMissed($dmodel->hiv_visit_part_id,Converter::toStore($dmodel->hiv_visit_q3));
	   $Hivmodel = $this->getLastPills($dmodel->hiv_visit_part_id,Converter::toStore($dmodel->hiv_visit_q3));
	   $lastvisitDate = $Hivmodel['lastvisitDate'];					
	   $days = $Hivmodel['days'];
	   
	   $misseddays=$dtdiff-$days;
	   
	   return $misseddays<=0 ? "":$misseddays;	   
	   
	}
	}
	
	
	
}
