<?php

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

/**
 * LiturgicalTimes *
 * @property LiturgicalTime $LiturgicalTime
 */
class LiturgicalTimesController extends AppController {

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

    /**
     * admin_index
     */
    public function admin_index($in_trash = false) {
        $this->LiturgicalTime->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_name' => array(
                        'LiturgicalTime.name' => array(
                            'operator' => 'like',
                        )
                    ),
                )
        );

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

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

        /**
         * Itens por pagina
         */
        $data = $this->request->params;
        $itemsPerPage = $this->items_per_page("{$data['controller']}/{$data['action']}");

        $params = $itemsPerPage['ItemsPerPage'];
        $this->FilterResults->setPaginate('limit', $params['quantity']);

        if ($params['orderby_field'] != '') {
            $this->FilterResults->setPaginate('order', "{$params['orderby_field']} {$params['orderby_type']}");
        }

        $this->set('items_per_page', $params['quantity']);
        $this->set('orderby_type', $params['orderby_type']);
        $this->set('orderby', array(
            $params['orderby_field'] => $params['orderby_field'],
            'LiturgicalTime.ordered' => __('Order'),
            'LiturgicalTime.name' => __('Name'),
        ));

        // Define conditions
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->set('box_visible', $this->box_visibility($data['controller'], $data['action']));
        $this->set('liturgicalTimes', $this->paginate());
    }

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

        $this->loadModel('FixedPart');
        $this->set('fixedParts', $this->FixedPart->find('all', array('order' => array('FixedPart.ordered' => 'asc'))));
        $this->set('liturgicalTime', $this->LiturgicalTime->read(null, $id));
    }

    /**
     * admin_add
     */
    public function admin_add($object_type = '', $object_id = null) {
        if ($this->request->is('post')) {
            $this->LiturgicalTime->create();
            $this->request->data['LiturgicalTime']['slug'] = strtolower(Inflector::slug($this->request->data['LiturgicalTime']['name']));
            if ($this->LiturgicalTime->save($this->request->data)) {
                $this->Session->setFlash(__('The liturgical time has been saved'), 'default', array(), 'good');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The liturgical time could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }
    }

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

        if ($this->request->is('post') || $this->request->is('put')) {
            $this->request->data['LiturgicalTime']['slug'] = strtolower(Inflector::slug($this->request->data['LiturgicalTime']['name']));
            if ($this->LiturgicalTime->save($this->request->data)) {
                $this->Session->setFlash(__('The liturgical time has been saved'), 'default', array(), 'good');
                $this->redirect(array('action' => 'view', $id));
            } else {
                $this->Session->setFlash(__('The liturgical time could not be saved. Please, try again.'), 'default', array(), 'bad');
            }
        }

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

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

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

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

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

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

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

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

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

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

    /**
     * admin_reordenation
     */
    public function admin_reordenation() {
        if ($this->request->is('post') || $this->request->is('put')) {
            foreach ($this->request->data['LiturgicalTime'] as $item) {
                $this->LiturgicalTime->id = $item['id'];
                $this->LiturgicalTime->saveField('ordenation', $item['ordenation']);
            }
        }
        $this->redirect(array('action' => 'index'));
    }

    /**
     * index
     */
    public function index() {

        $this->LiturgicalTime->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_name' => array(
                        'LiturgicalTime.name' => array(
                            'operator' => 'like',
                        )
                    ),
                )
        );

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

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

        $this->FilterResults->setPaginate('limit', 20);
        $this->FilterResults->setPaginate('order', array(
            "LiturgicalTime.name" => 'ASC'
        ));

        // Define conditions
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->set('liturgicalTimes', $this->paginate());
    }

    /**
     * view
     */
    public function view($slug = null) {
        $obj = $this->LiturgicalTime->find('first', array(
            'conditions' => array(
                'LiturgicalTime.slug' => $slug,
                'LiturgicalTime.in_trash' => false,
            ),
        ));

        if (count($obj) == 0) {
            throw new NotFoundException(__('Invalid Liturgical Time'));
        }

        $this->loadModel('MusicSugestion');
        $this->set('musicSugestion', $this->MusicSugestion->find('all', array(
            'conditions' => array(
                'MusicSugestion.liturgical_time_id' => $obj['LiturgicalTime']['id'],
                'MusicSugestion.in_trash' => false,
            ),
            'order' => array(
                'FixedPart.ordered' =>  'asc'
            )
        )));
        $this->set('liturgicalTime', $obj);
    }

}
