<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use app\models\Artcentre;

/**
 * This is the model class for table "{{%labref}}".
 *
 * @property integer $boxid_ref_id
 * @property string $boxid_state
 * @property string $boxid_ref_code
 */
class Boxidref extends \yii\db\ActiveRecord
{
	/**
	 * @inheritdoc
	 */
    public static function tableName()
	{
		return 'boxidref';
	}
	
	public function behaviors()
	{
		return [
			[
				'class' => TimestampBehavior::className(),
				'createdAtAttribute' => null,
				'updatedAtAttribute' => 'update_time',
				'value' => date('U'),
			]
		];
	}

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['boxid_ref_district','boxid_ref_artcname','boxid_ref_artccode', 'boxid_ref_month','boxid_ref_week','boxid_ref_code'], 'required', 'message' => 'Cannot be blank.'],
			[['boxid_ref_month'], 'string', 'max' => 3],			
			[['boxid_ref_week', 'boxid_ref_code'], 'integer'],
			[['record_date', 'update_time'], 'integer'],
			[['record_date'], 'default', 'value' => strtotime(date('Y/m/d'))],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'boxid_ref_id' => Yii::t('app', 'Ref ID'),
			'boxid_ref_artcname' => Yii::t('app', 'ARTC Name'),
			'boxid_ref_artccode' => Yii::t('app', 'ARTC Code'),
			'boxid_ref_district' => Yii::t('app', 'District'),
			'boxid_ref_code' => Yii::t('app', 'Ref Code'),
			'record_date' => Yii::t('app', 'Record Date'),
			'update_time' => Yii::t('app', 'Update Time'),
		];
	}
	
	public static function generateBoxno($artc,$month,$week)
	{		
	    $sdistrict=Yii::$app->user->identity->district;
        $artcname=Artcentre::find()->where(["artccode" => $artc])->one()->artcname;
		
		if ($artc != "") {
			$Refmodel = self::find()->where(["boxid_ref_artccode" => $artc, "boxid_ref_month" => $month, "boxid_ref_week" => $week])->one();
			if ($Refmodel === null)
				$Refmodel = new self;
			if ($Refmodel->boxid_ref_artccode == null){
			 $ref_code = 0;
			}
		    else {
			 $ref_code=$Refmodel->boxid_ref_code;
			} 
			$refid = ($ref_code+1);
		} else { 
			$Refmodel = new self;
			$refid = 1;
		}

		$Refmodel->boxid_ref_district = $sdistrict;
		$Refmodel->boxid_ref_artcname = $artcname;
		$Refmodel->boxid_ref_artccode = $artc;
		$Refmodel->	boxid_ref_month = $month;
		$Refmodel->boxid_ref_week =$week;
		$Refmodel->boxid_ref_code =$refid;	
        $Refmodel->update_user =Yii::$app->user->identity->id;		
		return $Refmodel;
    }
}
