<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%voucherref}}".
 *
 * @property string $vchr_ref_sur
 * @property string $vchr_ref_loc
 * @property string $vchr_ref_type
 * @property integer $vchr_ref_code
 * @property integer $record_date
 * @property integer $update_time
 */
class Voucherref extends \yii\db\ActiveRecord
{
	const REIMBURSEMENT = 'RIMB';
	const INCENTIVE = 'INC';

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

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

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['vchr_ref_sur', 'vchr_ref_loc', 'vchr_ref_type', 'vchr_ref_code'], 'required'],
			[['vchr_ref_code', 'record_date', 'update_time'], 'integer'],
			[['vchr_ref_sur', 'vchr_ref_loc', 'vchr_ref_type'], 'string', 'max' => 11],
			[['vchr_ref_sur', 'vchr_ref_loc', 'vchr_ref_type'], 'unique', 'targetAttribute' => ['vchr_ref_sur', 'vchr_ref_loc', 'vchr_ref_type'], 'message' => 'The combination of Survey, Location and Type has already been taken.'],
			[['record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'vchr_ref_sur' => Yii::t('app', 'Survey'),
			'vchr_ref_loc' => Yii::t('app', 'Location'),
			'vchr_ref_type' => Yii::t('app', 'Type'),
			'vchr_ref_code' => Yii::t('app', 'Last Voucher Number'),
			'record_date' => Yii::t('app', 'Record Date'),
			'update_time' => Yii::t('app', 'Update Date'),
		];
	}

	public static function generateVoucherno($sur, $pid, $type)
	{
		$loc = substr($pid, 0, 2);
		if ($loc != "") {
			$Refmodel = self::find()->where(['vchr_ref_sur' => $sur])->andWhere(['vchr_ref_loc' => $loc])->andWhere(['vchr_ref_type' => $type])->one();
			if ($Refmodel === null)
				$Refmodel = new self;
			$ref_code = $Refmodel->vchr_ref_code;
			$refid = ($ref_code+1);
		} else {
			$Refmodel = new self;
			$refid = 1;
		}

		if($loc == "") {
			$code = $type.'-';
		} else {
			$code = $loc.'-'.$type.'-';
		}

		$vno = str_pad($refid, 5, 0, STR_PAD_LEFT);
		$Refmodel->vchr_ref_sur = $sur;
		$Refmodel->vchr_ref_loc = $loc;
		$Refmodel->vchr_ref_type = $type;
		$Refmodel->vchr_ref_code = $vno;
		return $Refmodel;
    }
}
