<?php

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

/**
 * Wikis *
 * @property Wiki $Wiki
 */
class WikisController extends AppController {

    /**
     * beforeFilter
     *
     * @return void
     */
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow(
                'index', 'view', 'find', 'show_group'
        );
    }

    /**
     * admin_index
     */
    public function admin_index($in_trash = false) {
        $this->Wiki->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_name' => array(
                        'Wiki.name' => array(
                            'operator' => 'like',
                        )
                    ),
                    'filter_group' => array(
                        'Wiki.wiki_group_id' => array(
                            'select' => $this->FilterResults->select(
                                    'WikiGroup', $this->Wiki->WikiGroup->find('list')),
                        )
                    ),
                )
        );

        /*
         * Regras Fixas
         */
        $conditions = array(
            'Wiki.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', array('Wiki.id' => 'DESC'));
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 10);

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

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


        $users = array("" => "");

        $this->set(compact('users'));
    }

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

            $this->request->data['Wiki']['name'] = $this->request->data['Wiki']['title'];
            $this->request->data['Wiki']['slug'] = strtolower(Inflector::slug($this->request->data['Wiki']['title']));
            $this->request->data['Wiki']['user_id'] = $this->Auth->user('id');

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

        $users = $this->Wiki->User->list_all();
        $wiki_groups = $this->Wiki->WikiGroup->list_all();

        $this->set(compact('users', 'wiki_groups'));
    }

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

        if ($this->request->is('post') || $this->request->is('put')) {

            $this->request->data['Wiki']['name'] = $this->request->data['Wiki']['title'];
            $this->request->data['Wiki']['slug'] = strtolower(Inflector::slug($this->request->data['Wiki']['title']));
            $this->request->data['Wiki']['user_id'] = $this->Auth->user('id');

            if ($this->Wiki->save($this->request->data)) {
                $this->redirect(array('action' => 'edit', $id));
            } else {
                $this->Session->setFlash(__('The wiki could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

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

        $users = $this->Wiki->User->list_all($Wiki['Wiki']['user_id']);
        $wiki_groups = $this->Wiki->WikiGroup->list_all($Wiki['Wiki']['wiki_group_id']);

        $this->set(compact('users', 'wiki_groups'));
    }

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

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

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

        $obj = $this->Wiki->read(array('active'), $id);
        $this->Wiki->saveField('active', !$obj['Wiki']['active']);
        $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->Wiki->recursive = -1;
            $outputs = $this->Wiki->find('all', array(
                'fields' => array(
                    'id',
                    'name',
                ),
                'conditions' => array(
                    'AND' => array(
                        'LOWER(Wiki.name) LIKE' => '%' . strtolower($query['filter']) . '%',
                        'in_trash' => false
                    ),
                )
            ));

            $jsontext = "";
            $sep = '';
            foreach ($outputs as $obj) {
                $jsontext .= $sep . '{"id":"' . $obj['Wiki']['id'] . '", "text":"' . $obj['Wiki']['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->Wiki->recursive = -1;
            $outputs = $this->Wiki->find('list', array('limit' => 50));

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

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

        $this->Wiki->updateAll(array('default_selected' => false));
        $obj = $this->Wiki->read(array('default_selected'), $id);
        $this->Wiki->saveField('default_selected', !$obj['Wiki']['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->Wiki->create();
            $this->request->data['Wiki']['name'] = $query['p_name'];

            $lastid = '';
            if ($this->Wiki->save($this->request->data)) {
                $lastid = $this->Wiki->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['Wiki']['id']}', 'text': '{$item['Wiki']['name']}'},";
        }
        return "[{$jsonItems}]";
    }

    /**
     * index
     */
    public function index() {
        $this->layout = 'wiki';
        $this->set('wiki_groups', $this->Wiki->WikiGroup->find('all', array(
                    'conditions' => array(
                        'WikiGroup.in_trash' => false,
                        'WikiGroup.active' => true,
                    ),
                    'order' => array(
                        'WikiGroup.ordenation' => 'ASC'
                    )
        )));
        $this->set('wiki', array('Wiki' => array('title' => Configure::read('Site.title') . ' - Faq')));
    }

    /**
     * show_group
     */
    public function show_group() {
        $this->layout = 'wiki';

        if (!isset($this->request->params['group'])) {
            throw new NotFoundException(__('Invalid landing'));
        }
        $this->layout = 'wiki';
        $group = $this->request->params['group'];

        $this->Wiki->WikiGroup->recursive = -1;
        $wikiGroup = $this->Wiki->WikiGroup->findBySlug($group, array(
                'id',
                'name',
            ));
        $this->paginate['limit'] = 100;
        $this->paginate['order'] = array(
            'Wiki.name' => 'ASC'
        );
        $this->paginate['conditions'] = array(
                        'Wiki.in_trash' => false,
                        'WikiGroup.active' => true,
                        'Wiki.wiki_group_id' => $wikiGroup['WikiGroup']['id'],
                    );

        $this->set('wiki_groups', $this->Wiki->WikiGroup->find('all', array(
                    'conditions' => array(
                        'WikiGroup.in_trash' => false,
                        'WikiGroup.active' => true,
                    ),
                    'order' => array(
                        'WikiGroup.ordenation' => 'ASC'
                    )
        )));

        $this->set('wikis', $this->paginate('Wiki'));
        $this->set('wiki', array('Wiki' => array('title' => Configure::read('Site.title') . ' - Faq')));
        $this->set('group', $wikiGroup);
    }

    /**
     * view
     */
    public function view() {

        if (!isset($this->request->params['slug'])) {
            throw new NotFoundException(__('Invalid landing'));
        }
        $this->layout = 'wiki';
        $slug = $this->request->params['slug'];

        $this->set('wiki_groups', $this->Wiki->WikiGroup->find('all', array(
                    'conditions' => array(
                        'WikiGroup.in_trash' => false,
                        'WikiGroup.active' => true,
                    ),
                    'order' => array(
                        'WikiGroup.ordenation' => 'ASC'
                    )
        )));

        $this->Wiki->recursive = 1;
        $this->set('wiki', $this->Wiki->findBySlug($slug));
    }

    /**
     * find
     */
    public function find() {

        if (isset($this->request->data['Wiki']['filter_name'])) {
            $field = base64_encode(base64_encode('filter.filter_name'));
            $value = base64_encode(base64_encode($this->request->data['Wiki']['filter_name']));
            $this->request['named'] = array(
			$field => $value
		);
        }

        $this->layout = 'wiki';
        $this->Wiki->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_name' => array(
                        'OR' => array(
                            'Wiki.name' => array(
                                'operator' => 'like',
                            ),
                            'Wiki.content' => array(
                                'operator' => 'like',
                            )
                        )
                    ),
                )
        );

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

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

        // Define conditions
        $this->FilterResults->setPaginate('order', 'Wiki.name');
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 100);

        $this->set('wiki_groups', $this->Wiki->WikiGroup->find('all', array(
                    'conditions' => array(
                        'WikiGroup.in_trash' => false,
                        'WikiGroup.active' => true,
                    ),
                    'order' => array(
                        'WikiGroup.ordenation' => 'ASC'
                    )
        )));

        $this->set('wikis', $this->paginate());
        $this->set('filterTerm', isset($this->request->data['filter']['filter_name']) ?
                $this->request->data['filter']['filter_name'] : '');
        $this->set('wiki', array('Wiki' => array('title' => Configure::read('Site.title') . ' - Faq')));
    }

}
