<?php

App::uses('AppHelper', 'View/Helper');

/**
 * Custom Helper
 *
 * For custom theme specific methods.
 *
 * If your theme requires custom methods,
 * copy this file to /app/views/themed/your_theme_alias/helpers/custom.php and modify.
 *
 * You can then use this helper from your theme's views using $custom variable.
 *
 * @category Helper
 * @package  Bemmelhor
 * @version  1.0
 * @author   Fabricio S Costa <fabriciojf@gmail.com>
 *
 * @link     http://www.bemmelhor.org
 */
class IntegrationHelper extends AppHelper {

    /**
     * Other helpers used by this helper
     *
     * @var array
     * @access public
     */
    public $helpers = array(
        'Session',
    );

    /**
     * Adiciona um cliente ao preditivo
     */
    public static function agentConnect() {
        $url = sprintf('%s/bmtelecom/predictive/agent/connect/%s/0991072993',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'));
        $response = IntegrationHelper::getCurl($url, 'GET');
        return $response;
    }

    /**
     * Conecta o agente ao sistema
     * @param unknown_type $sip
     */
    public static function agentLogin($sip) {
        $url = sprintf('%s/bmtelecom/predictive/agent/login/%s/%s/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                trim($sip), trim($sip));
        $response = IntegrationHelper::getCurl($url, 'PUT');
        return $response;
    }

    /**
     * Desconecta o agente do sistema
     * @param unknown_type $sip
     */
    public static function agentLogoff($sip) {
        $url = sprintf('%s/bmtelecom/predictive/agent/logoff/%s/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                trim($sip));
        $response = IntegrationHelper::getCurl($url, 'PUT');
        return $response;
    }

    /**
     * Desconecta a chamada do agente para passar para a proxima ligacao
     * @param unknown_type $sip
     */
    public static function agentHangup($sip) {
        $url = sprintf('%s/bmtelecom/predictive/agent/hangup/%s/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                trim($sip));
        $response = IntegrationHelper::getCurl($url, 'PUT');
        return $response;
    }

    /**
     * Retorna se o agente está logado ou não
     * @param unknown_type $sip
     */
    public static function agentStatus($sip) {
        $url = sprintf('%s/bmtelecom/predictive/agent/status/%s/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                trim($sip));
        $response = IntegrationHelper::getCurl($url, 'GET');

        if ($response != false) {
            $status = $response;
        } else {
            $status = json_encode(array(
                'status' => false,
                'result' => 'O Servidor de Integração não está ativo',
                'description' => '/: (',
                'version' => '/: (',
                'islogged' => 'false'
            ));
        }

        return json_decode($status);
    }

    /**
     * Retorna informacoes sobre a conexao com o servidor de integração
     */
    public static function info() {
        $url = sprintf('%s/bmtelecom/predictive/',
                Configure::read('Node.predictive_host'));
        $response = IntegrationHelper::getCurl($url, 'GET');

        if ($response != false) {
            $status = $response;
        } else {
            $status = json_encode(array(
                'status' => false,
                'result' => 'O Servidor de Integração não está ativo',
                'description' => '/: (',
                'version' => '/: ('
            ));
        }

        return json_decode($status);
    }

    /**
     * Para ou reiniciar o sistema preditivo
     * $action = stop ou start
     */
    public static function predictive($action) {
        $url = sprintf('%s/bmtelecom/predictive/dialer/%s',
                Configure::read('Node.predictive_host'),
                $action
        );
        $response = IntegrationHelper::getCurl($url, 'PUT');

        if ($response != false) {
            $status = $response;
        } else {
            $status = json_encode(array(
                'result' => 'O Servidor de Integração não está ativo',
                'description' => '/: (',
                'version' => '/: ('
            ));
        }

        return json_decode($status);
    }

    /**
     * Para recriar fila no asterisk
     */
    public static function queue_reload() {
        $url = sprintf('%s/bmtelecom/astmanager/queues',
                Configure::read('Node.astmanager_host')
        );
        $response = IntegrationHelper::getCurl($url, 'GET');

        if ($response != false) {
            $status = $response;
        } else {
            $status = json_encode(array(
                'result' => 'O Servidor de Integração Asterisk não está ativo',
                'description' => '/: (',
                'version' => '/: ('
            ));
        }

        return json_decode($status);
    }

    /**
     * Apresenta o status do discador preditivo
     */
    public static function dialerStatus() {
        $url = sprintf('%s/bmtelecom/predictive/dialer/status',
                Configure::read('Node.predictive_host'));
        $response = IntegrationHelper::getCurl($url, 'GET');

        $predictive = json_encode(array(
            'status' => false,
            'message' => 'O Discador N&Aacute;O est&aacute; ativo',
            'id' => 'badMessage'
        ));

        if ($response != false) {
            $tmp = json_decode($response);

            if ($tmp->running == true) {
                $predictive = json_encode(array(
                    'status' => true,
                    'message' => 'O Discador est&aacute; ativo',
                    'id' => 'goodMessage'
                ));
            }
        }

        return json_decode($predictive);
    }

    /**
     * Importa contatos pelo Nodejs
     */
    public static function contactsImport($filename) {
        $url = sprintf('%s/bmtelecom/predictive/contacts/%s/import/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                $filename);
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Reload no Preditivo
     */
    public static function predictiveReload() {
        $url = sprintf('%s/bmtelecom/predictive/info/%s/reloadall',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'));
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Stop no Preditivo
     */
    public static function predictiveStopStart($action) {
        $url = sprintf('%s/bmtelecom/predictive/dialer/%s/' . $action,
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'));
        return json_decode(IntegrationHelper::getCurl($url, 'GET'));
    }

    /**
     * Start no Preditivo
     */
    public static function predictiveStart() {
        $url = sprintf('%s/bmtelecom/predictive/dialer/%s/start',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'));
        return json_decode(IntegrationHelper::getCurl($url, 'GET'));
    }

    /**
     * Status no Preditivo
     */
    public static function predictiveStatus() {
        $url = sprintf('%s/bmtelecom/predictive/dialer/%s/status',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'));
        return json_decode(IntegrationHelper::getCurl($url, 'GET'));
    }

    /**
     * Cria os itens da campanha
     */
    public static function campaingItemsCreate($importkey, $campaignid) {

        $url = sprintf('%s/bmtelecom/predictive/campaigns/%s/create/%s/%s',
                Configure::read('Node.predictive_host'),
                Configure::read('Telecom.nodejskey'),
                $importkey,
                $campaignid);
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Envia SMS unitario pelo BmSMS
     */
    public static function sendSMS($phone, $message) {
        $url = sprintf('%s/bmtelecom/sms/send/%s/%s',
                Configure::read('Node.sms_host'),
                $phone,
                IntegrationHelper::formatMessage($message, 'url'));
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Habilita o sistema de SMS
     */
    public static function bmsmsStart() {
        $url = sprintf('%s/bmtelecom/predictive/campaign/start',
                Configure::read('Node.predictive_host'));
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Habilita o sistema de Ura Reversa
     */
    public static function uraStart() {
        $url = sprintf('%s/bmtelecom/ura/start',
                Configure::read('Node.ura_host'));
        return IntegrationHelper::getCurl($url, 'GET');
    }

    /**
     * Retorna a saida da execucao do Curl
     */
    public static function getCurl($url, $typeRequest) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $typeRequest);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    /**
     * Formata a mensagem em um padrao pre-definido
     */
    public static function formatMessage($message = '', $type = 'url') {
        return str_replace(' ', '%20', $message);
    }

}
