<?php

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

class SmsController extends AppController {
	
	public $helpers = array ('Html','Form');
	public $components = array('Session', 'Cookie', 'TextMessages.URLEscapeCode');	
	
	function beforeFilter() {
	    parent::beforeFilter();
	    
	    //cookie setings
	    $this->Cookie->name = 'cookie_chips';
	    $this->Cookie->time = 3600;  // or '1 hour'
	    $this->Cookie->path = '/';
	    $this->Cookie->domain = '192.168.25.100';
	    $this->Cookie->secure = false;
	    $this->Cookie->key = '39lbkutg1i2l0kta6785d8qki5';
	    $this->Cookie->httpOnly = true;
	    	    
		$this->Auth->allow(
		        'send', 
		        'reset', 
		        'sendaudio',
		        'assetschips',
				'test'
		     );
	}	
		
	/**
	 * Realiza o envio de sms e salva no banco de dados
	 *
	 * CREATE TABLE sms (
	 *  id serial NOT NULL,
	 *  telefone varchar(30),
	 *  mensagem text,
	 *  status varchar(15),
	 *  data timestamp without time zone
	 * )
	 *
	 * IMPORTANTE: Acesso o LEIAME deste plugin para configurar as permissões
	 * necessárias so Apache dentro do Linux
	 */
	public function send($phone, $message) {	    
		$this->autoLayout = false;
		
		$message = $this->URLEscapeCode->decode($message);
		
		$this->loadModel('Chip');
		$this->Chip->create();
		$this->Chip->recursive = 0;
		
		$this->Chip->id = 1;	
		$_Chip = $this->Chip->read();
		
		$chipNumber = $_Chip['Chip']['indice'];
		
	    $status = "Falha no Envio";
		$host = Configure::read('Asterisk.host');
		$username = Configure::read('Asterisk.username');
		$password = Configure::read('Asterisk.password');
		$port = Configure::read('Asterisk.port');
		$channels = Configure::read('Sms.khomp_sms_channels');
		$debugMode = Configure::read('Environment.debug_mode');
		
		if ($debugMode) {
			$retorno = sprintf("Tel: %s, Mes: %s, Dt: %s", $phone, $message, date('Y-m-d H:i:s',strtotime("now")));
			$status = 'Envio em modo Debug';
		}
		else {			
			$command = sprintf("sudo rasterisk -x 'khomp sms %s %s \"%s\"'", 
			        $channels[$chipNumber], $phone, $message);
			$retorno = system($command);
			
			if (strpos($retorno, 'Message sent successfully!') !== false) {
				$status = 'Enviado com Sucesso';
			}			
			$retorno = $status;
		}
		
		$this->loadModel('TextMessage');
		$this->TextMessage->create();
		$this->TextMessage->set("phone", $phone);
		$this->TextMessage->set("message", $message);
		$this->TextMessage->set("data", date('Y-m-d H:i:s',strtotime("now")));
		$this->TextMessage->set("status", $status);
		$this->TextMessage->set("sms_type", 'teste');
		$this->TextMessage->save();
	    
	    $chipNumber ++;
	    if ($chipNumber == count($channels)) {
	        $chipNumber = 0;
	    }
	    
	    $this->Chip->saveField('indice', $chipNumber);	    
	    $this->set('param',sprintf("%s-sep-%s", $channels[$chipNumber], $retorno));
	}
	
/**
 * Reinicia um canal da placa, recebe:
 * $appliance: indice da placa
 * $channel: indice do canal
 * ex: reset("0 2")
 */	
	public function reset($channel) {		
		$this->autoLayout = false;
		
		$retorno = "";
		
		if ($channel != '') {
			$status = sprintf("Channel Reset %s", $channel);
			$command = sprintf("sudo rasterisk -x 'khomp modem reset %s'", $channel);
			$retorno = system($command);

			$this->loadModel('TextMessage');
			$this->TextMessage->create();
			$this->TextMessage->set("phone", "");
			$this->TextMessage->set("message", $status);
			$this->TextMessage->set("data", date('Y-m-d H:i:s',strtotime("now")));
			$this->TextMessage->set("status", $status);
			$this->TextMessage->set("sms_type", 'reset');
			$this->TextMessage->save();
		}				
		
		$this->set('param', $retorno);
	}
	
/**
 * Cria um arquivo de configuracoes dentro de uma pasta especifica do 
 * Asterisk para que ele faça o envio de uma gravacao para um numero celular
 */	
    public function sendaudio($appliance, $channel) {        
        $this->autoLayout = false;
        
        /**
         * Path onde os arquivos contendo os parametros para ligacoes devem
         * ser alocados, para que o Asterisk realize a discagem automatica.
         * Por default o path é /var/spool/asterisk/outgoing
         */
        $path = Configure::read('Asterisk.path_outgoing');
        $khomp_channel = sprintf("b%sc%s", $appliance, $channel);
        
        $phone = Configure::read('Phones.' .$khomp_channel);
        
        /**
         * Path onde o arquivo devera ser instalado temporariamente para ser 
         * criado
         */
        $file_tmp = WWW_ROOT. 'uploads' .DS. 'smsdial.' 
                                .$appliance.$channel. '.call';   
        
        $file_final = $path .DS. 'smsdial.'
                                .$appliance.$channel. '.call';        
        
        /**
         * Canal que devera ser utilizado para discagem
         */
        $dial = sprintf("Channel: khomp/b%sc%s/%s", 
                $appliance, $channel, $phone);
        
        $file = new File($file_tmp, true);
        $file->write($dial. "\n");
        $file->write("Application: Playback \n");
        $file->write("Data: hello-world \n");
        
        /**
         * Move o arquivo para o diretorio do Asterisk
         */
        $file->copy($file_final);
        
        $this->set('param', $file_final);
    }    
    
    /**
     * Retorna a quantidade de chips ativos
     */
    public function assetschips() {
        $this->autoLayout = false;        
        $quantity = 0;
        
        $channels = Configure::read('Sms.khomp_sms_channels');
        $quantity = count($channels);
        $this->set('param', $quantity);
    }
    
    /**
     * Envia um SMS pelo painel de admin
     */
    public function admin_sendsms() {
    	$this->set('title_for_layout', 'Envio de SMS Manual');
    	if ($this->request->is('post')) {
    		$phone = $this->request->data['TextMessage']['phone'];
    		$message = $this->request->data['TextMessage']['message'];
    		$this->send($phone, $message);
    		
    		$this->Session->setFlash(__('Enviado com sucesso'));
    		return $this->redirect(array(
    				'controller' => 'sms',
    				'action' => 'sendsms',
    				'admin' => true,
    				'plugin' => 'text_messages',
    		));
    	}
    }
}