<?php
class CurrenciesController extends AppController {

    var $name = 'Currencies';
    var $helpers = array('Html', 'Form', 'Ajax');
    var $components = array('RequestHandler');

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

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

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

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Currency', true));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            if ($this->Currency->save($this->data)) {
                $this->Session->setFlash(__('The Currency has been saved', true));
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Currency could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Currency->read(null, $id);
        }
    }

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


    function jsonlist() {
        $currencies = $this->Currency->find('all', array('recursive'=>0));

        $jsonlist = array();

            /* Make the cakePHP data structure more suitable for JSON */
        foreach ($currencies as $currency) {
            $id = $currency['Currency']['id'];
            $jsonlist[$id] = array('name' => $currency['Currency']['name'],
                'symbol'=>$currency['Currency']['symbol'],
                'iso4217'=>$currency['Currency']['iso4217']
            );
        }

        //$jsonlist = json_encode($jsonlist);

        $this->set('currencies', $jsonlist);
        //$this->set('currencies', $jsonlist);
        $this->render(null,'ajax');
        Configure::write('debug',0);
    }

}
?>
