<?php

namespace app\models;

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

/**
 * This is the model class for table "{{%contactclients}}".
 *
 * @property integer $contact_client_id
 * @property integer $id
 * @property string $contact_client_survey
 * @property string $contact_client_part_id
 * @property string $contact_client_q1
 * @property integer $contact_client_q2
 * @property string $contact_client_q3
 * @property string $contact_client_q4
 * @property integer $contact_client_q5
 * @property string $status
 * @property integer $create_time
 * @property integer $create_user
 * @property integer $update_time
 * @property integer $update_user
 * @property integer $record_date
 */
class Appointment extends \yii\db\ActiveRecord
{
	/**
	 * @inheritdoc
	 */
	public $dosage = [1 => "1st Dose", 2 => "2nd Dose", 3 => "Booster"];	
	public $sex = ["Male" => "Male", "Female" => "Female", "TG" => "TG"];
    public $ap_status = ["Open" => "Open", "Close" => "Close"];		
	
	public $dosedum = [1 => "1", 2 => "2", 3 => "3"];	
	
    public static function tableName()
	{
		return 'appointment';
	}

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

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [          
						
			[['block','district','staff_code','staff_name','beneficiary_name','mobile_number','gender','year_of_birth','vaccination_appointment_date','dose','appointment_id'], 'required', 'message' => 'Cannot be blank.'],
									
			[['referred_source','appointment_status','vaccination_date' ], 'safe'],			 
					 			 		   				
			[['create_time', 'create_user', 'update_time', 'update_user', 'record_date'], 'integer'],
			
			[['mobile_number','year_of_birth'], 'integer', 'message' => 'Must be an integer'],
			
			[['mobile_number'], 'string', 'max' => 10],
			[['mobile_number'], 'string', 'length' => 10, 'notEqual' => 'Must be {length} digits'],

            [['year_of_birth'], 'string', 'max' =>4],
            [['year_of_birth'], 'string', 'length' => 4, 'notEqual' => 'Must be {length} digits'],
           	
            [['year_of_birth'], 'number','min' => 1923, 'tooSmall' => 'Minimum value is {min}', 'max' => 2004, 'tooBig' => 'Maximum value is {max}'],		
          			
			[['beneficiary_name'], 'nameValidates'],
            
			[['mobile_number'], 'mobnoValidates'],
			[['mobile_number'], 'mobnocountValidate'],
			
            [['staff_code'], 'staffValidates'],
              
            [['staff_code'], 'staffcodeValidates'],	
            [['staff_name'], 'staffnameValidates'],				
         	                         			
			[['status'], 'string', 'max' => 1],
			[['record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],	
			[['appointment_status'], 'default', 'value' =>'Open'],	
           			
		];
	}
	
	
	public function nameValidates() {		
	  //if(!preg_match('/^[A-Za-z]{2}[0-9]*$/', $this->corfrm_pid) || (substr($this->corfrm_pid, 0, 2) !== $this->corfrm_loc)) {
		if(preg_match('[\s+$]', (substr($this->beneficiary_name, 0, 2))) || preg_match('[\s+$]', (substr($this->beneficiary_name, 0, 1)))) {
			$this->addError('beneficiary_name', 'Space should not be between First and Second Characters');
		}
	}
	
	public function mobnoValidates() {
		if($this->mobile_number != "") :		
		if(!preg_match('/^[0-9]*$/', $this->mobile_number)) {
			$this->addError('mobile_number', 'Invalid Mobile Number');
		}
		endif;
	}
	
	public function staffValidates($attribute, $params) {
	  
	  if($this->staff_name != "" && $this->staff_code != "" ) : 		
		$staffMaster = Staff::find()->where(["status" => 1])->andWhere(["staff_name" => $this->staff_name])->andWhere(["staff_code" => $this->staff_code])->one();
		if($staffMaster == null)
		{
			$this->addError($attribute, 'Staff Code Mismatch with this Chosen Staff Name');
		}
	  endif;	
	}	
	
	public function staffcodeValidates($attribute, $params) {
	  
	  if($this->staff_code != "" ) : 				
		$CMaster = Staff::find()->where(["status" => 1])->andWhere(["staff_code" => $this->staff_code])->andWhere(["block" => $this->block])->one();
		if($CMaster == null)
		{
			$this->addError($attribute, 'Wrong staff Code Chosen. This Staff Code is not in the Block Master');
		}
	  endif;	
	}	
	
	public function staffnameValidates($attribute, $params) {
	  
	  if($this->staff_name != "" ) : 				
		$SMaster = Staff::find()->where(["status" => 1])->andWhere(["staff_name" => $this->staff_name])->andWhere(["block" => $this->block])->one();
		if($SMaster == null)
		{
			$this->addError($attribute, 'Wrong Staff Name Chosen. This Staff Name is not in the Block Master');
		}
	  endif;	
	}	
    
  
	
	public function mobnocountValidate($attribute, $params) {
        if($this->mobile_number != "") :
			$Model= parent::find()->where(["mobile_number" => $this->mobile_number])->andWhere(["dose" => $this->dose])->one();
			if($Model !== null) {				
					$Mnocount = parent::find()->where(["mobile_number" => $this->mobile_number, "dose" => $this->dose])->count();
					if($Mnocount > 3) {
						$this->addError($attribute, "Same Mobile Number allow maximum 4 times only");
		    		}	    		
    		}
        endif;
	}
	
	
	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
          	
			'district' => Yii::t('app', 'District'),
			'block' => Yii::t('app', 'Block'),
			'staff_name' => Yii::t('app', 'Operator / Staff Name'),
			'staff_code' => Yii::t('app', 'Operator / Staff Code'),
			'dose' => Yii::t('app', 'Dose'),
			'beneficiary_name' => Yii::t('app', 'Beneficiary Name'),
			'mobile_number' => Yii::t('app', 'Mobile Number'),
			'gender' => Yii::t('app', 'Gender'),
			'year_of_birth' => Yii::t('app', 'Year of Birth'),
			'vaccination_appointment_date' => Yii::t('app', 'Vaccination Appointment Date'),		
			'referred_source' => Yii::t('app', 'Referred Source'),
			'appointment_id' => Yii::t('app', 'Appointment ID'),	
			'vaccination_date' => Yii::t('app', 'Date of Vaccination'),
			'appointment_status' => Yii::t('app', 'Appointment Status'),
			
			'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'),
			'record_date' => Yii::t('app', 'Record Date'),			
		];
	}	
	
	public function getDose()
	{
		return $this->dosedum[$this->dose];
		
	}
	
	public function getApstatus()
	{
		return $this->ap_status[$this->appointment_status];
		
	}
	
    public function beforeSave($insert)
	{
		if (parent::beforeSave($insert)) {	
			 
			 if($this->vaccination_appointment_date != "")
				$this->vaccination_appointment_date = Converter::toStore($this->vaccination_appointment_date);
			if($this->vaccination_date != "")
				$this->vaccination_date = Converter::toStore($this->vaccination_date);
			
	        return true;
	    } else {
	        return false;
	    }
	}
	
	public function afterFind()
	{
		parent::afterFind();
		if(Yii::$app->controller->action->id != "view") {			
			if($this->vaccination_appointment_date != "")
				$this->vaccination_appointment_date = Converter::toDisplay($this->vaccination_appointment_date);
			if($this->vaccination_date != "")
				$this->vaccination_date = Converter::toDisplay($this->vaccination_date);
          	
		}
	}
	
	
}
