<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use common\models\Product;
use common\models\Waste;
use yii\web\HttpException;
use common\models\Log;
use common\components\Helper;

/**
 * ContactForm is the model behind the contact form.
 * @property \Yii\web\UploadedFile $file
 */
class WasteCreateForm extends Model{
	
	
	public $productIdentifier;
	public $id_product;
	public $comment;
	public $count;
	
	private $_product;
	
	public function rules(){
		return [
				[['count', 'id_product',  ], 'integer'],
				[['count',  ], 'required'],
				[['comment'], 'string', 'max' => 255],
				[['productIdentifier'], 'string', 'max' => 128],
				[['id_product']  ,'validateProduct','skipOnEmpty' => false, 'skipOnError' => false]
		];
	}
	
	public function validateProduct($attribute,$params){
		$this->_product = null;
		 
		
		if ( isset($this->productIdentifier)){
			$this->_product = Product::findOne($this->id_product);
		}
		 
		if ( $this->_product == null ){
			$this->addError('productIdentifier' , Yii::t("common/procurement", "Invalid product"));
		}
		 
	}
	
	public function attributeLabels( ) {
		return [
				'count' => "Mennyiség",
				'comment' => "Megjegyzés"
		];
	}
	
	public function save(){
		
		$connection = \Yii::$app->db;
		
		$transaction = $connection->beginTransaction();
		
		try {
			
			$model = new Waste();
			$model->id_product = $this->id_product;
			$model->count = $this->count;
			$model->stock_before = $this->_product->stock;
			$model->stock_after = $this->_product->stock - $this->count;
			$model->id_user = \Yii::$app->user->id;
			$model->comment = $this->comment;
			
			if ( !$model->save(false)){
				throw new HttpException("Nem sikerült menteni a selejtet");
			}
			
			$product = $this->_product;
			$product->stock = $product->stock - $this->count;
			
			if ( !$product->save(false) ){
				throw new HttpException("Nem sikerült menteni a terméket");
			}
			
			Log::log([
        			'type' =>Log::$TYPE_WASTE,
        			'message' => "Selejt létrehozva. Termék:".$product->name ." Mennyiség: ". $this->count ,
					'id_product' => $product->id_product
        	]);
		
			$transaction->commit();
			
			Helper::flash('success', Yii::t('backend/procurement', 'Selejtezés mentve'));
			
		} catch (\Exception $e) {
			$transaction->rollback();
			throw $e;
		}
	}
	
}