<?php

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

/**
 * Links *
 * @property Link $Link
 */
class LinksController extends AppController {

    /**
     * admin_index
     */
    public function admin_index($menuId = null) {

        if (!$menuId) {
            $this->redirect(array(
                'controller' => 'menus',
                'action' => 'index',
            ));
            return;
        }

        $this->Link->Menu->recursive = 0;
        $menu = $this->Link->Menu->read(array(
            'Menu.id',
            'Menu.title',
            'Menu.alias',
                ), $menuId);

        if (!isset($menu['Menu']['id'])) {
            $this->redirect(array(
                'controller' => 'menus',
                'action' => 'index',
            ));
            return;
        }

        $this->Link->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_title' => array(
                        'Link.title' => array(
                            'operator' => 'like',
                        )
                    ),
                )
        );

        /*
         * Regras Fixas
         */
        $conditions = array(
            'Link.in_trash' => false,
            'Link.menu_id' => $menuId,
        );

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

        // Define conditions
        $this->FilterResults->setPaginate('order', array(
            'Link.status' => 'desc',
            'Link.lft' => 'asc',
            ));
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 10);

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

     /**
     * admin_index
     */
    public function admin_intrash() {

        $this->Link->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_title' => array(
                        'Link.title' => array(
                            'operator' => 'like',
                        )
                    ),
                )
        );

        /*
         * Regras Fixas
         */
        $conditions = array(
            'Link.in_trash' => true,
        );

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

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

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

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

        $parentLinks = array("" => "");
        $menus = array("" => "");

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

    /**
     * admin_add
     */
    public function admin_add($menuId = null) {
        if ($this->request->is('post')) {
            $this->Link->create();
            if ($this->Link->save($this->request->data)) {
                $this->Session->setFlash(__('The link has been saved'), 'default', array(), 'good');
                $this->clear_cache();
                $this->redirect(array('action' => 'index', $menuId));
            } else {
                $this->Session->setFlash(__('The link could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

        $menu = $this->Link->Menu->read(array(
            'Menu.id',
            'Menu.title',
            'Menu.alias',
                ), $menuId);

        $parent_links = $this->Link->ParentLink->list_all();
        $menus = $this->Link->Menu->list_all($menuId);

        $this->set(compact('parent_links', 'menus', 'menu'));
    }

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

        $this->Link->recursive = 2;
        $Link = $this->Link->read(null, $id);

        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Link->save($this->request->data)) {
                $this->Session->setFlash(__('The link has been saved'), 'default', array(), 'good');
                $this->clear_cache();
                $this->redirect(array('action' => 'index', $Link['Link']['menu_id']));
            } else {
                $this->Session->setFlash(__('The link could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

        $this->request->data = $Link;

        $parent_links = $this->Link->ParentLink->list_all($Link['Link']['parent_id']);
        $menus = $this->Link->Menu->list_all($Link['Link']['menu_id']);

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

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

        $link = $this->Link->read(array('menu_id'), $id);

        $this->Link->delete($id);
        $this->Session->setFlash(__('Link') . ' ' . __('deleted'), 'default', array(), 'good');
        $this->redirect(array(
            'action' => 'index', $link['Link']['menu_id']
        ));
    }

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

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

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

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

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

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

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

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

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

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

    /**
     * function to clear all cache data
     * by default accessible only for admin
     *
     * @access Public
     * @return void
     */
    public function clear_cache() {
        Cache::clear();
        clearCache();

        $files = array();
        $files = array_merge($files, glob(CACHE . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'css' . DS . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'js' . DS . '*'));  // remove cached js
        $files = array_merge($files, glob(CACHE . 'models' . DS . '*'));  // remove cached models
        $files = array_merge($files, glob(CACHE . 'persistent' . DS . '*'));  // remove cached persistent
        $files = array_merge($files, glob(CACHE . 'queries' . DS . '*'));  // remove cached persistent

        foreach ($files as $f) {
            if (is_file($f)) {
                unlink($f);
            }
        }

        if (function_exists('apc_clear_cache')):
            apc_clear_cache();
            apc_clear_cache('user');
        endif;
    }

    /**
     * admin_reordenation
     */
    public function admin_reordenation($menuId = null) {
        if ($this->request->is('post') || $this->request->is('put')) {

            foreach ($this->request->data['Link'] as $item) {
                $this->Link->id = $item['id'];
                $this->Link->saveField('lft', $item['lft']);
            }
            $this->clear_cache();
        }
        $this->redirect(array('action' => 'index', $this->request->data['Menu']['id']));
    }
}
