<?php
class CustomersController extends AppController {

	var $name = 'Customers';

    var $components = array(
	    'Filter' => array(
	        'index' => array(
				'name' => array(
        	        'form_options' => array('label' => 'Name'),
	            	'filter_options' => array('fields' => array('Customer.name'), 'operator' => 'like^'),
				),
	        )
        ),
	);

	function index() {
		$this->Customer->contain('Sale');
		$this->set('items', $this->paginate());
	}

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

	function add() {
		if (!empty($this->data)) {
			$this->Customer->create();
			if ($this->Customer->save($this->data)) {
				$this->Session->setFlash(__('The customer has been saved', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
			}
		}
	}

	function edit($id = null) {
		if ((!$id && empty($this->data)) || ($id && !($item = $this->Customer->read(null, $id)))) {
			$this->Session->setFlash(__('Invalid Customer', true) . ($id ? " #{$id}" : ""), 'default', array('class' => 'error'));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			$this->Customer->data = null;	// unset model data so modified field can be updated automagically
			if ($this->Customer->save($this->data)) {
				$this->Session->setFlash(__('The customer has been saved', true), 'default', array('class' => 'success'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
			}
		}
		if (empty($this->data)) {
			$this->data = $item;
		}
	}

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

}
