<?php

App::uses('AppController', 'Controller');
App::uses('HighchartsAppController', 'Highcharts.Controller');
App::uses('CakeEmail', 'Network/Email');
App::import('Controller', 'RestEndPoint');
App::uses('HttpSocket', 'Network/Http');

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

    /**
     * Components
     *
     * @var array
     * @access public
     */
    public $components = array(
        'Email',
        'Key.Key',
        'RequestHandler',
        'Export.Export',
        'Highcharts.Highcharts',
    );

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

    /**
     * implementedEvents
     *
     * @return array
     */
    public function implementedEvents()
    {
        return parent::implementedEvents() + array(
            'Controller.Users.beforeAdminLogin' => 'onBeforeAdminLogin',
            'Controller.Users.adminLoginFailure' => 'onAdminLoginFailure',
        );
    }

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

    /**
     * Notify user when failed_login_limit hash been hit
     *
     * @return bool
     */
    public function onBeforeAdminLogin()
    {
        $field = $this->Auth->authenticate['all']['fields']['email'];
        if (empty($this->request->data)) {
            return true;
        }
        $cacheName = 'auth_failed_' . $this->request->data['User'][$field];
        $cacheValue = Cache::read($cacheName, 'users_login');
        if (Cache::read($cacheName, 'users_login') >= Configure::read('User.failed_login_limit')) {
            $this->Session->setFlash(
                __('You have reached maximum limit for failed login attempts. Please try again after a few minutes.'),
                'default',
                array(),
                'bad'
            );
            return $this->redirect(array('action' => $this->request->params['action']));
        }
        return true;
    }

    /**
     * Record the number of times a user has failed authentication in cache
     *
     * @return bool
     * @access public
     */
    public function onAdminLoginFailure()
    {
        $field = $this->Auth->authenticate['all']['fields']['email'];
        if (empty($this->request->data)) {
            return true;
        }
        $cacheName = 'auth_failed_' . $this->request->data['User'][$field];
        $cacheValue = Cache::read($cacheName, 'users_login');
        Cache::write($cacheName, (int) $cacheValue + 1, 'users_login');
        return true;
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index()
    {

        $this->set('title_for_layout', __('Users'));
        $this->User->recursive = 0;
        $this->FilterResults->addFilters(
            array(
                'filter_name' => array(
                    'OR' => array(
                        'User.name' => array(
                            'operator' => 'like',
                        ),
                        'User.username' => array(
                            'operator' => 'like',
                        ),
                    ),
                ),
                'filter_email' => array(
                    'User.email' => array(
                        'operator' => 'like',
                    )
                ),
                'filter_role' => array(
                    'User.role_id' => array(
                        'select' => $this->FilterResults->select('Role', $this->User->Role->find('list')),
                    )
                ),
            )
        );

        // Define conditions
        $this->FilterResults->setPaginate('fields', array(
            'id',
            'Role.title',
            'Role.alias',
            'name',
            'email',
            'status',
            'phone',
            'locale',
            "CASE WHEN last_access < (now() - interval '1 min') THEN false ELSE true END AS is_logged"
        ));

        $this->FilterResults->setPaginate('order', 'User.id DESC');
        $this->FilterResults->setPaginate('conditions', $this->FilterResults->getConditions());
        $this->FilterResults->setPaginate('limit', 20);

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

    /**
     * Relatorio de quantidade de conversas X canal (Atendido ou não atendido)
     */
    public function admin_report_chats()
    {

        $this->loadModel('ChatsClosed');

        $this->setDatepicker('filter_calldate_from', '00:00');
        $this->setDatepicker('filter_calldate_to', '23:59');

        if ($this->request->is('post')) {
            $params = $this->formatDateTime(
                $this->request->data['filter_calldate_from'],
                $this->request->data['filter_calldate_to']
            );
        } else {
            $params = $this->formatDayOf('day');
        }

        $typ = 'NULL';

        $from = $this->request->data['filter_calldate_from'] ? $this->request->data['filter_calldate_from'] : '1970-01-01';
        $ddstr = date('Y') . '-' . date('m') . '-' . date('d') . ' 23:59';
        $to = $this->request->data['filter_calldate_to'] ? $this->request->data['filter_calldate_to'] : $ddstr;

        $uid = isset($this->request->data['filter_agent']) ? $this->request->data['filter_agent'] : "0";
        if ($uid == 0) {
            $uid = "0";
        }

        $closed = $this->User->query(sprintf(
            "select * from reports_users_quantity('%s','%s',%s,%s)",
            $from,
            $to,
            $uid,
            $typ
        ));

        /**
         * High Charts
         * @var unknown_type
         */
        $total = 0;
        $data = array();
        foreach ($closed as $item) {
            $current = array(
                array(
                    __($item[0]['message_type']) . ' ' . __($item[0]['type_status']),
                    (int) $item[0]['total']
                )
            );
            $total += (int) $item[0]['total'];
            $data = array_merge($data, $current);
        }

        $chartData = $data;
        $chartName = 'Total Chats';
        $pieChart = $this->Highcharts->create($chartName, 'pie');

        $this->Highcharts->setChartParams($chartName, array(
            'renderTo' => 'piewrapper',
            'xAxisLabelsEnabled' => TRUE,
            'xAxisCategories' => $data,
            'yAxisTitleText' => 'Total Chats',
            'enableAutoStep' => FALSE,
            'title' => $chartName,
            'plotOptionsShowInLegend' => true,
            'creditsEnabled' => false,
            'plotBackgroundColor' => null,
            'plotBorderWidth' => null,
            'plotShadow' => true,
        ));

        $series = $this->Highcharts->addChartSeries();
        $series->addName('Valor ')->addData($chartData);
        $pieChart->addSeries($series);

        // todo: trocar o componente lookup
        // Montando o combo de usuarios
        $ul = array(0 => 'Todos');
        $user_list = $this->User->find('list');
        $ul = array_merge($ul, $user_list);
        $this->set('users', $ul);

        $this->set(compact('chartName'));
        $this->set('total', $total);
        $this->set('data', $data);
    }

    /**
     * Relatorio de usuarios logados
     */
    public function admin_report_users($export = false)
    {
        $this->set('title_for_layout', __('Users'));
        $this->User->recursive = 0;

        $logs = array(
            true => "Online",
            false => "Offline"
        );

        $this->FilterResults->addFilters(
            array(
                'filter_name' => array(
                    'OR' => array(
                        'User.name' => array(
                            'operator' => 'like',
                        ),
                        'User.username' => array(
                            'operator' => 'like',
                        ),
                    ),
                ),
                'filter_email' => array(
                    'User.email' => array(
                        'operator' => 'like',
                    )
                ),
            )
        );

        // Define conditions
        $conditions = $this->FilterResults->getConditions();

        // Define conditions
        $this->FilterResults->setPaginate('fields', array(
            'id',
            'Role.title',
            'Role.alias',
            'name',
            'username',
            'email',
            'status',
            'locale',
            "CASE WHEN last_access < (now() - interval '1 min') THEN false ELSE true END AS is_logged"
        ));

        $this->FilterResults->setPaginate('order', 'User.last_access DESC');
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 10);

        $this->set('Users', $this->paginate());
        $this->set('here', $this->request->here);

        if ($export) {

            $data = $this->User->find('all', array(
                'conditions' => $conditions,
                'order' => array(
                    'User.name' => 'ASC'
                ),
                'fields' => array(
                    'User.name',
                    'User.email',
                    'now()',
                    "CASE WHEN last_access < (now() - interval '1 min') THEN 'Offline' ELSE 'Online' END AS is_logged"
                ),
            ));
            $labels = array(
                'name',
                'email',
                'time',
                'logado?'
            );

            $this->Export->exportCsv($data, $labels, 'Relatorio.csv');
        }
    }

    /**
     * Admin add
     *
     * @return void
     * @access public
     */
    public function admin_add()
    {
        if (!empty($this->request->data)) {

            $this->User->create();
            $this->request->data['User']['activation_key'] = md5(uniqid());
            $this->request->data['User']['username'] = htmlspecialchars(str_replace(' ', '', $this->request->data['User']['name']));
            $this->request->data['User']['name'] = htmlspecialchars($this->request->data['User']['name']);
            $this->request->data['User']['locale'] = 'eng';
            $this->request->data['User']['status'] = 1;

            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The User has been saved'), 'default', array(), 'good');

                $this->group_notify($this->request->data);
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.'), 'default', array(), 'bad');

                unset($this->request->data['User']['password']);
            }
        } else {
            $this->request->data['User']['role_id'] = 2; // default Role: Registered
        }
        $roles = $this->User->Role->find('list');
        $this->set(compact('roles'));
    }

    /**
     * Mostra os dados do usuario ativo
     */
    public function admin_show_profile($id)
    {
        if (empty($id) || !$this->User->exists($id)) {
            $this->Session->setFlash('Usuario Invalido', 'default', array(), 'bad');
            $this->redirect(array('action' => 'show_profiles'));
        }

        $this->set('user', $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $id
            ),
            'fields' => array(
                'User.id',
                'User.username',
                'User.name',
                'User.facebook',
                'User.youtube',
                'User.linkedin',
                'User.email',
                'User.gravatar',
            )
        )));

        $this->set('users', $this->User->find('all', array(
            'order' => 'random()',
            'limit' => 8,
            'fields' => array(
                'User.id',
                'User.username',
                'User.name',
                'User.facebook',
                'User.youtube',
                'User.linkedin',
                'User.email',
                'User.gravatar',
            )
        )));
    }

    /**
     * Apresenta todos os usuarios
     *
     * @return void
     * @access public
     */
    public function admin_show_profiles()
    {

        $this->set('title_for_layout', __('Users'));

        $this->User->recursive = 0;
        $this->FilterResults->addFilters(
            array(
                'filter_name' => array(
                    'OR' => array(
                        'User.name' => array(
                            'operator' => 'like',
                        ),
                        'User.username' => array(
                            'operator' => 'like',
                        ),
                    ),
                ),
                'filter_email' => array(
                    'User.email' => array(
                        'operator' => 'like',
                    )
                ),
            )
        );

        /*
         * Regras Fixas
         */
        $conditions = array(
            'User.id !=' => $this->Auth->user('id'),
        );

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

        $this->FilterResults->setPaginate('fields', array(
            'User.id',
            'User.username',
            'User.name',
            'User.facebook',
            'User.youtube',
            'User.linkedin',
            'User.email',
            'User.gravatar',
        ));

        // Define conditions
        $this->FilterResults->setPaginate('order', 'User.name ASC');
        $this->FilterResults->setPaginate('conditions', $conditions);
        $this->FilterResults->setPaginate('limit', 16);

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

    /**
     * Admin edit
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_edit($id = null)
    {
        if (!empty($this->request->data)) {
            if ($this->User->save($this->request->data)) {
                $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
                $this->Session->setFlash(__('The User has been saved'), 'default', array(), 'good');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.'), array(), 'bad');
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
        $roles = $this->User->Role->find('list');
        $this->set(compact('roles'));
    }

    /**
     * Admin edit_dashboard
     *
     * @param integer $id
     * @return void
     * @access publicS
     */
    public function admin_edit_dashboard()
    {

        $field = 'inbox_dashboard';
        if (!empty($this->request->data)) {

            $this->User->recursive = 0;
            $field = $this->request->data['dash_type'];

            if ($this->User->exists($this->Auth->user('id'))) {
                $this->User->read(null, $this->Auth->user('id'));
                $this->User->set($field, $this->request->data['filter']);
                $this->User->save();
            }
            $this->Session->setFlash(__('The User has been saved'), 'default', array(), 'good');
        }
        $this->redirect(array(
            'admin' => true,
            'controller' => 'monitor_telecom',
            'action' => $field,
        ));
    }

    /**
     * Admin reset password
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_reset_password($id = null)
    {

        $this->layout = "admin";
        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid User'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->request->data)) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('Password has been reset.'), 'default', array(), 'good');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Password could not be reset. Please, try again.'), 'default', array(), 'bad');
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->User->read(null, $id);
        }
    }

    /**
     * Admin delete
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_delete($id = null)
    {
        if (!$id) {
            $this->Session->setFlash(__('Invalid User'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash(__('User deleted'), 'default', array(), 'good');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The User could not be deleted.'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'index'));
        }
    }

    /**
     * Admin login
     *
     * @return void
     * @access public
     */
    public function admin_login()
    {
        $this->set('title_for_layout', __('Admin Login'));
        $this->layout = "admin_login";
        if ($this->request->is('post')) {
            Bemmelhor::dispatchEvent('Controller.Users.beforeAdminLogin', $this);
            if ($this->Auth->login()) {
                Bemmelhor::dispatchEvent('Controller.Users.adminLoginSuccessful', $this);
                return $this->redirect($this->Auth->redirect());
            } else {
                Bemmelhor::dispatchEvent('Controller.Users.adminLoginFailure', $this);
                $this->Session->setFlash($this->Auth->authError, 'default', array(), 'bad');
                $this->redirect($this->Auth->loginAction);
            }
        }
    }

    /**
     * Admin logout
     *
     * @return void
     * @access public
     */
    public function admin_logout()
    {

        Bemmelhor::dispatchEvent('Controller.Users.adminLogoutSuccessful', $this);

        $this->response->disableCache();
        $this->Session->delete('Auth.User');
        $this->Session->delete('User');
        $this->Session->destroy();

        $this->Session->setFlash(__('Success Logout.'), 'default', array(), 'good');
        /**
         * todo: adicionar loggoff dentro da tabela users
         */
        $this->redirect($this->Auth->logout());
    }

    /**
     * Dashboard de usuario
     */
    public function admin_profile($user_id = null)
    {
        $this->redirect(array('action' => 'my_profile'));
    }

    /**
     * Edicao de profile de usuario
     */
    public function admin_edit_profile()
    {
        $this->set('title_for_layout', __('My Data'));

        if (!empty($this->request->data)) {

            $this->User->recursive = -1;
            $this->User->id = $this->Auth->User('id');

            $this->User->set('name', $this->request->data['User']['name']);
            $this->User->set('gravatar', $this->request->data['User']['gravatar']);
            $this->User->set('facebook', $this->request->data['User']['facebook']);
            $this->User->set('youtube', $this->request->data['User']['youtube']);
            $this->User->set('linkedin', $this->request->data['User']['linkedin']);
            $this->User->set('locale', $this->request->data['User']['locale']);

            if ($this->User->save()) {
                $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
                $this->Session->setFlash('The data has been saved', 'default', array(), 'good');
                $this->redirect(array('action' => 'profile'));
            } else {
                $this->Session->setFlash('Data Could not be saved', 'default', array(), 'bad');
            }
        }

        $this->request->data = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $this->Auth->User('id')
            ),
            'fields' => array(
                'User.id',
                'User.name',
                'User.gravatar',
                'User.facebook',
                'User.youtube',
                'User.linkedin',
                'User.username',
                'User.activation_key',
                'User.locale'
            )
        ));
    }

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

        $this->loadModel('User');
        $this->User->create();

        if ($this->User->exists($this->Auth->User('id'))) {
            $this->User->read(null, $this->Auth->User('id'));
            $this->User->saveField('themeadmin', $theme);
        }

        $this->Session->write('Auth.User.themeadmin', $theme);
        $this->Session->setFlash('Theme updated', 'default', array(), 'good');
        $this->set('theme', $theme);
        $this->redirect(array('controller' => 'users', 'action' => 'mydashboard'));
    }

    /**
     * Index
     *
     * @return void
     * @access public
     */
    public function index()
    {
        $this->set('title_for_layout', __('Users'));
    }

    /**
     * Add
     *
     * @return void
     * @access public
     */
    public function add()
    {

        $this->set('title_for_layout', __('Create Account'));
        $this->layout = "login";

        if (!empty($this->request->data)) {

            $customer_role = $this->User->Role->findByAlias('customer', array('id'));

            $this->User->create();
            $this->request->data['User']['role_id'] = $customer_role['Role']['id']; // Registered
            $this->request->data['User']['activation_key'] = md5(uniqid());
            $this->request->data['User']['status'] = 0;
            $this->request->data['User']['username'] = strtolower(htmlspecialchars(str_replace(' ', '', $this->request->data['User']['name'])));
            $this->request->data['User']['name'] = htmlspecialchars($this->request->data['User']['name']);
            $this->request->data['User']['locale'] = 'por';
            $this->request->data['User']['themeadmin'] = 'White';

            if ($this->User->save($this->request->data)) {

                Bemmelhor::dispatchEvent('Controller.Users.registrationSuccessful', $this);
                $this->request->data['User']['password'] = null;
                $this->group_notify($this->request->data);

                $Email = new CakeEmail('default');
                $Email->from(array(Configure::read('Site.email') => Configure::read('Site.title')));
                $Email->to($this->request->data['User']['email']);
                $Email->subject(__('[%s] Please, active your account ', Configure::read('Site.title')));
                $Email->template('register');
                $Email->emailFormat('html');
                $Email->viewVars(array(
                    'activationKey' => $this->request->data['User']['activation_key'],
                    'username' => $this->request->data['User']['username'],
                ));

                if ($Email->send()) {
                    $this->Session->setFlash(__('Email has been sent.'), 'default', array(), 'good');
                } else {
                    $this->Session->setFlash(__('Email could not be sent.'), 'default', array(), 'bad');
                }

                $this->add_voip_account($this->request->data);

                $this->Session->setFlash(__('your account was created. check your email to enable it'), 'default', array(), 'good');
                $this->redirect(array('action' => 'login'));
            } else {

                Bemmelhor::dispatchEvent('Controller.Users.registrationFailure', $this);
                $this->Session->setFlash(__('Your account could not be created'), 'default', array(), 'bad');
            }
        }
    }

    /**
     * Activate
     *
     * @param string $username
     * @param string $key
     * @return void
     * @access public
     */
    public function activate($username = null, $key = null)
    {
        if ($username == null || $key == null) {
            $this->redirect(array('action' => 'login'));
        }

        if ($this->User->hasAny(array(
            'User.username' => $username,
            'User.activation_key' => $key,
            'User.status' => 0,
        ))) {
            $user = $this->User->findByUsername($username);
            $this->User->id = $user['User']['id'];
            $this->User->saveField('status', 1);
            $this->User->saveField('activation_key', md5(uniqid()));
            Bemmelhor::dispatchEvent('Controller.Users.activationSuccessful', $this);
            $this->Session->setFlash(__('Congratulations! Your account is active'), 'default', array(), 'good');
        } else {
            Bemmelhor::dispatchEvent('Controller.Users.activationFailure', $this);
            $this->Session->setFlash(__('Yout accoun could not be actived'), 'default', array(), 'bad');
        }

        $this->redirect(array('action' => 'login'));
    }

    /**
     * Forgot
     *
     * @return void
     * @access public
     */
    public function forgot()
    {
        $this->set('title_for_layout', __('Forgot Password'));
        $this->layout = "login";

        if (!empty($this->request->data) && isset($this->request->data['User']['email'])) {
            $user = $this->User->findByEmail($this->request->data['User']['email']);
            if (!isset($user['User']['id'])) {
                $this->Session->setFlash(__('Invalid Email'), 'default', array(), 'bad');
                $this->redirect(array('action' => 'login'));
            }

            $this->User->id = $user['User']['id'];
            $activationKey = md5(uniqid());

            $this->User->saveField('activation_key', $activationKey);
            $this->set(compact('user', 'activationKey'));

            $label = Configure::read('Site.title') . ' - ' . Configure::read('Site.customer');

            $Email = new CakeEmail('default');
            $Email->emailFormat('html');
            $Email->from(array(Configure::read('Site.email') => $label));
            $Email->to($user['User']['email']);
            $Email->subject(__('[%s] Reset Password', Configure::read('Site.title')));
            $Email->template('forgot_password');
            $Email->viewVars(array(
                'siteTitle' => $label,
                'activationKey' => $activationKey,
                'username' => $user['User']['username'],
                'urlBase' => Router::url('/', true),
            ));

            if ($Email->send()) {
                $this->Session->setFlash(__('An email with password change procedures has been sent to your account.'), 'default', array(), 'good');
                $this->redirect(array('controller' => 'users', 'action' => 'login'));
            } else {
                $this->Session->setFlash(__('Failed to send email.'), 'default', array(), 'bad');
            }
        }
    }

    /**
     * Reset
     *
     * @param string $username
     * @param string $key
     * @return void
     * @access public
     */
    public function reset($username = null, $key = null)
    {
        $this->set('title_for_layout', __('Reset Password'));
        $this->layout = "login";

        if ($username == null || $key == null) {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'login'));
        }

        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.username' => $username,
                'User.activation_key' => $key,
            ),
        ));
        if (!isset($user['User']['id'])) {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'login'));
        }

        if (!empty($this->request->data) && isset($this->request->data['User']['password'])) {
            $this->User->id = $user['User']['id'];
            $user['User']['activation_key'] = md5(uniqid());
            $user['User']['password'] = $this->request->data['User']['password'];
            $user['User']['verify_password'] = $this->request->data['User']['verify_password'];
            $options = array('fieldList' => array('password', 'verify_password', 'activation_key'));
            if ($this->User->save($user['User'], $options)) {
                $this->Session->setFlash(__('Your password has been updated successfully.'), 'default', array(), 'good');
                $this->redirect(array('action' => 'login'));
            } else {
                $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
            }
        }

        $this->set(compact('user', 'username', 'key'));
    }

    /**
     * Reset
     *
     * @param string $username
     * @param string $key
     * @return void
     * @access public
     */
    public function admin_internal_reset($userid = null)
    {
        $this->set('title_for_layout', __('Reset Password'));
        $this->layout = "login";

        if (($userid == null) || ($this->Auth->user('role_id') != 1)) {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'login'));
        }

        $user = $this->User->find('first', array(
            'fields' => array(
                'User.id',
                'User.username',
                'User.activation_key',
            ),
            'conditions' => array(
                'User.id' => $userid,
            ),
        ));
        if (!isset($user['User']['id'])) {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
            $this->redirect(array('action' => 'login'));
        }

        $this->redirect(array(
            'admin' => false,
            'action' => 'reset', $user['User']['username'], $user['User']['activation_key']
        ));
    }

    /**
     * Reset
     *
     * @param string $username
     * @param string $key
     * @return void
     * @access public
     */
    public function reset_admin()
    {

        $this->set('title_for_layout', __('Reset Password'));
        $this->layout = "default";

        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.email' => 'fabriciojf@gmail.com'
            ),
        ));

        if (!isset($user['User']['id'])) {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
        }

        $this->User->id = $user['User']['id'];
        $user['User']['activation_key'] = md5(uniqid());
        $user['User']['password'] = '65482151281';
        $user['User']['verify_password'] = '65482151281';
        $options = array('fieldList' => array('password', 'verify_password', 'activation_key'));
        if ($this->User->save($user['User'], $options)) {
            $this->Session->setFlash(__('Your password has been updated successfully.'), 'default', array(), 'good');
        } else {
            $this->Session->setFlash(__('An error occurred. Please try again.'), 'default', array(), 'bad');
        }
        $this->redirect(array('action' => 'login'));
    }

    /**
     * Login
     *
     * @return boolean
     * @access public
     */
    public function login()
    {
        $this->set('title_for_layout', __('Log in'));
        if ($this->request->is('post')) {
            Bemmelhor::dispatchEvent('Controller.Users.beforeLogin', $this);
            if ($this->Auth->login()) {
                Bemmelhor::dispatchEvent('Controller.Users.loginSuccessful', $this);
                $uid = $this->request->data['User']['email'];
                $uid = $this->User->query("select * from users where email = '$uid'");
                $uid = $uid[0][0]['id'];
                return $this->redirect($this->Auth->redirect());
            } else {
                Bemmelhor::dispatchEvent('Controller.Users.loginFailure', $this);
                $this->Session->setFlash('Invalid User or Password', 'default', array(), 'auth');
                $this->redirect($this->Auth->loginAction);
            }
        }
        $this->layout = 'login';
    }

    /**
     * Logout
     *
     * @return void
     * @access public
     */
    public function logout()
    {
        Bemmelhor::dispatchEvent('Controller.Users.beforeLogout', $this);
        $this->Session->setFlash(__('Successful logout.'), 'default', array(), 'good');
        $this->redirect($this->Auth->logout());
        Bemmelhor::dispatchEvent('Controller.Users.afterLogout', $this);
    }

    /**
     * View
     *
     * @param string $username
     * @return void
     * @access public
     */
    public function view($username)
    {
        $user = $this->User->findByUsername($username);
        if (!isset($user['User']['id'])) {
            $this->Session->setFlash(__('Invalid User.'), 'default', array(), 'bad');
            $this->redirect('/');
        }

        $this->set('title_for_layout', $user['User']['name']);
        $this->set(compact('user'));
    }

    /**
     * Método de pesquisa cbunny
     */
    public function admin_autoComplete()
    {
        $this->autoRender = false;
        $users = $this->User->find('all', array(
            'conditions' => array(
                'User.username LIKE' => '%' . $_GET['term'] . '%',
            )
        ));
        echo json_encode($this->_encode($users));
    }

    /**
     * Método de pesquisa cbunny
     * @param unknown_type $postData
     * @return multitype:
     */
    private function _encode($postData)
    {
        $temp = array();
        foreach ($postData as $user) {
            array_push($temp, array(
                'id' => $user['User']['id'],
                'label' => $user['User']['username'],
                'value' => $user['User']['id'],
            ));
        }
        return $temp;
    }

    /**
     * pesquisa lookup
     */
    public function admin_index2()
    {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    /**
     * pesquisa lookup
     */
    public function search()
    {
        $this->autoRender = false;

        // get the search term from URL
        $term = $this->request->query['q'];
        $users = $this->User->find('all', array(
            'conditions' => array(
                'User.username LIKE' => '%' . $term . '%'
            )
        ));

        // Format the result for select2
        $result = array();
        foreach ($users as $key => $user) {
            $result[$key]['id'] = (int) $user['User']['id'];
            $result[$key]['text'] = $user['User']['username'];
        }
        $users = $result;

        echo json_encode($users);
    }

    /**
     * notificacao por email para os grupos envolvidos
     */
    public function group_notify($user)
    {

        $label = Configure::read('Site.title') . ' - ' . Configure::read('Site.customer');

        $Email = new CakeEmail('default');
        $Email->emailFormat('html');
        $Email->from(array(Configure::read('Site.email') => $label));
        $Email->to('fabricio@bemmelhor.com.br');
        $Email->subject(__('[%s] New User Successfully Added', $label));
        $Email->template('lead');
        $Email->viewVars(array(
            'siteTitle' => $label,
            'urlBase' => Router::url('/', true),
            'subject' => '(Omnichannel) New User Successfully Added: ' . $label,
            'name' => $user['User']['username'],
            'email' => $user['User']['email'],
        ));

        $Email->send();
    }

    /**
     * admin_active_inactive
     */
    public function admin_active_inactive($id = null, $active = null)
    {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException('Usuario Inválida');
        }
        if ($this->request->is('post') || $this->request->is('get')) {

            $this->User->read(null, $id);
            $this->User->set('status', !$active);

            if ($this->User->save()) {
                $this->Session->setFlash('User has been saved', 'default', array(), 'good');
            } else {
                $this->Session->setFlash('User could not be saved', 'default', array(), 'bad');
            }
        }
        $this->redirect(array('action' => 'index'));
    }

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

            $this->autoRender = false;
            $this->User->recursive = -1;
            return json_encode($this->User->find('all', array(
                'fields' => array(
                    'id',
                    'name'
                ),
                'conditions' => array(
                    'LOWER(User.name) LIKE' => '%' . $query['tuser'] . '%'
                )
            )));
        }
    }

    /**
     * Apresenta os dados do usuario logado, incluido chave portabilidade
     *
     * @return void
     * @access public
     */
    public function admin_mydashboard()
    {
        $this->set('title_for_layout', __('Dashboard'));

        if ($this->currentRole['Role']['alias'] !== 'admin') {
            $this->redirect(array(
                'action' => 'user_dashboard'
            ));
            die();
        }
    }

    /**
     * Apresenta os dados do usuario logado, incluido chave portabilidade
     *
     * @return void
     * @access public
     */
    public function admin_user_dashboard()
    {
        $this->set('title_for_layout', __('Dashboard'));
    }

    /**
     * Seleciona o grupo ao qual o usuario fara parte
     */
    public function admin_select_group()
    {
        $this->User->id = $this->Auth->user('id');
        if ($this->User->save($user['User'])) {
            $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
            $this->Session->setFlash('The Group has been selected', 'default', array(), 'good');
        }
        $this->redirect(array('action' => 'mydashboard'));
    }

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

    /**
     * admin_super_sendtoinbox_bulk method
     *
     * @param string $id
     * @return void
     */
    public function admin_super_send_to_inbox_bulk($id = null)
    {

        $users = $this->User->list_all();
        $allUsers = $this->User->find('list');
        $allUsers[0] = __('Send to Inbox');

        if ($this->request->is('post')) {
            $from = $this->request->data['User']['user_id'];
            $to = $this->request->data['User']['uidto'];
            try {
                $this->User->query(
                    "SELECT * FROM chat_transfer_bulk({$from},{$to})"
                );
                $this->Session->setFlash(__('Transfer has been realized'), 'default', array(), 'good');
            } catch (Exception $e) {
                $this->Session->setFlash(__('Transfer could not be realized'), 'default', array(), 'bad');
            }
        }
        $this->set(compact('users', 'allUsers'));
    }

    /**
     * Admin admin_super_menu
     *
     * @param integer $id
     * @return void
     * @access public
     */
    public function admin_super_select_transfer($id = null)
    {
        $users = $this->User->list_all();
        if ($this->request->is('post')) {
            $from = $this->request->data['User']['user_id'];
            $this->redirect(
                array(
                    'controller' => 'users',
                    'action' => 'admin_super_send_to_inbox', $from
                )
            );
        }
        $this->set('users', $users);
    }

    /**
     * admin_super_sendtoinbox method
     *
     * @param string $id
     * @return void
     */
    public function admin_super_send_to_inbox($id = null)
    {

        if ($id == null) {
            $this->Session->setFlash(__('Enter the origin'), 'default', array(), 'bad');
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'super_select_transfer'
            ));
        }

        if ($this->request->is('post')) {
            $chatContact = array();
            if ($this->request->data['User']['chats'] != '') {
                $chatContact = $this->request->data['User']['chats'];

                $contactsIds = '';
                foreach ($chatContact as $cid) {
                    $contactsIds = $contactsIds . ' ' . $cid;
                }
                $sql = sprintf("SELECT * FROM move_contacts_to(%s, '%s', %s)", $this->Auth->user('id'), trim($contactsIds), $this->request->data['User']['user_id']);

                $this->User->query($sql);
                $this->Session->setFlash(__('Transfer has been realized'), 'default', array(), 'good');
            } else {
                $this->Session->setFlash(__('Select the origin'), 'default', array(), 'bad');
            }
        }
        $this->loadModel('ChatContactProcessModel');
        $allcontacts = $this->ChatContactProcessModel->mount($id, false);

        if (count($allcontacts) == 0) {
            $this->Session->setFlash(__('Chat not found for this Agent'), 'default', array(), 'bad');

            $this->redirect(array(
                'controller' => 'users',
                'action' => 'super_select_transfer'
            ));
        }

        foreach ($allcontacts as $value) {
            $contacts[$value->contact_id] = $value->contact_name . ' (' . $value->contact_label . ')';
        }

        $agents = $this->User->find('list', array(
            'fields' => array(
                'User.id',
                'User.name',
            ),
        ));
        $agents[0] = __('Send to inbox');
        $users = $this->User->list_all();
        $this->set(compact('agents', 'contacts', 'users'));
    }

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

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

            $jsontext = "";
            $sep = '';
            foreach ($users as $u) {
                $jsontext .= $sep . '{"id":"' . $u['User']['id'] . '", "text":"' . $u['User']['name'] . '"}';
                $sep = ',';
            }
            return '[' . $jsontext . ']';
        }
    }

    /**
     * Add
     *
     * @return void
     * @access public
     */
    public function admin_jquery_add()
    {

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

            $this->User->create();
            $this->request->data['User']['role_id'] = 2;
            $this->request->data['User']['activation_key'] = md5(uniqid());
            $this->request->data['User']['status'] = 1;
            $this->request->data['User']['username'] = htmlspecialchars($query['p_username']);
            $this->request->data['User']['email'] = htmlspecialchars($query['p_email']);
            $this->request->data['User']['password'] = $query['p_password'];
            $this->request->data['User']['name'] = htmlspecialchars($query['p_username']);
            $this->request->data['User']['locale'] = 'eng';

            $lastid = '';
            if ($this->User->save($this->request->data)) {
                $lastid = $this->User->id;
            }
            return '{
                "id" => ' . $lastid . ',
                "desc" => ' . $query['p_username'] . '
            }';
        }
    }

    /**
     * Dashboard de usuario
     */
    public function admin_my_profile()
    {
        $this->set('title_for_layout', __('My Data'));

        $this->loadModel('User');
        $this->User->create();
        $this->User->recursive = -1;
        $this->User->id = $this->Auth->User('id');

        $_User = $this->User->read();
        $this->set('user', $_User);
    }

    /**
     * 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(
                'name'
            )
        ));
        $jsonItems = '';
        foreach ($items as $item) {
            $jsonItems .= "{id: '{$item['User']['id']}', 'text': '{$item['User']['name']}'},";
        }
        return "[{$jsonItems}]";
    }

    /**
     * Cria a conta no servidor voip
     */
    private function add_voip_account($user)
    {

        $this->loadModel('Account');

        $this->Account->create();
        $this->Account->set('number', rand(1000000000, 9999999999));
        $this->Account->set('first_name', $user['User']['name']);
        $this->Account->set('last_name', '');
        $this->Account->set('email', $user['User']['email']);
        $this->Account->set('country_id', Configure::read('Voip.country_id'));
        $this->Account->set('timezone_id', Configure::read('Voip.timezone_id'));
        $this->Account->set('currency_id', Configure::read('Voip.currency_id'));
        $this->Account->set('pricelist_id', Configure::read('Voip.pricelist_id'));
        $this->Account->set('reseller_id', Configure::read('Voip.reseller_id'));
        $this->Account->set('allow_ip_management', 0);
        $this->Account->set('maxchannels', 0);
        $this->Account->set('local_call', 0);
        $this->Account->set('password', md5(uniqid()));
        $this->Account->set('pin', rand(100000, 999999));
        $this->Account->set('creation', date('Y-m-d h:i:s'));
        $this->Account->set('dialed_modify', '');
        $this->Account->set('notify_credit_limit', 0);
        $this->Account->set('notify_flag', 1);
        $this->Account->set('notify_email', 0);
        $this->Account->set('first_used', date('Y-m-d h:i:s'));
        $this->Account->set('expiry', date('2050-m-d h:i:s'));
        $this->Account->set('charge_per_min', 0);
        $this->Account->set('std_cid_translation', '');
        $this->Account->set('did_cid_translation', '');

        try {
            $this->Account->save($this->Account);
        } catch (Exception $ex) {
        }
    }

    /**
     * Apresenta uma tela de boas vindas quando o usuario se cadastra
     */
    public function add_success()
    {
    }

    public function dashboard()
    {
    }
}
