<?php
class ReceivingOrder extends AppModel {
	var $name = 'ReceivingOrder';
	var $order = array('ReceivingOrder.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(
		'ReceivingOrderItem' => array(
			'className' => 'ReceivingOrderItem',
			'foreignKey' => 'receiving_order_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	function cancelReceivingOrder($id = null) {
		$this->contain('ReceivingOrderItem.Article');
		$this->read(null, $id);
		
		if ($this->data['ReceivingOrder']['canceled']) {
			return false;
		} else {
			foreach($this->data['ReceivingOrderItem'] 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->ReceivingOrderItem->Article->updateAll(
					array(
						'amount' => "`amount`-{$i['amount']}",
//						'price_buy' => $snc,
					),
					array('Article.id' => $i['article_id'])
				);*/
			}

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

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

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

	

		return true;
	}

}
