<?php
class ReceivingItem extends AppModel {
	var $name = 'ReceivingItem';
	var $validate = array(
		'article_id' => array(
			'numeric' => array('rule' => array('numeric')),
		),
		'amount' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'ge0' => array('rule' => array('comparison', '>=', 0)),
		),
		'price' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'ge0' => array('rule' => array('comparison', '>=', 0)),
		),
		'price_buy' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'g0' => array('rule' => array('comparison', '>=', 0)),
		),
		'price_sell' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'g0' => array('rule' => array('comparison', '>=', 0)),
		),
		'discount' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'ge0' => array('rule' => array('comparison', '>=', 0)),
		),
	);

	var $belongsTo = array(
		'Receiving' => array(
			'className' => 'Receiving',
			'foreignKey' => 'receiving_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Article' => array(
			'className' => 'Article',
			'foreignKey' => 'article_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	function  beforeSave($options) {
		parent::beforeSave($options);

		// calculate marza
		$nc = $this->data['ReceivingItem']['price_buy'];
		$pc = $this->data['ReceivingItem']['price_sell'];

		$article = $this->Article->read(null, $this->data['ReceivingItem']['article_id']);
		$tax1 = $article['TaxGroup']['tax_1'] / 100;
		$tax2 = $article['TaxGroup']['tax_2'] / 100;

		$m_perc = ($pc / ((1 + $tax1 + $tax2) * $nc) - 1); // bujaaa *100
		$m_unit = $pc / (1 + $tax1 + $tax2) - $nc;
		$m_rec = $m_unit * $this->data['ReceivingItem']['amount'];

		$this->data['ReceivingItem']['marza_percent'] = $m_perc;
		$this->data['ReceivingItem']['marza_per_unit'] = $m_unit;
		$this->data['ReceivingItem']['marza_per_receiving'] = $m_rec;

		return true;
	}

	function afterSave($created) {
		parent::afterSave($created);
		if ($created) {

			$save_data = $this->data;

			// calculate SNC
			$article = $this->Article->read(null, $save_data['ReceivingItem']['article_id']);
			if ($article['Article']['amount'] > 0 && $save_data['ReceivingItem']['amount'] > 0) {
				$snc = ($article['Article']['amount'] * $article['Article']['price_buy'] + $save_data['ReceivingItem']['amount'] * $save_data['ReceivingItem']['price_buy']) / ($article['Article']['amount'] + $save_data['ReceivingItem']['amount']);
			} else {
				$snc = $save_data['ReceivingItem']['price_buy'];
			}

			// $this->Article->updateAll(
				// array(
					// 'amount' => "`amount`+{$save_data['ReceivingItem']['amount']}",
					// 'price_buy' => $snc,
					// 'price_sell' => $save_data['ReceivingItem']['price_sell'],
				// ),
				// array(
					// 'Article.id' => $save_data['ReceivingItem']['article_id']
				// )
			// );
		}
	}

}
