<?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 Cax 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_bot');
		$this->load->model('Md_cax');
		$this->load->model('Md_express');
	}

	public function response_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

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

		$data = $this->Md_cax->getKeys($cleanPost);

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

	}

	public function welcome_get() {

			$account = $this->Md_bot->getUser($this->get('auth'));
			$mensajes = $this->Md_bot->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() {

			$post = $this->put();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$device = $cleanPost['usr_dev'];

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

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

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

				if($return) {
					$data['bot'] = $return[0]['bot'];
					$return2 = $this->Md_bot->putLive($return, $account[0]['id']);

					if(!empty($return2)) {
						foreach ($return2 as $value) {
							$name = $this->Md_bot->getUsername($value['user_id']);
							$data['mensaje'] .=  '<div style="width:100%;float:left;">';
							$data['mensaje'] .= '<div class="fogata-bot-response">'.base64_decode($value['message']).'</div>';
							$data['mensaje'] .= '</div>';
							if($name[0]['name'] != '') {
								$data['mensaje'] .=  '<div style="width:100%;float:left;">';
								$data['mensaje'] .= '<div style="font-size: 9px"><b>Agent: </b>'.$name[0]['name'].'</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 live_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$device = $cleanPost['usr_dev'];

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

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

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

				if($return) {
					$data['bot'] = $return[0]['bot'];
					$return2 = $this->Md_bot->putLive($return, $account[0]['id']);

					if(!empty($return2)) {
						foreach ($return2 as $value) {
							$name = $this->Md_bot->getUsername($value['user_id']);
							$data['mensaje'] .=  '<div style="width:100%;float:left;">';
							$data['mensaje'] .= '<div class="fogata-bot-response">'.base64_decode($value['message']).'</div>';
							$data['mensaje'] .= '</div>';
							if($name[0]['name'] != '') {
								$data['mensaje'] .=  '<div style="width:100%;float:left;">';
								$data['mensaje'] .= '<div style="font-size: 9px"><b>Agent: </b>'.$name[0]['name'].'</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() {


			$post = $this->put();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$name = $cleanPost['name'];
			$email = $cleanPost['email'];
			$phone = $cleanPost['phone'];
			$device = $cleanPost['usr_dev'];

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

				$return = $this->Md_bot->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 user_post() {


			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$name = $cleanPost['name'];
			$email = $cleanPost['email'];
			$phone = $cleanPost['phone'];
			$device = $cleanPost['usr_dev'];

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

				$return = $this->Md_bot->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 newchat_put() {

			$post = $this->put();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$word = $cleanPost['msg'];
			$type = $cleanPost['type'];
			$key = $cleanPost['bots_key_id'];
			$device = $cleanPost['usr_dev'];
			$msg = FALSE;
			$data = [];
			$data['mensaje'] = '';
			$data['botones'] = '';
			$keyEncId = $cleanPost['keyenc_id'];
			$keyId = $cleanPost['keyenc'];

//error_log( 'llega mierda ' . $word);
			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]) ) {

				$cycles = $this->Md_bot->getCycle($ip, $device, $account[0]['id']);
				//aki
				$typeA = 0;
				if($cycles){
					////error_log( 'llega mierda ' . $type);
					$respuesta = $this->Md_bot->getEncResp( $cycles );
					//$respuestaID = $this->Md_bot->getEncRespId( $keyID );
					$data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
					//$msg = $respuestaID[0]['button'];
					$buttons = $this->Md_bot->getBotonesEnc( $cycles );
					foreach ($buttons as $btn) {
						$data['botones'] .= '<div data-id="'.$respuesta[0]['id'].'" class="fogata-encuesta-callback">'.$btn['button'].'</div>';
					};

					$this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA);
				//	$this->Md_bot->putMsg($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word, $typeA);
					//$this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $key, 0, $device, $word);

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

				} else{

				$keys = $this->Md_bot->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'];
								$exp[ $value['id'] ]['mail_alert']= $value['mail_alert'];
								$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'];

								$typeA = $exp[$key]['key'];

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

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

									$buttons = $this->Md_bot->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_bot->getImage($key);

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

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

									$buttons = $this->Md_bot->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_bot->getCombos($key);

									$galWidth = count($combos);
									$galWidth = 224 * $galWidth;

									$data['mensaje'] .= '<div class="fogata-gallery">';
									$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-right"></i>
																				</div>
																		   </div>';

									$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

			            foreach ($combos as $combo) {
										$data['mensaje'] .= '<div class="fogata-tile">';
			              $data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_url'].'" width="100%"></a>';
			              $data['mensaje'] .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
										if($combo['subtitle'] != '')
										$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>';
										$data['mensaje'] .= '</div>';
									};

									$data['mensaje'] .= '</div>';
									$data['mensaje'] .= '</div>';

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

										$combos = $this->Md_bot->getCombots($key);


										$galWidth = count($combos);
										$galWidth = 224 * $galWidth;

										$data['mensaje'] .= '<div class="fogata-gallery">';
										$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-right"></i>
																				</div>
																				</div>';

										$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

										foreach ($combos as $combo) {
												$data['mensaje'] .= '<div class="fogata-tile">';
												$data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_image'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_image'].'" width="100%"></a>';
												$data['mensaje'] .= '<div class="bot-button fogata-option-button">'.$combo['button'].'</div>';
												$data['mensaje'] .= '</div>';
										};

										$data['mensaje'] .= '</div>';
										$data['mensaje'] .= '</div>';

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

			          };

								if($exp[$key]['mail_alert'] == 1) {
									$this->Md_bot->putAlerts($account[0]['id'], $ip, $device);
								}

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


			        } else {

								$mensajes = $this->Md_bot->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_bot->putMsg($ip, $msg, 0, $account[0]['id'], 0, 0, $device, $word, $typeA);


			        }


			} else if ($type == 2) {
				$respuesta = $this->Md_bot->getEncResp( $key );
				$respuestaID = $this->Md_bot->getEncRespId( $keyEncId );
			  $data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
			  $msg = $respuestaID[0]['button'];
				$buttons = $this->Md_bot->getBotonesEnc($key);
				foreach ($buttons as $btn) {
					$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
				};
				////error_log($ip. ' '.  $msg . ' '. 3 . ' '. $account[0]['id'] . ' '. $key . ' '. $keyID . ' '. $device . ' '. $word . ' '. $typeA);
				$this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA);

			} else {
				$mensajes = $this->Md_bot->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);

	}

	public function newchat_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$word = $cleanPost['msg'];
			$type = $cleanPost['type'];
			$key = $cleanPost['bots_key_id'];
			$device = $cleanPost['usr_dev'];
			$msg = FALSE;
			$data = [];
			$data['mensaje'] = '';
			$data['botones'] = '';
			$keyEncId = $cleanPost['keyenc_id'];
			$keyId = $cleanPost['keyenc'];

			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]) ) {

				$cycles = $this->Md_bot->getCycle($ip, $device, $account[0]['id']);
				//aki
				$typeA = 0;
				if($cycles){
					////error_log( 'llega mierda ' . $type);
					$respuesta = $this->Md_bot->getEncResp( $cycles );
					//$respuestaID = $this->Md_bot->getEncRespId( $keyID );
					$data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
					//$msg = $respuestaID[0]['button'];
					$buttons = $this->Md_bot->getBotonesEnc( $cycles );
					foreach ($buttons as $btn) {
						$data['botones'] .= '<div data-id="'.$respuesta[0]['id'].'" class="fogata-encuesta-callback">'.$btn['button'].'</div>';
					};

					$userId = $this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA);
				//	$this->Md_bot->putMsg($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word, $typeA);
					//$this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $key, 0, $device, $word);

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

				} else {

				$keys = $this->Md_bot->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'];
								$exp[ $value['id'] ]['mail_alert']= $value['mail_alert'];
								$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'];

								$typeA = $exp[$key]['key'];

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

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

									$buttons = $this->Md_bot->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_bot->getImage($key);

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

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

									$buttons = $this->Md_bot->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_bot->getCombos($key);

									$galWidth = count($combos);
									$galWidth = 224 * $galWidth;

									$data['mensaje'] .= '<div class="fogata-gallery">';
									$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-right"></i>
																				</div>
																			 </div>';

									$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

									foreach ($combos as $combo) {
										$data['mensaje'] .= '<div class="fogata-tile">';
										$data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_url'].'" width="100%"></a>';
										$data['mensaje'] .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
										if($combo['subtitle'] != '')
										$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>';
										$data['mensaje'] .= '</div>';
									};

									$data['mensaje'] .= '</div>';
									$data['mensaje'] .= '</div>';

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

										$combos = $this->Md_bot->getCombots($key);


										$galWidth = count($combos);
										$galWidth = 224 * $galWidth;

										$data['mensaje'] .= '<div class="fogata-gallery">';
										$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-right"></i>
																				</div>
																				</div>';

										$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

										foreach ($combos as $combo) {
												$data['mensaje'] .= '<div class="fogata-tile">';
												$data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_image'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_image'].'" width="100%"></a>';
												$data['mensaje'] .= '<div class="bot-button fogata-option-button">'.$combo['button'].'</div>';
												$data['mensaje'] .= '</div>';
										};

										$data['mensaje'] .= '</div>';
										$data['mensaje'] .= '</div>';

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

								};

								if($exp[$key]['mail_alert'] == 1) {
									$this->Md_bot->putAlerts($account[0]['id'], $ip, $device);
								}

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


							} else {

								$mensajes = $this->Md_bot->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. ☺';
								}

								$userId = $this->Md_bot->putMsg($ip, $msg, 0, $account[0]['id'], 0, 0, $device, $word, $typeA);


							}


			} else if ($type == 2) {
				$respuesta = $this->Md_bot->getEncResp( $key );
				$respuestaID = $this->Md_bot->getEncRespId( $keyEncId );
				$data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
				$msg = $respuestaID[0]['button'];
				$buttons = $this->Md_bot->getBotonesEnc($key);
				foreach ($buttons as $btn) {
					$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
				};
				
				$userId = $this->Md_bot->putMsg($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA);

			} else {
				$mensajes = $this->Md_bot->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. ☺';
				}
			}

			$sendData = array();
			$sendData['msg'] = $word;
			$sendData['channel'] = 1;
			$sendData['nombre'] = "";
			$sendData['telefono'] = "";
			$sendData['correo'] = "";
			$sendData['id'] = $userId;

