<?php
/**
 * OfferItem Model
 * Stavke ponude su ARTIKLI/USLUGE
 * Automobil/Uređaj je dodatna informacija o ponudi (ne stavka)
 */
class OfferItem extends AppModel {
	var $name = 'OfferItem';
	
	var $validate = array(
		'article_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				'message' => 'Artikl je obavezan',
				'allowEmpty' => false
			),
		),
		'amount' => array(
			'numeric' => array('rule' => array('numeric'), 'allowEmpty' => true),
		),
		'price' => array(
			'numeric' => array('rule' => array('numeric'), 'allowEmpty' => true),
		),
		'discount' => array(
			'numeric' => array('rule' => array('numeric'), 'allowEmpty' => true),
		),
	);

	var $belongsTo = array(
		'Offer' => array(
			'className' => 'Offer',
			'foreignKey' => 'offer_id'
		),
		'Article' => array(
			'className' => 'Article',
			'foreignKey' => 'article_id'
		)
	);

	function beforeSave($options = array()) {
		parent::beforeSave($options);
		
		// Dohvati price_buy iz artikla
		if (!empty($this->data['OfferItem']['article_id'])) {
			$article = $this->Article->read(null, $this->data['OfferItem']['article_id']);
			if ($article) {
				$this->data['OfferItem']['price_buy'] = $article['Article']['price_buy'];
			}
		}
		
		// Izračunaj ukupnu cijenu: amount * price_sell * (1 - discount/100)
		if (isset($this->data['OfferItem']['amount']) && isset($this->data['OfferItem']['price_sell'])) {
			$amount = floatval($this->data['OfferItem']['amount']);
			$price_sell = floatval($this->data['OfferItem']['price_sell']);
			$discount = isset($this->data['OfferItem']['discount']) ? floatval($this->data['OfferItem']['discount']) : 0;
			
			$this->data['OfferItem']['price'] = $amount * $price_sell * (1 - $discount / 100);
		}
		
		return true;
	}
}
