<?php

App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::uses('ApiHelper', 'View/Helper');
App::uses('BemmelhorRestAPI', 'Lib/Api');
App::uses('HttpSocket', 'Network/Http');

/**
 * Suporte Controller
 *
 * @property PaginatorComponent $Paginator
 * @property SessionComponent $Session
 */
class SuporteController extends AppController {

    public $helpers = array(
        'Ajax',
        'Api',
    );
    public $components = array(
        'Email',
        'Export.Export'
    );

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

    /**
     * admin_index method
     *
     * @return void
     */
    public function admin_index() {

    }

    /**
     * Apresenta os icones do bootstrap presentes no package atual
     */
    public function admin_icons() {
        $this->set('title_for_layout', 'Glyph Icons Package');
    }

    public function admin_fontawesome() {
        $this->set('title_for_layout', 'Font Awesome Package');
    }

    public function admin_ionicons() {
        $this->set('title_for_layout', 'Ion Icons Package)');
    }

    public function admin_bemmelhor() {
        $this->set('title_for_layout', __('About Bemmelhor SI'));
    }

    public function admin_simulewhatsapp() {

        $this->loadModel('Chat');

        $this->Chat->create();
        $this->Chat->set('account', $this->Auth->user('group_uniqueid'));
        $this->Chat->set('message_type', 'whatsapp');
        $this->Chat->set('user_from', $this->Auth->user('id'));
        $this->Chat->set('user_to', 7810);
        $this->Chat->set('contact_reply', '+5532991072993');
        $this->Chat->set('message', 'teste');
        $this->Chat->save($this->Chat);

        $this->Session->setFlash('Simulação executada!', 'default', array(), 'good');

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

    public function admin_app_news() {
        //Request data via CURL
        $url = 'http://www.bemmelhor.com.br/site/app_news/notes/omnichannel ';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $output = trim(curl_exec($ch));
        curl_close($ch);
        $this->set('news', json_decode($output));
    }

    /**
     * admin_about method
     *
     * @return void
     */
    public function admin_about() {
        $this->set('title_for_layout', __('About System'));

        $this->loadModel('Version');
        $versions = $this->Version->find('all');

        $db = ConnectionManager::getDataSource('default');

        $database_info = array(
            'name' => $db->config['database'],
            'host' => $db->config['host'],
            'encoding' => $db->config['encoding'],
            'datasource' => $db->config['datasource']
        );
        $this->set('database', $database_info);
        $this->set(compact('versions'));

        $db = ConnectionManager::getDataSource('default');
        $this->set(compact('versions'));
        $this->set('omnirest', Configure::read('Omnichannel.whatsapp_host'));
        $this->set('chat_io', Configure::read('Omnichannel.chatio_host'));
        $this->set('file_path', Configure::read('Omnichannel.path_upload_omnirest'));
    }

    public function admin_get_users() {
        $sql = 'insert into users (%s) values (%s);';
        $this->loadModel('User');

        $allfields = array_keys($this->User->getColumnTypes());
        $types = $this->User->getColumnTypes();

        $users = $this->User->find('all');
        foreach ($users as $u) {
            $values = '';
            $columns = '';
            $sep = '';
            foreach ($allfields as $fd) {
                if ($u['User'][$fd] != '') {
                    $columns .= "{$sep}{$fd}";
                    if ($types[$fd] == 'integer') {
                        $values .= "{$sep}{$u['User'][$fd]}";
                    } else if (($types[$fd] == 'string') ||
                            ($types[$fd] == 'text') ||
                            ($types[$fd] == 'datetime')) {
                        $values .= "{$sep}'{$u['User'][$fd]}'";
                    }
                    $sep = ',';
                }
            }
            debug(sprintf($sql, $columns, $values));
        }

        exit(0);
    }

    /**
     * function to clear all cache data
     * by default accessible only for admin
     *
     * @access Public
     * @return void
     */
    public function admin_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

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

        if (function_exists('apc_clear_cache')) {
            apc_clear_cache();
            apc_clear_cache('user');
        }

        $this->Session->setFlash('Limpeza realizada com sucesso!', 'default', array(), 'good');
    }

