<?php
class ReceivingOrderItem extends AppModel {
	var $name = 'ReceivingOrderItem';
	var $validate = array(
		'article_id' => array(
			'numeric' => array('rule' => array('numeric')),
		),
		'amount' => array(
			'numeric' => array('rule' => array('numeric')),
		//	'ge0' => array('rule' => array('comparison', '>=', 0)),
		),
		
	);

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

	function  beforeSave($options) {
		parent::beforeSave($options);
		$article = $this->Article->read(null, $this->data['ReceivingOrderItem']['article_id']);
		return true;
	}

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

			$save_data = $this->data;

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

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

}
