<?php

class OffersController extends AppController {

	var $name = 'Offers';
	var $paginate = array(
		'limit' => 10,
		'order' => array('Offer.created' => 'desc')
	);
    var $components = array(
	    'Filter' => array(
	        'index' => array(
	            'customer_id' => array(
        	        'form_options' => array('label' => 'Customer', 'options' => 'Customers'),
	            	'filter_options' => array(),
	            ),
				'canceled' => array(
        	        'form_options' => array('label' => 'Status', 'options' => 'Filter.Offer_cancel'),
	            	'filter_options' => array(),
				),
//				'date' => array(
//        	        'form_options' => array('label' => 'Date', 'type' => 'date'),
//	            	'filter_options' => array('fields' => array('DATE(date)')),
//				)
	        )
        ),
	);

	function  beforeFilter() {
		parent::beforeFilter();
		$this->Auth->mapActions(array('cancel' => 'delete', 'send_email' => 'read', 'generate_offer_pdf' => 'read', 'convert_to_radni_nalog' => 'update'));
	}

	function index() {
		$this->Offer->recursive = 0;
		$items = $this->paginate();
		
		// Dohvati stavke za svaku ponudu
		foreach ($items as $key => $item) {
			$stavke = $this->Offer->OfferItem->find('all', array(
				'conditions' => array('OfferItem.offer_id' => $item['Offer']['id']),
				'contain' => array('Article.TaxGroup')
			));
			$items[$key]['OfferItem'] = array();
			foreach ($stavke as $s) {
				$items[$key]['OfferItem'][] = array_merge($s['OfferItem'], array('Article' => $s['Article']));
			}
		}
		
		$this->set('items', $items);
	}

