<?php
class CostingsController extends AppController {

	var $name = 'Costings';
	var $helpers = array('Html', 'Form', 'Javascript');

	function index() {
		$this->Costing->recursive = 0;
		$this->set('costings', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Costing.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('costing', $this->Costing->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Costing->create();
			if ($this->Costing->save($this->data)) {
				$this->Session->setFlash(__('The Costing has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Costing could not be saved. Please, try again.', true));
			}
		}
		if(isset($this->params['named']['productid'])) {
			$product = $this->Costing->Product->findById($this->params['named']['productid']);

			$this->set('type', 'product');
			$this->set('product', $product);
		}

		if(isset($this->params['named']['line_item_id'])) {
			$line_item = $this->Costing->LineItem->findById($this->params['named']['line_item_id']);

			$this->set('type', 'line_item');
			$this->set('line_item', $line_item);
		}



		$purchaseCurrencies = $this->Costing->PurchaseCurrency->find('list');
		$saleCurrencies = $this->Costing->SaleCurrency->find('list');
		$this->set(compact('purchaseCurrencies', 'saleCurrencies'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Costing', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Costing->save($this->data)) {
				$this->Session->setFlash(__('The Costing has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Costing could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Costing->read(null, $id);
		}
		$products = $this->Costing->Product->find('list');
		$lineItems = $this->Costing->LineItem->find('list');
		$purchaseCurrencies = $this->Costing->PurchaseCurrency->find('list');
		$saleCurrencies = $this->Costing->SaleCurrency->find('list');
		$this->set(compact('products','lineItems','purchaseCurrencies','saleCurrencies'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Costing', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Costing->del($id)) {
			$this->Session->setFlash(__('Costing deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>
