<?php

App::uses('AppController', 'Controller');

/**
 * Menus *
 * @property Menu $Menu
 */
class MenusController extends AppController {

    /**
     * admin_index
     */
    public function admin_index($in_trash = false) {
        $this->Menu->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_alias' => array(
                        'OR' => array (
                            'Menu.alias' => array(
                                'operator' => 'like',
                            ),
                            'Menu.title' => array(
                                'operator' => 'like',
                            ),
                        )
                    ),
                )
        );

        /*
         * Regras Fixas
         */
        $conditions = array(
            'Menu.in_trash' => $in_trash
        );

        /*
         * Mix com filter_results
         */
        if ($this->FilterResults->getConditions()) {
            $conditions = array_merge($this->FilterResults->getConditions(), $conditions);
        }

        // Define conditions
        $this->FilterResults->setPaginate('order', 'Menu.alias');
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 10);

        $this->set('menus', $this->paginate());
    }

    /**
     * admin_view
     */
    public function admin_view($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid menu'));
        }
        $this->set('menu', $this->Menu->read(null, $id));


    }

    /**
     * admin_add
     */
    public function admin_add($object_type = '', $object_id = null) {
        if ($this->request->is('post')) {
            $this->Menu->create();

            $this->request->data['Menu']['weight'] = 1;
            $this->request->data['Menu']['link_count'] = 1;
            $this->request->data['Menu']['status'] = 1;

            if ($this->Menu->save($this->request->data)) {
                $this->Session->setFlash(__('The menu has been saved'), 'default', array(), 'good');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The menu could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

    }

    /**
     * admin_edit
     */
    public function admin_edit($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid menu'));
        }

        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Menu->save($this->request->data)) {
                $this->Session->setFlash(__('The menu has been saved'), 'default', array(), 'good');
                $this->redirect(array('action' => 'view', $id));
            } else {
                $this->Session->setFlash(__('The menu could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

        $this->Menu->recursive = 2;
        $Menu = $this->Menu->read(null, $id);
        $this->request->data = $Menu;

    }

    /**
     * admin_remove
     */
    public function admin_remove($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid menu'));
        }
        $this->Menu->set('in_trash', true);
        if ($this->Menu->save()) {
            $this->Session->setFlash(__('Menu') .' '. __('deleted'), 'default', array(), 'good');
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Menu') .' '. __('was not deleted'), 'default', array(), 'bad');
        $this->redirect(array('action' => 'index'));
    }

    /**
     * admin_recover
     */
    public function admin_recover($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid menu'));
        }
        $this->Menu->set('in_trash', false);
        if ($this->Menu->save()) {
            $this->Session->setFlash(__('Menu') .' '. __('Recovered'), 'default', array(), 'good');
            $this->redirect(array('action' => 'view', $id));
        }
        $this->Session->setFlash(__('Menu') .' '. __('was not recovered'), 'default', array(), 'bad');
        $this->redirect(array('action' => 'index'));
    }

    /**
     * admin_active_inactive
     */
    public function admin_active_inactive($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid Menu'));
        }

        $obj = $this->Menu->read(array('status'), $id);
        $this->Menu->saveField('status', !$obj['Menu']['status']);
        $this->redirect(array(
            'action' => 'index'
        ));
    }

    /**
     * Componente de busca Lookup
     */
    public function admin_lookup() {
        $this->autoRender = false;
        if ($this->request->is('ajax')) {
            $query = $this->request->query;

            $this->autoRender = false;
            $this->Menu->recursive = -1;
            $outputs = $this->Menu->find('all', array(
                'fields' => array(
                    'id',
                    'name',
                ),
                'conditions' => array(
                    'AND' => array(
                        'LOWER(Menu.name) LIKE' => '%' . strtolower($query['filter']) . '%',
                        'in_trash' => false
                    ),
                )
            ));

            $jsontext = "";
            $sep = '';
            foreach ($outputs as $obj) {
                $jsontext .= $sep . '{"id":"' . $obj['Menu']['id'] . '", "text":"' . $obj['Menu']['name'] . '"}';
                $sep = ',';
            }
            return '[' . $jsontext . ']';
        }
    }

    /**
     * Componente de busca Lookup list
     */
    public function admin_lookup_init() {
        $this->autoRender = false;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->Menu->recursive = -1;
            $outputs = $this->Menu->find('list', array('limit' => 50));

            $jsontext = "";
            $sep = '';
            foreach ($outputs as $obj) {
                $jsontext .= $sep . '{"id":"' . $obj['Menu']['id'] . '", "text":"' . $obj['Menu']['name'] . '"}';
                $sep = ',';
            }
            return '[' . $jsontext . ']';
        }
    }

    /**
     * set default_selected
     */
    public function admin_default_selected($id = null) {
        $this->Menu->id = $id;
        if (!$this->Menu->exists()) {
            throw new NotFoundException(__('Invalid menu'));
        }

        $this->Menu->updateAll(array('default_selected' => false));
        $obj = $this->Menu->read(array('default_selected'), $id);
        $this->Menu->saveField('default_selected', !$obj['Menu']['default_selected']);
        $this->redirect(array(
            'action' => 'index'
        ));
    }

    /**
     * admin_jquery_Add
     */
    public function admin_jquery_add() {

        $this->autoRender = false;
        if ($this->request->is('ajax')) {
            $query = $this->request->query;

            $this->Menu->create();
            $this->request->data['Menu']['name'] = $query['p_name'];

            $lastid = '';
            if ($this->Menu->save($this->request->data)) {
                $lastid = $this->Menu->id;
            }
            return json_encode(array(
                "id" => $lastid,
                "desc" => $query['p_name']
            ));
        }
    }

    /**
     * Retorna um json de itens para popular um combo
     */
    public function list_all() {
        $this->recursive = -1;
        $items = $this->find('all', array(
            'fields' => array(
                'id',
                'name'
            ),
            'order' => array(
                'default_selected',
                'name'
            )
        ));
        $jsonItems = '';
        foreach ($items as $item) {
            $jsonItems .= "{id: '{$item['Menu']['id']}', 'text': '{$item['Menu']['name']}'},";
        }
        return "[{$jsonItems}]";
    }

}