    /**
     * Verifica se alguma partição está estourando espaço
     */
    public function disk_space() {
        $this->autoRender = false;
        $this->response->type('json');

        $limitAceitavel = 93;

        $warning = false;
        $warningValue = array();

        $output = shell_exec('df -h');
        $quebra = explode(" ", $output);

        foreach ($quebra as $item) {
            if ((trim($item) != '') && (strpos($item, '%') !== false)) {
                $value = str_replace('%', '', $item);
                if ($value > $limitAceitavel) {
                    $warning = true;
                    $warningValue[] = $item;
                }
            }
        }

        if ($warning) {

            $commands = array(
                'ifconfig' => shell_exec('ifconfig'),
                'uname' => shell_exec('uname -a'),
                'hostname' => shell_exec('cat /etc/hostname')
            );

            $Email = new CakeEmail('default');
            $Email->emailFormat('html');
            $Email->from(array('bmmailersite@gmail.com' => Configure::read('Site.title')));
            $Email->to('fabriciojf@gmail.com');
            $Email->addCc('suporte@bemmelhor.com.br');
            $Email->subject(__('[%s] Warning: Espaço Estourando', Configure::read('Site.customer')));
            $Email->template('diskspace');
            $Email->viewVars(array(
                'subject' => 'Novo Lead Criado no Sistema ' . Configure::read('Site.title'),
                'customer' => Configure::read('Site.customer'),
                'diskspace' => $output,
                'datas' => $commands,
            ));
            $Email->send();
        }

        $this->response->body(json_encode($warningValue));
    }

    /**
     * Verifica se alguma partição está estourando espaço
     */
    public function admin_disk_space() {

        $output = shell_exec('df -h');
        $this->set('output', $output);
    }

