<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Hector Luna
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Visa extends REST_Controller {

	function __construct() {
		header('Access-Control-Allow-Origin: *');
		header("Access-Control-Allow-Headers: Content-Type, Cache-Control");
		header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");
		$method = $_SERVER['REQUEST_METHOD'];
		if($method == "OPTIONS") {
				die();
		}

		parent::__construct();
		//$this->load->model('Md_facebook');
		$this->load->model('Md_visa');
	}
/*
	public function facebook_get() {
 			$data = $this->Md_facebook->getListado(1);
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function widget_get() {
			$data = $this->Md_facebook->getListado(1);
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function botkeys_get() {
 			$data = $this->Md_visa->getKeys($this->get('id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function botones_get() {
 			$data = $this->Md_visa->getBotones($this->get('id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function encuestas_get() {
			$data = $this->Md_visa->getEncuestas($this->get('id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function encuestarep_get() {
			$data = $this->Md_visa->getEncResp($this->get('id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data[0] ], REST_Controller::HTTP_OK);
	}

	public function image_get() {
			$data = $this->Md_visa->getImage($this->get('id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function msg_put() {
			$data = $this->Md_visa->putMsg($this->put('user'), $this->put('msg'), $this->put('type'), $this->put('account_id'), $this->put('bots_key_id'));
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}
*/


	public function welcome_get() {

			$account = $this->Md_visa->getUser($this->get('auth'));
			$mensajes = $this->Md_visa->getMensajes($account[0]['id']);

			if( isset( $mensajes[0]['bienvenida'] ) && $mensajes[0]['bienvenida'] != '' ) {
				$data = $mensajes[0]['bienvenida'];
			} else {
				$data = '';
			}

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function live_put() {
			$account = $this->Md_visa->getUser($this->put('auth'));
			$ip = $this->put('user');
			$device = $this->put('usr_dev');

			$data = [];
			$data['mensaje'] = '';
			$data['bot'] = '';

			if ( isset($account[0]) ) {

				$return = $this->Md_visa->getLive($account[0]['id'], $ip, $device);

				if($return) {
					$data['bot'] = $return[0]['bot'];
					$return2 = $this->Md_visa->putLive($return, $account[0]['id']);
					if(!empty($return2)) {
						foreach ($return2 as $value) {
							$data['mensaje'] .=  '<div style="width:100%;float:left;">';
							$data['mensaje'] .= '<div class="fogata-bot-response">'.base64_decode($value['message']).'</div>';
							$data['mensaje'] .= '</div>';
						}
					}
				}

				$data = json_encode($data);

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);
	}

	public function user_put() {
			$account = $this->Md_visa->getUser($this->put('auth'));
			$ip = $this->put('user');
			$name = $this->put('name');
			$email = $this->put('email');
			$phone = $this->put('phone');
			$device = $this->put('usr_dev');

			if ( isset($account[0]) ) {

				$return = $this->Md_visa->putUser($account[0]['id'], $ip, $name, $email, $phone, $device);

				if($return)

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $return], REST_Controller::HTTP_OK);

				else

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $return], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);
	}

	public function webchat_put() {
			$account = $this->Md_visa->getUser($this->put('auth'));
			$ip = $this->put('user');
			$word = $this->put('msg');
			$type = $this->put('type');
			$key = $this->put('bots_key_id');
			$device = $this->put('usr_dev');
			$msg = FALSE;

			function getEncodeUrl($text) {
		 		$retu =  base64_decode($text);
		 		$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
				    return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
		 		return $replace;
		 	}

			function getEncodeUrl2($text) {
				$retu =  $text;
				$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
				    return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
		 		return $replace;
			}

			function normaliza ($cadena){
				$originales =  'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ?¿';
				$modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr?¿';
				$cadena = utf8_decode($cadena);
				$cadena = strtr($cadena, utf8_decode($originales), $modificadas);
				$cadena = strtolower($cadena);
				return utf8_encode($cadena);
			}

			if ( isset($account[0]) ) {
				$keys = $this->Md_visa->getKeys($account[0]['id']);

				if ($type == 1) {

			        $mensaje = strtolower($word);
			        $mensaje = urldecode($mensaje);
			        $mensaje = normaliza($mensaje);

			        //$hilos = json_decode($keys);

							foreach ($keys as $value) {
								$exp[ $value['id'] ]['id']= $value['id'];
								$exp[ $value['id'] ]['key']= $value['key_group'];
								$exp[ $value['id'] ]['mensaje']= $value['mensaje'];
								$chk[ $value['id'] ] = strtolower($value['key']);
			          //echo normaliza(strtolower($value->key)).'  //  ';
							}

							$found = FALSE;
							$count = 0;

							foreach ($chk as $value) {
			          $value2 = explode(",", $value);
			          foreach ($value2 as $value3) {
			            if (strpos($mensaje, normaliza($value3)) !== false) {
			                $key = array_search($value, $chk);
			                $msg = $value3;
											$hooman[$count]['key'] = $key;
											$hooman[$count]['msg'] = strlen(utf8_decode($msg));
											$hooman[$count]['text'] = $msg;
			                $found = TRUE;
											$count++;
			            }
			          }
							}

			        if($found == TRUE){

								$esta = max(array_column($hooman, 'msg'));
								$key = array_search($esta, array_column($hooman, 'msg'));
								$msg = $hooman[$key]['text'];
								$key = $hooman[$key]['key'];



								$exp[$key]['mensaje'] = getEncodeUrl($exp[$key]['mensaje']);

								if(	$exp[$key]['key'] == 2  ){
									$buttons = $this->Md_visa->getBotones($key);

			            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;">';
			            foreach ($buttons as $btn) {
			              $exp[$key]['mensaje'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
			            };
			            $exp[$key]['mensaje'] .= '</div>';

			          } else if(	$exp[$key]['key'] == 3 ){

									$image = $this->Md_visa->getImage($key);
			            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;">';
			            foreach ($image as $img) {
			              $exp[$key]['mensaje'] .= '</br><a href="https://fogatacrm.com/admin/advanced/backend/web'.$img['key_url'].'" target="_blank"><img src="https://fogatacrm.com/admin/advanced/backend/web'.$img['key_url'].'" width="100%"></a>';
			            };
			            $exp[$key]['mensaje'] .= '</div>';

			          } else if( $exp[$key]['key'] == 4 ){

									$buttons = $this->Md_visa->getEncuestas($key);
			            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;">';
			            foreach ($buttons as $btn) {
			              $exp[$key]['mensaje'] .= '<div data-id="'.$btn['bots_keys_id'].'" data-key="'.$btn['id'].'" class="encuesta-response fogata-encuesta-response">'.$btn['button'].'</div>';
			            };
			            $exp[$key]['mensaje'] .= '</div>';

			          } else if( $exp[$key]['key'] == 5 ){

									$combos = $this->Md_visa->getCombos($key);

			            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;">';
			            foreach ($combos as $combo) {

			              $exp[$key]['mensaje'] .= '</br><a href="https://fogatacrm.com/admin/advanced/backend/web'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatacrm.com/admin/advanced/backend/web'.$combo['key_url'].'" width="100%"></a>';
			              $exp[$key]['mensaje'] .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
			              $exp[$key]['mensaje'] .= '<p style="margin: 1px 0 2px">'.$combo['subtitle'].'</p>';
			              $exp[$key]['mensaje'] .= '<a href="'.$combo['image_url'].'" target="_blank"><div class="bot-button fogata-bot-button">'.$combo['button'].'</div></a>';

			            };
			            $exp[$key]['mensaje'] .= '</div>';

			          } else if(strlen($exp[$key]['mensaje']) <= 7 && $exp[$key]['key'] == 1){

			            $exp[$key]['mensaje'] = '<h2 style="color:#fff">'.$exp[$key]['mensaje'].'</h2>';

			          } else if(strlen($exp[$key]['mensaje']) <= 9 && $exp[$key]['key'] == 1){

			            $exp[$key]['mensaje'] = '<h3 style="color:#fff">'.$exp[$key]['mensaje'].'</h3>';

			          };

			          $data = $exp[$key]['mensaje'];

			        } else {

								$mensajes = $this->Md_visa->getMensajes($account[0]['id']);

								if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
									$data = $mensajes[0]['notfound'];
								} else {
									$data = 'Sorry, try again with another question. ☺';
								}

			        }

				$this->Md_visa->putMsgOld($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word);

			} else if ($type == 2) {
				$keyID = $this->put('keyenc_id');
				$key = $this->put('keyenc');
				$respuesta = $this->Md_visa->getEncResp( $key );
				$respuestaID = $this->Md_visa->getEncRespId( $keyID );
			  $data =  /*$respuesta[0]['text']*/  getEncodeUrl2( $respuesta[0]['text'] );
			  $msg = $respuestaID[0]['button'];


				$buttons = $this->Md_visa->getBotonesEnc($key);

				$data .= '<div style="width:100%;float:left;">';
				foreach ($buttons as $btn) {
					$data .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
				};
				$data .= '</div>';

				/*$test = 'Únete Al Marketing Inteligente \ud83d\ude00';
				$rest = strpos($data, '\u');
				$rest2 = substr($data, $rest, ($rest + 12)); // devuelve "d"
				$emo = json_decode('"'.$rest2.'"');

				$data =  str_replace($rest2, $emo, $data);*/


				$this->Md_visa->putMsgOld($ip, $msg, 3, $account[0]['id'], $key, $keyID, $device, $word);
			}

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);

	}

	public function newchat_put() {
			$account = $this->Md_visa->getUser($this->put('auth'));
			$ip = $this->put('user');
			$word = $this->put('msg');
			$type = $this->put('type');
			$key = $this->put('bots_key_id');
			$device = $this->put('usr_dev');
			$msg = FALSE;
			$data = [];
			$data['mensaje'] = '';
			$data['botones'] = '';

			function getEncodeUrl($text) {
		 		$retu =  base64_decode($text);
		 		$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
				    return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
		 		return $replace;
		 	}

			function getEncodeUrl2($text) {
				$retu =  $text;
				$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
				    return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
		 		return $replace;
			}

			function normaliza ($cadena){
				$originales =  'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ?¿';
				$modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr?¿';
				$cadena = utf8_decode($cadena);
				$cadena = strtr($cadena, utf8_decode($originales), $modificadas);
				$cadena = strtolower($cadena);
				return utf8_encode($cadena);
			}

			if ( isset($account[0]) ) {
//aki


				$keys = $this->Md_visa->getKeys($account[0]['id']);

				if ($type == 1 && count($keys) > 0) {

			        $mensaje = strtolower($word);
			        $mensaje = urldecode($mensaje);
			        $mensaje = normaliza($mensaje);

			        //$hilos = json_decode($keys);

							foreach ($keys as $value) {
								$exp[ $value['id'] ]['id']= $value['id'];
								$exp[ $value['id'] ]['key']= $value['key_group'];
								$exp[ $value['id'] ]['mensaje']= $value['mensaje'];
								$chk[ $value['id'] ] = strtolower($value['key']);
			          //echo normaliza(strtolower($value->key)).'  //  ';
							}

							$found = FALSE;
							$count = 0;

							foreach ($chk as $value) {
			          $value2 = explode(",", $value);
			          foreach ($value2 as $value3) {
			            if (strpos($mensaje, normaliza($value3)) !== false) {
			                $key = array_search($value, $chk);
			                $msg = $value3;
											$hooman[$count]['key'] = $key;
											$hooman[$count]['msg'] = strlen(utf8_decode($msg));
											$hooman[$count]['text'] = $msg;
			                $found = TRUE;
											$count++;
			            }
			          }
							}

			        if($found == TRUE){

								$esta = max(array_column($hooman, 'msg'));
								$key = array_search($esta, array_column($hooman, 'msg'));
								$msg = $hooman[$key]['text'];
								$key = $hooman[$key]['key'];



								$data['mensaje'] = getEncodeUrl($exp[$key]['mensaje']);

								if(	$exp[$key]['key'] == 2  ){

									$buttons = $this->Md_visa->getBotones($key);

			            foreach ($buttons as $btn) {
			              $data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
			            };

			          } else if(	$exp[$key]['key'] == 3 ){

									$image = $this->Md_visa->getImage($key);

			            foreach ($image as $img) {
			              $data['mensaje'] .= '</br><a href="https://fogatacrm.com/admin/advanced/backend/web'.$img['key_url'].'" target="_blank"><img src="https://fogatacrm.com/admin/advanced/backend/web'.$img['key_url'].'" width="100%"></a>';
			            };

			          } else if( $exp[$key]['key'] == 4 ){

									$buttons = $this->Md_visa->getEncuestas($key);

			            foreach ($buttons as $btn) {
			               $data['botones'] .= '<div data-id="'.$btn['bots_keys_id'].'" data-key="'.$btn['id'].'" class="encuesta-response fogata-encuesta-response">'.$btn['button'].'</div>';
			            };

			          } else if( $exp[$key]['key'] == 5 ){

									$combos = $this->Md_visa->getCombos($key);

			            foreach ($combos as $combo) {

			              $data['mensaje'] .= '</br><a href="https://fogatacrm.com/admin/advanced/backend/web'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatacrm.com/admin/advanced/backend/web'.$combo['key_url'].'" width="100%"></a>';
			              $data['mensaje'] .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
			              $data['mensaje'] .= '<p style="margin: 1px 0 2px">'.$combo['subtitle'].'</p>';
			              $data['mensaje'] .= '<a href="'.$combo['image_url'].'" target="_blank"><div class="bot-button fogata-bot-button">'.$combo['button'].'</div></a>';

			            };

			          } else if(strlen($exp[$key]['mensaje']) <= 7 && $exp[$key]['key'] == 1){

			            $data['mensaje'] = '<h2 style="color:#fff">'.$exp[$key]['mensaje'].'</h2>';

			          } else if(strlen($exp[$key]['mensaje']) <= 9 && $exp[$key]['key'] == 1){

			            $data['mensaje'] = '<h3 style="color:#fff">'.$exp[$key]['mensaje'].'</h3>';

			          };

			        } else {

								$mensajes = $this->Md_visa->getMensajes($account[0]['id']);

								if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
									$data['mensaje'] = $mensajes[0]['notfound'];
								} else {
									$data['mensaje'] = 'Sorry, try again with another question. ☺';
								}

			        }

				$this->Md_visa->putMsg($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word);

			} else if ($type == 2 && count($keys) > 0) {
				$keyID = $this->put('keyenc_id');
				$key = $this->put('keyenc');
				$respuesta = $this->Md_visa->getEncResp( $key );
				$respuestaID = $this->Md_visa->getEncRespId( $keyID );
			  $data['mensaje'] =  /*$respuesta[0]['text']*/  getEncodeUrl2( $respuesta[0]['text'] );
			  $msg = $respuestaID[0]['button'];


				$buttons = $this->Md_visa->getBotonesEnc($key);


				foreach ($buttons as $btn) {
					$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
				};


				/*$test = 'Únete Al Marketing Inteligente \ud83d\ude00';
				$rest = strpos($data, '\u');
				$rest2 = substr($data, $rest, ($rest + 12)); // devuelve "d"
				$emo = json_decode('"'.$rest2.'"');

				$data =  str_replace($rest2, $emo, $data);*/


				$this->Md_visa->putMsg($ip, $msg, 3, $account[0]['id'], $key, $keyID, $device, $word);
			} else if($type == 3) {
				$mensaje = strtolower($word);
				$mensaje = urldecode($mensaje);
				$mensaje = normaliza($mensaje);
								if (strpos($mensaje, normaliza('admin')) !== false) {
										$data = array('mensaje' => 'Hola Restaurante La Fogata S.A. Para continuar ingrese su contraseña.', 'botones' => '', 'signup' => 1);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else {
									$data = array('mensaje' => 'Usuario no encontrado, por favor verifique su usuario y vuelva a intentarlo.', 'botones' => '', 'signup' => 0);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								}
			} else if($type == 4) {
				$mensaje = strtolower($word);
				$mensaje = urldecode($mensaje);
				$mensaje = normaliza($mensaje);
								if (strpos($mensaje, normaliza('1234')) !== false) {
									$botones = '<div class="option-button fogata-option-button">Ayuda</div>
									<div class="option-button fogata-option-button">Salir</div>';


										$data = array('mensaje' => 'Muchas gracias, para empezar a realizar consultas puedes escribir el comando "Ayuda". Si desea hablar con asistente escriba "Salir"', 'botones' => $botones, 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else {
									$data = array('mensaje' => 'Contraseña incorrecta, por favor verifique su contraseña y vuelva a intentarlo.', 'botones' => '', 'signup' => 1);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								}
			} else if($type == 5) {
				$mensaje = strtolower($word);
				$mensaje = urldecode($mensaje);
				$mensaje = normaliza($mensaje);
								if (strpos($mensaje, normaliza('ayuda')) !== false) {
									$botones = '<div class="option-button fogata-option-button">Puntos</div>
									<div class="option-button fogata-option-button">Premios</div>
									<div class="option-button fogata-option-button">Facturación</div>';

										$data = array('mensaje' => 'Desde la plataforma VisaNet Clientes puedes consultar "Puntos", "Premios" y "Facturación"', 'botones' => $botones, 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else if (strpos($mensaje, normaliza('puntos')) !== false) {

										$trans = $this->Md_visa->getTransac();
										$monto = 0;
										foreach ($trans as $value) {
											$monto += $value['monto'];
										}
										$monto = round($monto) * 10;
										$botones = '<div class="option-button fogata-option-button">Puntos</div>
										<div class="option-button fogata-option-button">Premios</div>
										<div class="option-button fogata-option-button">Facturación</div>';

										$data = array('mensaje' => 'Hasta la fecha tienes '.$monto.' puntos acumulados.', 'botones' => $botones, 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else if (strpos($mensaje, normaliza('premios')) !== false) {
									$botones = '<div class="option-button fogata-option-button">Puntos</div>
									<div class="option-button fogata-option-button">Premios</div>
									<div class="option-button fogata-option-button">Facturación</div>';

									$combos = array(
										'1' => array(
											'key_url' => 'http://panamaoficial.com/test/visanet/tv-samsung.png',
											'title' => '65" TV Samsung',
											'subtitle' => 'Smart TV 4k - 70,000 puntos',
											'button' => 'Canjear',
											'image_url' => 'http://www.visanet.com.gt/visaconpuntos.php',
										),
										'2' => array(
											'key_url' => 'http://panamaoficial.com/test/visanet/ps4.jpg',
											'title' => 'SONY PS4',
											'subtitle' => 'PS4 500GB - 21,000 puntos',
											'button' => 'Canjear',
											'image_url' => 'http://www.visanet.com.gt/visaconpuntos.php',
										),
										'3' => array(
											'key_url' => 'http://panamaoficial.com/test/visanet/chrome.jpg',
											'title' => 'Chromecast',
											'subtitle' => 'Chromecast Ultra - 3,150 puntos',
											'button' => 'Canjear',
											'image_url' => 'http://www.visanet.com.gt/visaconpuntos.php',
										)
									);
									$premios ='';
									$premios .= '<div style="width:100%;float:left;">';
			            foreach ($combos as $combo) {

			              $premios .= '</br><a href="'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="'.$combo['key_url'].'" width="100%"></a>';
			              $premios .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
			              $premios .= '<p style="margin: 1px 0 2px">'.$combo['subtitle'].'</p>';
			              $premios .= '<a href="'.$combo['image_url'].'" target="_blank"><div class="bot-button fogata-bot-button">'.$combo['button'].'</div></a>';

			            };
			            $premios .= '</div>';


										$data = array('mensaje' => 'Estos son los premios que puedes canjear con tus puntos'.$premios, 'botones' => $botones, 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else if (strpos($mensaje, normaliza('facturacion')) !== false) {

									$trans = $this->Md_visa->getFactu();
									$monto = '';
									foreach ($trans as $value) {
										$monto .= date("m/d", strtotime($value['fecha'])).' '.$value['cliente']. ' / $'.round(($value['monto'] * 1.12), 2).'<br>';
									}

										$data = array('mensaje' => 'Estas son las últimas 10 transacciones registradas: <br>'.$monto, 'botones' => '', 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else if (strpos($mensaje, normaliza('salir')) !== false){
									$data = array('mensaje' => 'Ha salido del sistema de VisaNet Clientes, para otra consulta escribanos ahora.', 'botones' => '', 'signup' => 3);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								} else {
									$botones = '<div class="option-button fogata-option-button">Ayuda</div>
									<div class="option-button fogata-option-button">Salir</div>';


										$data = array('mensaje' => 'Para ayuda escribie el comando "Ayuda". Si desea hablar con asitencia al público escriba "Salir"', 'botones' => $botones, 'signup' => 2);
										$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
								}
			} else {
				$mensajes = $this->Md_visa->getMensajes($account[0]['id']);

				if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
					$data['mensaje'] = $mensajes[0]['notfound'];
				} else {
					$data['mensaje'] = 'Sorry, try again with another question. ☺';
				}
			}

			$data = json_encode($data);

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);

	}

}