/*		if(isset($cleanPost['msg'])) $word = $cleanPost['msg'];
		else $word = FALSE;
		if(isset($cleanPost['channel'])) $channel = $cleanPost['channel'];
		else $channel = FALSE;
		if(isset($cleanPost['nombre'])) $nombre = $cleanPost['nombre'];
		else $nombre = FALSE;
		if(isset($cleanPost['telefono'])) $telefono = $cleanPost['telefono'];
		else $telefono = FALSE;
		if(isset($cleanPost['correo'])) $correo = $cleanPost['correo'];
		else $correo = FALSE;
		if(isset($cleanPost['id'])) $user = $cleanPost['id'];
		else $user = FALSE;
*/


			$this->Md_cax->getKeys($sendData);

			$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 chatbotCax_post() {

		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		
		$account = $this->Md_bot->getTelegram($cleanPost['account_id']);
		$user_id = $cleanPost['user_id'];
		$chatId = $cleanPost['chatId'];
		$typeTl = $cleanPost['typeTl'];
		$word = $cleanPost['msg'];
		$username = $cleanPost['username'];
		$key = 0;

		$data = [];
		$data['mensaje'] = '';
		$data['botones'] = '';
		$msg = "";

		$data['message'] = "";
		$data['buttons'] = array();
		$data['gallery1'] = array();
		$data['gallery2'] = array();
		$data['image'] = array();
		
		//log_message('error', 'Some variable did not contain a value.');

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

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

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

			$keys = $this->Md_express->getKeys($account[0]['user_id']);

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

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

			$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++;
					}
				}
			}

			$userData = $this->Md_bot->putMsgBots($user_id, 1, $account[0]['id'], $key, $word, 'telegram', $username, '', '');
			//log_message('error', json_encode($userData));
			$this->Md_cax->getKeysa($cleanPost, $userData['id']);

			$type = $userData['step'];

			if (isset($userData['id'])) {

				if ($type != 2 && count($keys) > 0) {
	
					if ($found == TRUE) {
	
							$maxi = max(array_column($hooman, 'msg'));
							$key = array_search($maxi, array_column($hooman, 'msg'));
							$msg = $hooman[$key]['text'];
							$key = $hooman[$key]['key'];
	
							$keyWord = $msg;
							$botsKey = $key;
	
							$typeA = $exp[$key]['key'];
							$data['message'] = base64_decode($exp[$key]['mensaje']);
							$data['type'] = 1;
						if ($exp[$key]['key'] == 2) {
							$buttons = $this->Md_express->getBotones($key);
							foreach ($buttons as $btn) {
								$data['buttons'][] = $btn['button'];
							};
							$data['type'] = 2;
						} else if ($exp[$key]['key'] == 3) {
							$image = $this->Md_express->getImage($key);
							foreach ($image as $img) {
								$data['image'][] = "https://api.fogatabot.com/admin/advanced/backend/web" . $img['key_url'];
							};
							$data['type'] = 3;
						} else if ($exp[$key]['key'] == 4) {
							$buttons = $this->Md_express->getEncuestas($key);
							$enc = array();
							foreach ($buttons as $btn) {
								$enc[] = array(
									'bots_keys_id' => $btn['bots_keys_id'],
									'keyenc_id' => $btn['id'],
									'button' => $btn['button'],
								);
							};
							$data['buttonsEnc'] = $enc;
							$data['type'] = 4;
							$this->Md_bot->putTelegramenc($userData['id'], 2);
						} else if ($exp[$key]['key'] == 5) {
							$combos = $this->Md_express->getCombos($key);
							$combs = array();

							foreach ($combos as $combo) {
								$combs[] = array(
									'title' => $combo['title'],
									'subtitle' => $combo['subtitle'],
									'image_url' => "https://api.fogatabot.com/admin/advanced/backend/web" . $combo['key_url'],
									'key_url' => $combo['image_url'],
									'button' => $combo['button'],
									'bots_keys_id' => $combo['id'],
								);
							};
							$data['gallery1'] = $combs;
							$data['type'] = 5;
						} else if ($exp[$key]['key'] == 6) {
							$combos = $this->Md_express->getCombots($key);
							$combs = array();
							foreach ($combos as $combo) {
								$combs[] = array(
									'image_url' => "https://api.fogatabot.com/admin/advanced/backend/web" . $combo['key_image'],
									'button' => $combo['button'],
									'bots_keys_id' => $combo['id'],
								);
							};
							$data['gallery2'] = $combs;
							$data['type'] = 6;
						}
					} else {
						$mensajes = $this->Md_express->getMensajes2($account[0]['id']);
						if (isset($mensajes[0]['notfound']) && $mensajes[0]['notfound'] != '') {
							$data['message'] = $mensajes[0]['notfound'];
						}
						$data['type'] = 1;
					}
	
					//$this->Md_express->putMsg($ip, $msg, 0, $account[0]['user_id'], $key, 0, $device, $word, $typeA);

				} else if ($type == 2 && count($keys) > 0) {

					$thisLast =$this->Md_bot->getLastmsg($userData['id']);
					$ecuestaResp = $this->Md_bot->findBotonesEnc($thisLast[1]['bots_key_id']);
					$testKey = $this->Md_bot->findEncResp($thisLast[1]['bots_key_id']);
			
					$msg = $testKey[0]['text'];
					if($ecuestaResp) {
					  foreach ($ecuestaResp as $btn) {
						$msg .= "\n<b>".$btn['button']."</b>";
					  };
					}


					$data['message'] = $msg;
					$this->Md_bot->putTelegramenc($userData['id'], 1);
					//$this->Md_express->putMsg($ip, $msg, 3, $account[0]['user_id'], $key, $keyID, $device, $word, $typeA);
				} else {
					$mensajes = $this->Md_express->getMensajes2($account[0]['user_id']);
	
					if (isset($mensajes[0]['notfound']) && $mensajes[0]['notfound'] != '') {
						$data['message'] = $mensajes[0]['notfound'];
					}
					$data['type'] = 1;
				}
	
				$msgs = $data['message'];
				
				if($userData['bot'] == 0 && !empty($msgs)) {
					foreach ($data['buttons'] as $value) {
						$msgs .= "\n<b>". $value ."</b>";
					}
					foreach ($data['image'] as $value) {
						$this->Md_bot->sendTelegramphoto($account[0]['token'], $chatId, $value);
					}
					foreach ($data['gallery1'] as $value) {

						$msgComb = "<b>".$value['title']."</b>\n<i>".$value['subtitle']."</i>\n<b><a href='".$value['key_url']."' target='_blank'>".$value['button']."</a></b>";

						$this->Md_bot->sendTelegramphoto($account[0]['token'], $chatId, $value['image_url']);
						$this->Md_bot->sendTelegram($account[0]['token'], $chatId, $msgComb);
					}
					foreach ($data['gallery2'] as $value) {

						$msgComb = "<b>".$value['button']."</b>";

						$this->Md_bot->sendTelegramphoto($account[0]['token'], $chatId, $value['image_url']);
						$this->Md_bot->sendTelegram($account[0]['token'], $chatId, $msgComb);
					}

					$this->Md_bot->sendTelegram($account[0]['token'], $chatId, $msgs);
					$this->Md_bot->putMsgBots($user_id, 0, $account[0]['id'], $key, $msgs, 'telegram', $username, '', '');
				}
				
	
				} else {

					$mensajes = $this->Md_express->getMensajes2($account[0]['user_id']);

					if (isset($mensajes[0]['response']) && $mensajes[0]['response'] != '') {
						$data['message'] = $mensajes[0]['response'];
					}
					$msg=$data['message'];
					$this->Md_bot->sendTelegram($account[0]['token'], $chatId, $msg);
				}
		 
		} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'Usuario no encontrado'], REST_Controller::HTTP_OK);

	}

}