    /**
     * Exporta as permissoes setadas no ambiente
     */
    public function admin_permissions_export() {
        $this->set('title_for_layout', __('Permissions Export'));

        $this->loadModel('Version');
        $permissions = $this->Version->query('SELECT * FROM get_cake_permissions()');

        $labels = array(
            'permission_role',
            'permission_controller',
            'permission_action',
            'permission_create',
            'permission_read',
            'permission_delete',
            'permission_update'
        );

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

    /**
     * Exporta as permissoes vindas de um arquivo csv
     */
    public function admin_permissions_import() {
        $this->set('title_for_layout', __('Permissions Import'));

        if ($this->request->is('post')) {
            $filename = $this->request->data['suporte']['document']['name'];
            $tmpname = $this->request->data['suporte']['document']['tmp_name'];
            if (($filename == null) || (trim($filename) == "")) {
                $this->Session->setFlash(__('Select a valid File'), 'default', array(), 'bad');
            } else {

                $this->reset_permissions();

                $this->loadModel('Version');
                $filedata_oficial = WWW_ROOT . 'imports/' . $filename;

                move_uploaded_file($tmpname, $filedata_oficial);
                chmod($filedata_oficial, 0777);

                $file = fopen($filedata_oficial, "r");
                while (($line = fgetcsv($file, 1000, ";")) !== false) {
                    if ($line[0] == 'permission_role') {
                        continue;
                    }
                    $sql = sprintf(
                            "SELECT * FROM import_cake_permissions('%s', '%s', '%s', '%s')", $line[0], $line[1], $line[2], $line[3]
                    );
                    $this->Version->query($sql);
                }
                fclose($file);

                $this->Session->setFlash(__('Permissions Updated!'), 'default', array(), 'good');
            }
        }
    }

    /**
     * Reseta as sequencias dentro do banco de dados
     */
    public function admin_reset_sequences() {
        $this->loadModel('Version');
        $this->Version->query('SELECT * FROM update_sequence()');

        $this->Session->setFlash(__('Sequences Updated!'), 'default', array(), 'good');

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

    /**
     * Simula uma mensagem de whatsapp para teste
     */
    public function admin_simule_whatsapp_message() {

        $contact_number = '0000000000001';

        if ($this->request->is('post')) {
            $contact_number = $this->request->data['contact_number'];
            $message_body = $this->request->data['message_body'];
            $message_hash = md5(date('Y-m-d H:i:s'));

            $message = array(
                "Status" => null,
                "Outcomings" => null,
                "Messages" => array(
                    array(
                        "MessageId" => null,
                        "Body" => $message_body,
                        "ContactLabel" => "Simulated Message",
                        "ContactNumber" => $contact_number,
                        "Account" => $this->Auth->user('group_uniqueid'),
                        "Created" => date('Y-m-d H:i'),
                        "ContentType" => null,
                        "Ordernation" => 0,
                        "FileOriginalName" => "text",
                        "FileNameWithoutExtension" => "text",
                        "FileNameWithExtension" => "text",
                        "FileExtension" => "",
                        "FileHash" => "1C-B2-51-EC-0D-56-8D-E6-A9-29-B5-20-C4-AE-D8-D1",
                        "TypeFileKey" => "",
                        "LabelDate" => "[15:29, 7/8/2019",
                        "LabelHour" => "15:29",
                        "DataPrePlainText" => "[15:29, 7/8/2019] Fabricio Bem Melhor",
                        "TypeEnum" => "text",
                        "IoEnum" => "in",
                        "FilePathWithExtension" => "C:\\Omnichannel\\Downloads\\text",
                        "CleanFileName" => "text",
                        "HashMessage" => $message_hash
                    )
                )
            );

            /**
             * Notifica alteracao na caixa de entrada
             */
            try {
                $this->loadModel('MessageRest');
                $this->dump_app($this->MessageRest->addMessagesRestURI);

                $HttpNotify = new HttpSocket();
                $HttpNotify->post(
                        $this->MessageRest->addMessagesRestURI, $message);
            } catch (Exception $e) {

            }

            $this->Session->setFlash(__("Success"), 'default', array(), 'good');
        }
        $this->set('contact_number', $contact_number);
    }

    /**
     * Reseta as permissions para o default
     */
    public function reset_permissions() {

        $this->loadModel('Aro');
        $this->loadModel('Aco');
        $this->loadModel('Role');
        $this->loadModel('ArosAco');
        $this->loadModel('User');

        $this->Aro->deleteAll(array('id > ' => '0'), true);
        $this->Aro->query('DELETE FROM aros_acos');

        echo 'Tabelas Aros e ArosAcos Limpas';

        $acos = $this->Aco->find('all');
        $roles = $this->Role->find('all');
        foreach ($roles as $role) {
            $this->Aro->create();
            $aro = $this->Aro->save(array(
                'model' => 'Role',
                'foreign_key' => $role['Role']['id'],
                'alias' => $role['Role']['alias'],
                'parent' => 'parent_ARO_alias'
            ));

            if ($role['Role']['alias'] == 'admin') {
                foreach ($acos as $aco) {
                    $this->ArosAco->create();
                    $this->ArosAco->save(array(
                        '_create' => '1',
                        '_delete' => '1',
                        '_read' => '1',
                        '_update' => '1',
                        'aco_id' => $aco['Aco']['id'],
                        'aro_id' => $aro['Aro']['id'],
                    ));
                }
                echo '     Permissões para Role Admin Criadas';
            } else {
                foreach ($acos as $aco) {
                    $this->ArosAco->create();
                    $this->ArosAco->save(array(
                        '_create' => '0',
                        '_delete' => '0',
                        '_read' => '0',
                        '_update' => '0',
                        'aco_id' => $aco['Aco']['id'],
                        'aro_id' => $aro['Aro']['id'],
                    ));
                }

                echo "     Permissões para Role {$role['Role']['alias']} Criadas";
            }
        }

        $users = $this->User->find('all');
        foreach ($users as $user) {
            $this->Aro->create();
            $aro = $this->Aro->save(array(
                'model' => 'User',
                'foreign_key' => $user['User']['id'],
                'alias' => $user['User']['name'],
                'parent' => 'parent_ARO_alias'
            ));
            foreach ($acos as $aco) {
                $this->ArosAco->create();
                $this->ArosAco->save(array(
                    '_create' => '0',
                    '_delete' => '0',
                    '_read' => '0',
                    '_update' => '0',
                    'aco_id' => $aco['Aco']['id'],
                    'aro_id' => $aro['Aro']['id'],
                ));
            }
            echo "     Permissões para User {$user['User']['name']} Criadas";
        }

        echo 'Done';
    }

    /**
     * Envia os modelos de templates criados no sistema
     */
    public function admin_send_mail_model() {

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

            $email = $this->request->data['email'];
            $template = $this->request->data['template'];

            if ((trim($email) == '') || (trim($template) == '')) {
                throw new NotFoundException(__('Type a valid mail'));
            }

            $Email = new CakeEmail('default');
            $Email->from(array(Configure::read('Site.email') => Configure::read('Site.title')));
            $Email->to($email);
            $Email->subject(__('Test mail template'));
            $Email->template($template);
            $Email->emailFormat('html');
            $Email->viewVars(array(
                'activationKey' => 'activation_key',
                'username' => 'username',
                'siteTitle' => Configure::read('Site.title'),
                'urlBase' => Router::url('/', true),
                'subject' => __('Test mail template'),
                'name' => $this->Auth->user('name'),
                'email' => $this->Auth->user('email'),
            ));

            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');
            }
        }
    }

    function admin_extra_translates() {
        echo __('Sip Password');
        echo __('Sip Number');
        echo __('Name / Extension');
        echo __('CallerId');
        echo __('Company Name');
        echo __('Record Calls');
        echo __('Notify Credit Limit');
        echo __('Item Amount');
        echo __('Reference');
        echo __('see more');
        echo __('');
        echo __('');
        echo __('');
        echo __('');
    }

}
