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

	var $belongsTo = array(
		'Customer' => array(
			'className' => 'Customer',
			'foreignKey' => 'customer_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'RadniNalog' => array(
			'className' => 'RadniNalog',
			'foreignKey' => 'radni_nalog_id',
		),
		'Automobil' => array(
			'className' => 'Automobil',
			'foreignKey' => 'automobil_id',
		),
		'Uredjaj' => array(
			'className' => 'Uredjaj',
			'foreignKey' => 'uredjaj_id',
		)
	);

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

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

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

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

		if (!empty($this->data['Offer']['id'])) {
			$this->OfferItem->deleteAll(array('offer_id' => $this->data['Offer']['id']), false, false);
		}

		// Generiraj broj ponude ako nije postavljen
		if (empty($this->data['Offer']['id']) && empty($this->data['Offer']['number'])) {
			$this->data['Offer']['number'] = $this->generateNumber();
		}

		return true;
	}

	/**
	 * Generira sljedeći broj ponude
	 * Format: broj (počinje od 1000)
	 */
	function generateNumber() {
		$lastOffer = $this->find('first', array(
			'fields' => array('number'),
			'order' => array('CAST(number AS UNSIGNED) DESC'),
			'recursive' => -1
		));
		
		if (!empty($lastOffer) && is_numeric($lastOffer['Offer']['number'])) {
			$nextNumber = (int)$lastOffer['Offer']['number'] + 1;
		} else {
			$nextNumber = 1000;
		}
		
		return (string)$nextNumber;
	}

}
