<?php

namespace common\models;

use Yii;
use common\components\AccountAwareBehavior;
use common\components\UserAwareBehavior;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "collection".
 *
 * @property integer $id_collection
 * @property integer $id_user
 * @property integer $created_by
 * @property integer $id_account
 * @property integer $money
 * @property string $start
 * @property string $end
 * @property integer $type
 * @property string $created_at
 * @property string $updated_at
 */
class CollectionCreate extends \common\models\Collection
{
    
	public $lastCollection;
	public $accounts;
	public $accountMap;
	public $account;
	public $totals;
	public $userCartTotal;
	
	public $timestampEnd;
	public $timestampStart;
	
	
	public function rules(){
		return [
			['end','required'],
			/**enable seconds*/
			[[ 'end' , ], 'date'  ,'format' => 'yyyy-MM-dd HH:mm:ss' , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss' ,'timeZone' => 'UTC' ],
			/*enable only minutes*/
// 			[[ 'end' , ], 'date'  ,'format' => 'yyyy-MM-dd HH:mm' , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm' ,'timeZone' => 'UTC' ],
			[[ 'end' ], 'validateEndDate' ]
		];
	}
	
	public function validateEndDate($attribute,$params){
		if ( isset($this->lastCollection)){
			if ( strtotime( $this->lastCollection->end ) >= strtotime( $this->timestampEnd ) ){
				$this->addError($attribute,Yii::t('frontend/collection' ,'End date is invalid') );
			}
		}
	}

	public function beforeSave($insert){
		if (parent::beforeSave($insert)) {
			$this->id_user = Yii::$app->user->id;
			$this->created_by = Yii::$app->user->id;
			$paidAt = Transfer::mkPaidAtTotals($this->timestampStart, $this->timestampEnd, $this->user->id, null, $this->account->id_account,  $this->accounts, $this->accountMap);
			$this->money = $paidAt['total'];
			return true;
		} else {
			return false;
		}
	}
	
	
}
