<?php
class Receiving extends AppModel {
	var $name = 'Receiving';
	var $order = array('Receiving.date DESC');
	var $validate = array(
		'supplier_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				'allowEmpty' => true,
			),
		),
	);

	var $belongsTo = array(
		'Supplier' => array(
			'className' => 'Supplier',
			'foreignKey' => 'supplier_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	var $hasMany = array(
		'ReceivingItem' => array(
			'className' => 'ReceivingItem',
			'foreignKey' => 'receiving_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	function cancelReceiving($id = null) {
		$this->contain('ReceivingItem.Article');
		$this->read(null, $id);
		
		if ($this->data['Receiving']['canceled']) {
			return false;
		} else {
			foreach($this->data['ReceivingItem'] as $i) {

//				if ($i['Article']['amount'] == $i['amount']) {
//					$snc = $i['Article']['price_buy'];
//				} else {
//					$snc = ($i['Article']['amount'] * $i['Article']['price_buy'] - $i['amount'] * $i['price_buy']) / ($i['Article']['amount'] - $i['amount']);
//				}

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

			unset($this->data['ReceivingItem']);
			$this->data['Receiving']['canceled'] = true;
			$this->data['Receiving']['canceled_by'] = $this->Session->read('Auth.User.username');
			$this->save();

			return true;
		}
	}
function  beforeSave($options) {
		parent::beforeSave($options);

		if (!empty($this->data['Receiving']['id'])) {
			$this->ReceivingItem->deleteAll(array('receiving_id' => $this->data['Receiving']['id']), false, false);
		}

	

		return true;
	}

}
