<?php
class LineItemsController extends AppController {

	var $name = 'LineItems';
	var $helpers = array('Html', 'Form', 'Javascript', 'Number', 'Decimal');

	var $components = array('RequestHandler');



	function ajax_add() {
		$this->layout = 'ajax';
		if(!empty($this->data)) {
			$this->LineItem->create($this->data);

			if ($this->LineItem->save($this->data)) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";

				//print_r($this->data);
			}
		}
		else {
			echo "NO-DATA";
		}

	}


	function ajax_edit() {
		$this->layout = 'ajax';
		if(!empty($this->data)) {

			if ($this->LineItem->save($this->data)) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}
		}
		else {
			echo "NO-DATA";
		}

	}


	function ajax_delete($id = null) {
		$this->layout = 'ajax';
		if($id == null) {
			echo "FAILURE";
		}
		else {
			if ($this->LineItem->del($id)) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}
		}
	}

	/**
	 * Get the products table with prices (for quotes, invoices etc)
	 * @param <type> $documentID
	 */
	function getTable($documentID = null) {
		$this->layout = 'ajax';
		if($documentID == null) {
			echo "INVALID DOCUMENT ID";
		}
		else {
			$document = $this->LineItem->Document->find('first',array('conditions'=>array('Document.id'=>$documentID)));
			$this->set('document',$document);

			$enquiry = $this->LineItem->Document->getEnquiry($document);
			$this->set('enquiry', $enquiry);
			$gst = $this->LineItem->Document->gstApplies($enquiry);
			$this->set('gst',$gst);

			$this->set('totals', $this->calculateTotals($document, $gst));

			$currency = $this->LineItem->Document->getCurrency($document);
			$this->set('currencyCode', $currency['Currency']['iso4217']);
			$this->set('currencySymbol', $currency['Currency']['symbol']);
		}
	}

	function edit($id = null) {
		$this->layout = 'ajax';

		$this->data = $this->LineItem->read(null,$id);
		$this->set('yesNo', array(0=>'No', 1=>'Yes'));
		$this->set('principles', $this->LineItem->Product->Principle->find('list'));



	}

	function add($documentID = null) {
		$this->layout = 'ajax';
		$document = $this->LineItem->Document->read(null, $documentID);
		$this->set('document', $document);
		$this->set('yesNo', array(0=>'No', 1=>'Yes'));
		$this->set('principles', $this->LineItem->Product->Principle->find('list'));
	}

}
?>
