<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use app\base\Converter;

/**
 * This is the model class for table "{{%attandance}}".
 *
 * @property integer $id
 * @property string $sid
 * @property string $location
 * @property string $pid
 * @property string $participant_id
 * @property string $interviewer
 * @property string $visit
 * @property string $visit_date
 * @property integer $visit_in
 * @property string $out_interviewer
 * @property integer $visit_out
 * @property string $status
 * @property integer $create_time
 * @property integer $create_user
 * @property integer $update_time
 * @property integer $update_user
 */
class Attandance extends \yii\db\ActiveRecord
{
	public $servicechk;
	/**
	 * @inheritdoc
	 */
    public static function tableName()
	{
		return '{{%attandance}}';
	}

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

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['sid', 'location', 'pid', 'interviewer'], 'required', 'message' => 'Cannot be blank.'],
			[['servicechk'], 'safe'],
			[['interviewer','out_interviewer', 'visit', 'visit_date', 'visit_in', 'visit_out', 'create_time', 'create_user', 'update_time', 'update_user'], 'integer', 'message' => 'Must be an integer'],
			[['remarks'], 'required', 'when' => function ($model) {
				return ($model->servicechk == '0');
			}, 'whenClient' => "function (attribute, value) {
				return ($('#attandance-servicechk').val() == '0');
			}"],
			
			[['out_interviewer'], 'required', 'message' => 'Cannot be blank.', 'when' => function ($model) {
				return ($model->out_interviewer == '' && $model->visit_out !==null);
			}, 'whenClient' => "function (attribute, value) {
				return ($('#attandance-out_interviewer').val() == '' && $('#attandance-visit_out').val() !==null);
			}"],
			
			[['visit'], 'required', 'message' => 'Cannot be blank.', 'on' => 'visitentry'],
			[['sid', 'location', 'pid', 'participant_id'], 'string', 'max' => 20],
			[['interviewer', 'out_interviewer'], 'string', 'max' => 3],
			[['remarks'], 'string', 'max' => 250],
			[['status'], 'string', 'max' => 1],
			[['visit_date','record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],
			[['visit'], 'dataentryValidate', 'on' => 'visitentry'],
		];
	}

	public function dataentryValidate($attribute, $params) {
		if($this->visit != "") :
			$Master = Visitschedule::find()->where(["participant_id" => $this->pid, "visit_code" => $this->visit])->one();
			if($Master !== null) {
				if(!is_integer($Master->window_start))
					$window_start = Converter::toStore($Master->window_start);
				if(!is_integer($Master->window_end))
					$window_end = Converter::toStore($Master->window_end);
				$AMaster = parent::find()->where(["sid" => $this->sid, "location" => $this->location, "pid" => $this->pid, "visit_date" => $this->visit_date])->andWhere(["BETWEEN", "visit_date", $window_start, $window_end])->one();
				if($AMaster === null) {
					$this->addError($attribute, "This Visits are Allowed from $Master->window_start to $Master->window_end");
				}
			} else {
				$SModel = Screening::find()->where(["mem_scrn_part_id" => $this->pid])->one();
				if(($SModel === null && $this->visit != '1') || ($SModel !== null && $this->visit != '1')){
					$this->addError($attribute, "This Visit not allowed");
				}
			}
		endif;
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'id' => Yii::t('app', 'ID'),
			'sid' => Yii::t('app', 'Survey'),
			'location' => Yii::t('app', 'Location'),
			'pid' => Yii::t('app', 'ICC Client ID'),
			'participant_id' => Yii::t('app', 'Participant ID'),
			'interviewer' => Yii::t('app', 'Site Coordinator'),
			'visit' => Yii::t('app', 'Visit'),
			'visit_date' => Yii::t('app', 'Visit Date'),
			'visit_in' => Yii::t('app', 'Visit In'),
			'out_interviewer' => Yii::t('app', 'Site Coordinator'),
			'remarks' => Yii::t('app', 'Remarks'),
			'visit_out' => Yii::t('app', 'Visit Out'),
			'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)
	{
		if (parent::beforeSave($insert)) {
			// $Vmodel = Attandance::find()->where(['pid' => $this->pid])->andWhere(['>', 'visit', 0])->count();
			$Vmodel = Attandance::find()->where(['pid' => $this->pid])->count();
			if ($this->isNewRecord) {
				if (empty($Vmodel))
	        		$this->visit = 2;
	        	else
	        		$this->visit = ($Vmodel+1);

	        	$this->participant_id = $this->pid;
	        	$this->visit_in = date('U');
			} else {
				$this->participant_id = $this->pid;
				if($this->scenario !== "visitentry")
	        		$this->visit_out = date('U');
			}
			return true;
		}
	}

    public function getSurvey()
    {
        return $this->hasOne(\app\models\Surveymaster::className(), ['sur_code' => 'sid']);
    }

    public function getLocations()
    {
        return $this->hasOne(\app\models\Locationmaster::className(), ['loc_code' => 'location']);
    }

    public function getVisits()
    {
        return $this->hasOne(Visitmaster::className(), ['visit_code' => 'visit']);
    }

    public function getRegistration()
    {
        return $this->hasOne(\app\models\Registration::className(), ['corfrm_pid' => 'participant_id']);
    }

    public function getCd4()
    {
    	$date = strtotime(date("Y/m/d"));
    	$tname = \app\models\Cd4::tableName();
        return $this->hasOne(\app\models\Cd4::className(), ['cd4_test_part_id' => 'participant_id'])->andOnCondition(["<=", "$tname.record_date", $date])->orderBy(["$tname.record_date" => SORT_DESC]);
    }

	public function getPreART($pid, $dt, $type = "earned")
	{
		if($type == "earned")
			$Gmodel = Preartincenmaster::find()->where(["preart_inc_part_id" => $pid])->andWhere(["record_date" => $dt])->sum("preart_inc_q2");
		elseif($type == "paid")
			$Gmodel = Preartincenmaster::find()->where(["preart_inc_part_id" => $pid])->andWhere(["preart_inc_q3" => $dt])->sum("preart_inc_q2");
		elseif($type == "allearned")
			$Gmodel = Preartincenmaster::find()->where(["preart_inc_part_id" => $pid])->sum("preart_inc_q2");
		elseif($type == "allpaid")
			$Gmodel = Preartincenmaster::find()->where(["preart_inc_part_id" => $pid])->andWhere(["preart_inc_q1" => 1])->sum("preart_inc_q2");
		if($Gmodel !== null) {
			return $Gmodel;
		}
		else
			return "-";
	}

	public function getART($pid, $dt, $type = "earned")
	{
		if($type == "earned")
			$Gmodel = Artincenmaster::find()->where(["art_inc_part_id" => $pid])->andWhere(["record_date" => $dt])->sum("art_inc_q2");
		elseif($type == "paid")
			$Gmodel = Artincenmaster::find()->where(["art_inc_part_id" => $pid])->andWhere(["art_inc_q3" => $dt])->sum("art_inc_q2");
		elseif($type == "allearned")
			$Gmodel = Artincenmaster::find()->where(["art_inc_part_id" => $pid])->sum("art_inc_q2");
		elseif($type == "allpaid")
			$Gmodel = Artincenmaster::find()->where(["art_inc_part_id" => $pid])->andWhere(["art_inc_q1" => 1])->sum("art_inc_q2");
		if($Gmodel !== null) {
			return $Gmodel;
		}
		else
			return "-";
	}

	public function getMotInc($pid, $dt, $type = "earned")
	{
		if($type == "earned")
			$Gmodel = Motincenmaster::find()->where(["mot_inc_part_id" => $pid])->andWhere(["record_date" => $dt])->sum("mot_inc_q2");
		elseif($type == "paid")
			$Gmodel = Motincenmaster::find()->where(["mot_inc_part_id" => $pid])->andWhere(["mot_inc_q3" => $dt])->sum("mot_inc_q2");
		elseif($type == "allearned")
			$Gmodel = Motincenmaster::find()->where(["mot_inc_part_id" => $pid])->sum("mot_inc_q2");
		elseif($type == "allpaid")
			$Gmodel = Motincenmaster::find()->where(["mot_inc_part_id" => $pid])->andWhere(["mot_inc_q1" => 1])->sum("mot_inc_q2");
		if($Gmodel !== null) {
			return $Gmodel;
		}
		else
			return "-";
	}

	public function getARTInc($pid, $dt, $type = "earned")
	{
		if($type == "earned")
			$Gmodel = Artinitiationincentmaster::find()->where(["art_init_inc_part_id" => $pid])->andWhere(["record_date" => $dt])->sum("art_init_inc_q2");
		elseif($type == "paid")
			$Gmodel = Artinitiationincentmaster::find()->where(["art_init_inc_part_id" => $pid])->andWhere(["art_init_inc_q3" => $dt])->sum("art_init_inc_q2");
		elseif($type == "allearned")
			$Gmodel = Artinitiationincentmaster::find()->where(["art_init_inc_part_id" => $pid])->sum("art_init_inc_q2");
		elseif($type == "allpaid")
			$Gmodel = Artinitiationincentmaster::find()->where(["art_init_inc_part_id" => $pid])->andWhere(["art_init_inc_q1" => 1])->sum("art_init_inc_q2");
		if($Gmodel !== null) {
			return $Gmodel;
		}
		else
			return "-";
	}
	
	public function getScreening()
    {
        return $this->hasOne(\app\models\Screening::className(), ['mem_scrn_part_id' => 'participant_id']);
    }
	
	/*
	public function afterSave($insert, $changedAttributes) {
	    parent::afterSave($insert, $changedAttributes);
	    if($this->record_date !== Null && $this->scenario === "visitentry") {	    	
		    $visitdate = $this->record_date;			
			$VSModels = Visitschedule::find()->where(['participant_id' => $this->pid,'visit_code'=> $this->visit])->andWhere(['visit_date' => Null ])->one();
			if(!empty($VSModels)) {						
					$VSModels->visit_date = $visitdate;	
					$VSModels->actual_date = Converter::toStore($VSModels->actual_date);
					$VSModels->window_start = Converter::toStore($VSModels->window_start);
					$VSModels->window_end = Converter::toStore($VSModels->window_end);
					$VSModels->date_of_screening = Converter::toStore($VSModels->date_of_screening);
                    $VSModels->save(false);			
     			}
	    }
	}
	*/
	
	public function afterSave($insert, $changedAttributes) {
	    parent::afterSave($insert, $changedAttributes);
	    if($this->record_date !== Null && $this->scenario === "visitentry") {	    	
		    $visitdate = $this->record_date;			
			$VSModels = Visitschedule::find()->where(['participant_id' => $this->pid,'visit_code'=> $this->visit])->andWhere(['visit_date' => Null ])->one();
			if(!empty($VSModels)) {						
					$VSModels->visit_date = Converter::toDisplay($visitdate);	
					$VSModels->actual_date = Converter::toDisplay($VSModels->actual_date);
					$VSModels->window_start = Converter::toDisplay($VSModels->window_start);
					$VSModels->window_end = Converter::toDisplay($VSModels->window_end);
					$VSModels->date_of_screening = Converter::toDisplay($VSModels->date_of_screening);
                    $VSModels->save(false);			
     			}
	    }
	}
	
	public function getCohortVisits($id)
	{
		$Gmodel = \app\models\Visitmaster::find()->where(['NOT', ['visit_interval' => null]])->andWhere(["status" => 1])->andWhere(["visit_code" => $id])->one();
		if($Gmodel !== null) {			
				return $Gmodel->visit_name;
		} else
			return "-";
	}	
}
