<?php
class AddressesController extends AppController {

	var $name = 'Addresses';
	var $helpers = array('Html', 'Form');
	var $components = array('RequestHandler');
	function index() {
		$this->Address->recursive = 0;
		$this->set('addresses', $this->paginate());
	}

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

	function add($customerid = null ) {
		if(isset($this->params['named']['customerid'])) {
			$customerid = $this->params['named']['customerid'];
		}
		if(!$customerid) {
			$this->Session->setFlash(__('Invalid Customer ID', true));
			$this->redirect(array('controller'=>'Enquiries', 'action'=>'index'));
		}
		
		if (!empty($this->data)) {
			$this->Address->create();
			if ($this->Address->save($this->data)) {
				$this->Session->setFlash(__('The Address has been saved', true));
				$this->redirect(array('controller' => 'customers', 'action'=>'view/'.$customerid));
			} else {
				$this->Session->setFlash(__('The Address could not be saved. Please, try again.', true));
			}
		}
		$customer = $this->Address->Customer->findById($customerid);
		$states = $this->Address->State->find('list');
		$countries = $this->Address->Country->find('list');
		$this->set(compact('customer', 'states', 'countries'));
	}

	function add_another($increment) {
		$this->set('increment', $increment);
		$states = $this->Address->State->find('list');
		$countries = $this->Address->Country->find('list');
		$this->set('states', $states);
		$this->set('countries', $countries);
	}
	function remove_another($increment) {
		$this->set('increment', $increment);
	}
	

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Address', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Address->save($this->data)) {
				$id = $this->Address->id;
				$address = $this->Address->findById($id);
				$this->Session->setFlash(__('The Address has been saved', true));
				$this->redirect(array('controller' => 'customers', 'action'=>'view/'.$address['Address']['customer_id']));
			} else {
				$this->Session->setFlash(__('The Address could not be saved. Please, try again.', true));
			}
		}
		
		$address = $this->Address->read(null, $id);
		$customer = $this->Address->Customer->findById($address['Address']['customer_id']);
		$states = $this->Address->State->find('list');
		$countries = $this->Address->Country->find('list');
		$this->set(compact('customer','states','countries', 'address'));
		if (empty($this->data)) {
			$this->data = $address; 
		}
	
	}



	function customerAddresses($customerID) {
	    $this->layout = 'ajax';

	    $this->set('addresses', $this->Address->find('all', array('conditions'=>array('Customer.id'=>$customerID))));
	}

}
?>