	function view($id = null) {
		// Dohvati ponudu sa stavkama (artikli) i predmetom (automobil/uređaj)
		$this->Offer->contain('Customer', 'RadniNalog', 'Automobil', 'Uredjaj', 'OfferItem.Article');
		if (!$id  || !($item = $this->Offer->read(null, $id))) {
			$this->Session->setFlash(__('Invalid Offer', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('item', $item);
	}

	function add() {
		if (!empty($this->data)) {
			// Kupac je obavezan
			if (empty($this->data['Offer']['customer_id'])) {
				$this->Session->setFlash(__('Kupac je obavezan. Molimo odaberite kupca.', true), 'default', array('class' => 'error'));
				$this->_setFormData();
				return;
			}
			// Postavi datum ako nije postavljen (nova ponuda)
			if (empty($this->data['Offer']['date'])) {
				$this->data['Offer']['date'] = date('Y-m-d H:i:s');
			}
			
			// Konvertiraj datume iz dd.mm.yyyy. u yyyy-mm-dd format
			if (!empty($this->data['Offer']['document_date'])) {
				$parts = explode('.', $this->data['Offer']['document_date']);
				if (count($parts) >= 3) {
					$this->data['Offer']['document_date'] = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
				}
			}
			if (!empty($this->data['Offer']['vrijedi_do'])) {
				$parts = explode('.', $this->data['Offer']['vrijedi_do']);
				if (count($parts) >= 3) {
					$this->data['Offer']['vrijedi_do'] = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
				}
			}
			
			// Filtriraj stavke - samo artikli
			$price = 0;
			$validItems = array();
			if (!empty($this->data['OfferItem'])) {
				foreach($this->data['OfferItem'] as $ri) {
					if (!empty($ri['article_id'])) {
						$ri['price'] = $ri['amount'] * $ri['price_sell'] * (1 - ($ri['discount'] / 100));
						$price += $ri['price'];
						$article = $this->Offer->OfferItem->Article->read(null, $ri['article_id']);
						$ri['price_buy'] = $article['Article']['price_buy'];
						$validItems[] = $ri;
					}
				}
			}
			$this->data['OfferItem'] = $validItems;
			$this->data['Offer']['price'] = $price;

			$this->Offer->create();
			if ($this->Offer->saveAll($this->data)) {
				$this->Session->setFlash(__('Ponuda je spremljena', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Ponuda nije mogla biti spremljena. Pokušajte ponovo.', true), 'default', array('class' => 'error'));
			}
		}
		
		// Postavi sljedeći broj ponude i datum ako je nova ponuda
		if (empty($this->data)) {
			$this->data['Offer']['number'] = $this->Offer->generateNumber();
			$this->data['Offer']['date'] = date('Y-m-d H:i:s');
		}
		
		$this->_setFormData();
	}
	
	/**
	 * Pripremi podatke za formu (add/edit)
	 */
	function _setFormData() {
		$customers = $this->Offer->Customer->find('list');
		
		$tmp = $this->Offer->OfferItem->Article->find('all', array('order' => array('Article.name' => 'asc')));
		$articles = array();
		$articlesData = array();
		foreach($tmp as &$t) {
			$label = $t['Article']['name'];
			if (!empty($t['Article']['barcode'])) {
				$label .= ' [' . $t['Article']['barcode'] . ']';
			}
			$articles[$t['Article']['id']] = $label;
			$articlesData[$t['Article']['id']] = $t;
		}
		unset($tmp);
		
		// Automobili
		$this->loadModel('Automobil');
		$automobilData = $this->Automobil->find('all', array('order' => array('Automobil.marka' => 'ASC')));
		$automobili = array();
		foreach ($automobilData as $auto) {
			$label = $auto['Automobil']['marka'] . ' ' . $auto['Automobil']['tip'];
			if (!empty($auto['Automobil']['registarska_oznaka'])) {
				$label .= ' (' . $auto['Automobil']['registarska_oznaka'] . ')';
			}
			$automobili[$auto['Automobil']['id']] = $label;
		}
		
		// Uređaji
		$this->loadModel('Uredjaj');
		$uredjajData = $this->Uredjaj->find('all', array('order' => array('Uredjaj.naziv_uredjaja' => 'ASC')));
		$uredjaji = array();
		foreach ($uredjajData as $ured) {
			$label = $ured['Uredjaj']['naziv_uredjaja'];
			if (!empty($ured['Uredjaj']['serijski_broj'])) {
				$label .= ' (SN: ' . $ured['Uredjaj']['serijski_broj'] . ')';
			}
			$uredjaji[$ured['Uredjaj']['id']] = $label;
		}

		$this->set(compact('customers', 'articles', 'articlesData', 'automobili', 'uredjaji'));
	}

	function cancel($id = null) {
		if ((!$id && empty($this->data)) || ($id && !($item = $this->Offer->read(null, $id)))) {
			$this->Session->setFlash(__('Invalid Offer', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		if ($this->Offer->cancelOffer($id)) {
			$this->Session->setFlash(__('Offer canceled', true), 'default', array('class' => 'success'));
		} else {
			$this->Session->setFlash(__('Offer could not be canceled', true), 'default', array('class' => 'error'));
		}
		$this->redirect(array('action' => 'index'));
	}


	function edit($id = null) {
		// Dohvati ponudu sa stavkama (artikli) i predmetom (automobil/uređaj)
		$this->Offer->contain('OfferItem.Article', 'Customer', 'RadniNalog', 'Automobil', 'Uredjaj');
		if ((!$id && empty($this->data)) || ($id && !($item = $this->Offer->read(null, $id)))) {
			$this->Session->setFlash(__('Invalid Offer', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}
		
		if (!empty($this->data)) {
			// Kupac je obavezan
			if (empty($this->data['Offer']['customer_id'])) {
				$this->Session->setFlash(__('Kupac je obavezan. Molimo odaberite kupca.', true), 'default', array('class' => 'error'));
				$this->_setFormData();
				return;
			}
			$this->Offer->data = null;
			
			// Konvertiraj datume iz dd.mm.yyyy. u yyyy-mm-dd format
			if (!empty($this->data['Offer']['document_date'])) {
				$parts = explode('.', $this->data['Offer']['document_date']);
				if (count($parts) >= 3) {
					$this->data['Offer']['document_date'] = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
				}
			}
			if (!empty($this->data['Offer']['vrijedi_do'])) {
				$parts = explode('.', $this->data['Offer']['vrijedi_do']);
				if (count($parts) >= 3) {
					$this->data['Offer']['vrijedi_do'] = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
				}
			}
			
			// Filtriraj stavke - samo artikli
			$price = 0;
			$validItems = array();
			if (!empty($this->data['OfferItem'])) {
				foreach($this->data['OfferItem'] as $ri) {
					if (!empty($ri['article_id'])) {
						$ri['price'] = $ri['amount'] * $ri['price_sell'] * (1 - ($ri['discount'] / 100));
						$price += $ri['price'];
						$article = $this->Offer->OfferItem->Article->read(null, $ri['article_id']);
						$ri['price_buy'] = $article['Article']['price_buy'];
						$validItems[] = $ri;
					}
				}
			}
			$this->data['OfferItem'] = $validItems;
			$this->data['Offer']['price'] = $price;
			
			// Obriši stare stavke
			$list = $this->Offer->OfferItem->find('all', array('conditions' => array('OfferItem.offer_id' => $id)));
			foreach($list as $roi) { 
				$this->Offer->OfferItem->delete($roi['OfferItem']['id']);
			}
			
			if ($this->Offer->saveall($this->data)) {
				$this->Session->setFlash(__('Ponuda je spremljena', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Ponuda nije mogla biti spremljena. Pokušajte ponovo.', true), 'default', array('class' => 'error'));
			}
		}
		
		if (empty($this->data)) {
			$this->data = $item;
		}
		
		$this->_setFormData();
	}

	function delete($id = null) {
		if (!$id || !$this->Offer->read(null, $id)) {
			$this->Session->setFlash(__('Invalid Offer', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Offer->delete($id)) {
			$this->Session->setFlash(__('Offer deleted', true), 'default', array('class' => 'success'));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Offer delete failed. Please, try again.', true), 'default', array('class' => 'error'));
		$this->redirect(array('action' => 'index'));
	}


	/*function _faSuppliers() {
		return $this->Receiving_order->Supplier->find('list');
	}*/

/**
	 * Pretvori ponudu u radni nalog
	 * Kopira artikle iz ponude u radni nalog i prenosi automobil/uređaj
	 */
	function convert_to_radni_nalog($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Nevažeća ponuda', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		// Dohvati ponudu
		$this->Offer->contain('Customer', 'OfferItem.Article', 'Automobil', 'Uredjaj');
		$offer = $this->Offer->read(null, $id);

		if (empty($offer)) {
			$this->Session->setFlash(__('Ponuda nije pronađena', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}
		
		// Kreiraj novi radni nalog
		$this->loadModel('RadniNalog');
		
		// Pripremi napomenu
		$napomena = 'Kreirano iz ponude #' . $offer['Offer']['number'];
		if (!empty($offer['Offer']['note'])) {
			$napomena .= "\n" . $offer['Offer']['note'];
		}
		
		$radniNalogData = array(
			'RadniNalog' => array(
				'customer_id' => $offer['Offer']['customer_id'],
				'datum_rn' => date('Y-m-d'),
				'napomena_rn' => $napomena,
				'offer_id' => $id,
				'automobil_id' => $offer['Offer']['automobil_id'],
				'uredjaj_id' => $offer['Offer']['uredjaj_id'],
				'radni_nalog_status_id' => 1 // Početni status
			)
		);

		$this->RadniNalog->create();
		if (!$this->RadniNalog->save($radniNalogData)) {
			$this->Session->setFlash(__('Greška pri kreiranju radnog naloga.', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'view', $id));
		}
		
		$newRadniNalogId = $this->RadniNalog->id;
		
		// Kopiraj stavke artikala iz ponude u radni nalog
		$this->loadModel('RadniNalogStavka');
		$artiklCount = 0;
		
		if (!empty($offer['OfferItem'])) {
			foreach ($offer['OfferItem'] as $item) {
				if (!empty($item['article_id'])) {
					$this->RadniNalogStavka->create();
					
					$stavkaData = array(
						'RadniNalogStavka' => array(
							'radni_nalog_id' => $newRadniNalogId,
							'article_id' => $item['article_id'],
							'amount' => $item['amount'],
							'discount' => isset($item['discount']) ? $item['discount'] : 0,
							'napomena' => isset($item['napomena']) ? $item['napomena'] : null
						)
					);
					
					if ($this->RadniNalogStavka->save($stavkaData)) {
						$artiklCount++;
					}
				}
			}
		}
		
		// Ažuriraj ponudu - poveži s radnim nalogom
		$this->Offer->id = $id;
		$this->Offer->saveField('radni_nalog_id', $newRadniNalogId);
		
		$msg = __('Radni nalog je uspješno kreiran iz ponude', true);
		if ($artiklCount > 0) {
			$msg .= ' (' . $artiklCount . ' ' . ($artiklCount == 1 ? 'artikl' : 'artikala') . ' kopirano)';
		}
		$this->Session->setFlash($msg, 'default', array('class' => 'success'));
		
		$this->redirect(array('controller' => 'radni_nalogs', 'action' => 'edit', $newRadniNalogId));
	}

	function send_email($id = null, $with_notes = 0) {
		if (!$id) {
			$this->Session->setFlash(__('Nevažeća ponuda', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		// Dohvati ponudu s podacima o kupcu
		$this->Offer->contain('Customer', 'OfferItem.Article');
		$offer = $this->Offer->read(null, $id);
		
		if (empty($offer)) {
			$this->Session->setFlash(__('Ponuda nije pronađena', true), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}

		// PDF će se generirati u AJAX skripti prije slanja emaila
		
		$this->set('offer', $offer);
		$this->set('offer_id', $id);
		$this->set('with_notes', (int)$with_notes);
	}

}
