<?php
namespace backend\models;



use common\models\Procurement;
use common\models\Product;
use yii\helpers\VarDumper;
use common\models\Log;


class ProcurementUpdate extends Procurement{

	private $oldCount;
	
	public function rules( ) {
		return [
				[ ['count', 'purchase_price' ], 'integer'],	
				[ ['count', 'purchase_price' ], 'required'],	
		]; 
	}

	public function beforeSave($insert){
		if ( !$insert ){
			$changed = $this->getOldAttribute('count');
// 				VarDumper::dump($changed);
// 			VarDumper::dump($this->getDirtyAttributes(['count']));
			$this->oldCount = $this->getOldAttribute('count'); 
			
		}
		return true;
	}
	
	public function afterSave($insert, $changedAttributes){
		$product = Product::findOne($this->id_product);
		
		$product->stock = $product->stock - $this->oldCount + $this->count;
		
		$product->save(false);
		
		Log::log([
					'id_product' => $this->product->id_product,
        			'type' =>Log::$TYPE_PROCUREMENT_UPDATE,
        			'message' => "Beszerzés(#".$this->id_procurement.") módosítva. Beszerzett mennyiség: " . $this->oldCount . " > " .$this->count,
        	]);
	}
	
	
}