<?php

App::uses('AppController', 'Controller');
App::uses('HighchartsAppController', 'Highcharts.Controller');
App::import('Controller', 'Api');

/**
 * Settings Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Bemmelhor
 * @version  1.0
 * @author   Fabricio S Costa <fabriciojf@gmail.com>
 *
 * @link     http://www.bemmelhor.org
 */
class SettingsController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    public $name = 'Settings';

    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    public $uses = array('Setting');

    /**
     * Prepara os componentes que serao reutilizados dentro da classe
     */
    var $ApiCtrl;

    public function prepareApis() {
        $this->ApiCtrl = new ApiController();
        $this->ApiCtrl->constructClasses();
    }

    /**
     * Helpers used by the Controller
     *
     * @var array
     * @access public
     */
    public $helpers = array('Html', 'Form');
    public $components = array(
        'Session',
        'Highcharts.Highcharts'
    );

    /**
     * Admin dashboard
     *
     * @return void
     * @access public
     */
    public function admin_dashboard() {
        $this->redirect(array(
            'controller' => 'users',
            'action' => 'mydashboard',
        ));
    }

    /**
     * Admin dashboard
     *
     * @return void
     * @access public
     */
    public function admin_wgresume() {

        $this->loadModel('OfflineCall');
        $this->OfflineCall->create();
        $this->OfflineCall->recursive = 0;

        $primeiroDiaDoMes = date("Y-m-1");
        $ultimoDiaDoMes = date("Y-m-t");

        $conditions = array(
            'conditions' => array(
                'and' => array(
                    array(
                        'OfflineCall.created >= ' => $primeiroDiaDoMes,
                        'OfflineCall.created <= ' => $ultimoDiaDoMes,
                    ),
                )
            ),
            'fields' => array(
                'OfflineCall.dialstatus',
                'COUNT(OfflineCall.id) as offline_call_count'
            ),
            'group' => 'OfflineCall.dialstatus',
        );
        $resume = $this->OfflineCall->find('all', $conditions);
        $this->set('offline_calls', $resume);
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index() {
        $this->Setting->recursive = 0;
        $this->FilterResults->addFilters(
                array(
                    'filter_key' => array(
                        'OR' => array(
                            'Setting.key' => array(
                                'operator' => 'like',
                            ),
                            'Setting.value' => array(
                                'operator' => 'like',
                            ),
                        )
                    ),
                    'filter_key_select' => array(
                        'Setting.key' => array(
                            'select' => $this->FilterResults->select('Key', array(
                                'site' => 'Site',
                                'meta' => 'Meta',
                                'comment' => 'Comment',
                                    )
                            ),
                            'operator' => 'like',
                        )
                    ),
                )
        );

        /*
         * Regras Fixas
         */
        $conditions = array();

        /*
         * 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'],
            'Setting.key' => __('Key'),
        ));

        // Define conditions
        $this->FilterResults->setPaginate('conditions', $conditions);

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

    /**
     * Admin view
     *
     * @param view $id
     * @return void
     * @access public
     */
    public function admin_view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid Setting.'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('setting', $this->Setting->read(null, $id));
    }

    /**
     * Admin add
     *
     * @return void
     * @access public
     */
    public function admin_add() {
        $this->set('title_for_layout', __('Add Setting'));

        if (!empty($this->request->data)) {
            $this->request->data['Setting']['weigth'] = 10;
            $this->request->data['Setting']['editable'] = 1;
            $this->request->data['Setting']['description'] = $this->request->data['Setting']['value'];
            $this->Setting->create();
            if ($this->Setting->save($this->request->data)) {
                $this->Session->setFlash(__('The Setting has been saved'), 'default', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Setting could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
    }

    /**
     * Admin edit
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('Edit Setting'));

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

    /**
     * Admin delete
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_remove($id = null) {

        $this->Setting->id = $id;
        if (!$this->Setting->exists()) {
            $this->Session->setFlash(__('Invalid id for Setting'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
            die();
        }

        $setting = $this->Setting->find('first', array(
            'conditions' => array(
                'id' => $id
            ),
            'fields' => array(
                'key'
            )
        ));

        if ($this->Setting->deleteKey($setting['Setting']['key'])) {
            $this->Session->setFlash(__('Setting deleted'), 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'index'));
        }
    }

    /**
     * Admin prefix
     *
     * @param string $prefix
     * @return void
     * @access public
     */
    public function admin_prefix($prefix = null) {
        $this->set('title_for_layout', __('Settings: %s', $prefix));

        if (!empty($this->request->data) && $this->Setting->saveAll($this->request->data['Setting'])) {
            $this->Session->setFlash(__("Settings updated successfully"), 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'prefix', $prefix));
        }

        $settings = $this->Setting->find('all', array(
            'order' => array(
                'Setting.key' => 'ASC',
            ),
            'conditions' => array(
                'Setting.key LIKE' => $prefix . '.%',
                'Setting.editable' => 1,
            ),
        ));
        $this->set(compact('settings'));

        if (count($settings) == 0) {
            $this->Session->setFlash(__("Invalid Setting key"), 'default', array('class' => 'error'));
        }

        $this->set("prefix", $prefix);
    }

    /**
     * Admin prefix
     *
     * @param string $prefix
     * @return void
     * @access public
     */
    public function admin_confs() {

        $prefix = 'Site';
        $this->set('title_for_layout', __('Settings: %s', $prefix));

        if (!empty($this->request->data) && $this->Setting->saveAll($this->request->data['Setting'])) {
            $this->Session->setFlash(__("Settings updated successfully"), 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'confs'));
        }

        $settings = $this->Setting->find('all', array(
            'order' => array(
                'Setting.key' => 'ASC',
            ),
            'conditions' => array(
                'Setting.key LIKE' => $prefix . '.%',
                'Setting.editable' => 1,
            ),
        ));
        $this->set(compact('settings'));

        if (count($settings) == 0) {
            $this->Session->setFlash(__("Invalid Setting key"), 'default', array('class' => 'error'));
        }

        $this->set("prefix", $prefix);
    }

    /**
     * Admin prefix
     *
     * @param string $prefix
     * @return void
     * @access public
     */
    public function admin_themeadmin($theme = 'Ubuntu') {
        $this->set('title_for_layout', __('Settings: Theme Admin'));

        $theme = $theme == '' ? 'Ubuntu' : $theme;

        $settings = $this->Setting->find('first', array(
            'conditions' => array(
                'Setting.key =' => 'Site.themeadmin'
            ),
        ));
        if ($this->Setting->exists($settings['Setting']['id'])) {
            $this->Setting->read(null, $settings['Setting']['id']);
            $this->Setting->set('value', $theme);
            $this->Setting->save();
        } else {
            $this->Setting->create();
            $this->Setting->set('key', 'Site.themeadmin');
            $this->Setting->set('value', $theme);
            $this->Setting->set('editable', 1);
            $this->Setting->save();
        }

        Configure::write('Site.themeadmin', $theme);
        $this->Session->setFlash(__("Settings updated successfully"), 'default', array('class' => 'success'));
        $this->set('theme', $theme);
    }

    /**
     * Admin moveup
     *
     * @param integer $id
     * @param integer $step
     * @return void
     * @access public
     */
    public function admin_moveup($id, $step = 1) {
        if ($this->Setting->moveUp($id, $step)) {
            $this->Session->setFlash(__('Moved up successfully'), 'default', array('class' => 'success'));
        } else {
            $this->Session->setFlash(__('Could not move up'), 'default', array('class' => 'error'));
        }

        $this->redirect(array('admin' => true, 'controller' => 'settings', 'action' => 'index'));
    }

    /**
     * Admin moveup
     *
     * @param integer $id
     * @param integer $step
     * @return void
     * @access public
     */
    public function admin_movedown($id, $step = 1) {
        if ($this->Setting->moveDown($id, $step)) {
            $this->Session->setFlash(__('Moved down successfully'), 'default', array('class' => 'success'));
        } else {
            $this->Session->setFlash(__('Could not move down'), 'default', array('class' => 'error'));
        }

        $this->redirect(array('admin' => true, 'controller' => 'settings', 'action' => 'index'));
    }

    /**
     * Retorna o condition para status no mes
     * @param unknown_type $dialstatus
     */
    public function getConditionStatusMes($dialstatus) {

        $primeiroDiaDoMes = date("Y-m-1");
        $ultimoDiaDoMes = date("Y-m-t");

        return array(
            'OfflineCall.dialstatus' => $dialstatus,
            'and' => array(
                array(
                    'OfflineCall.created >= ' => $primeiroDiaDoMes,
                    'OfflineCall.created <= ' => $ultimoDiaDoMes,
                ),
        ));
    }

}
