<?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 Aseguradora 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_aseguradora');
		$this->load->library('form_validation');
		$this->load->helper(array('form', 'url'));
	}

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


	// Subir imágenes

	public function uploadImage_post()
	{

		$post = $this->post();

		$config['upload_path']          = './uploads/';
		$config['allowed_types']        = 'gif|jpg|png|jpeg|GIF|JPG|PNG|JPEG';
		$config['max_size']             = 8192;
		$config['max_width']            = 8192;
		$config['max_height']           = 8192;

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload('userfile')) {
			$error = array('error' => $this->upload->display_errors());
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error uploading', 'data' => $error], REST_Controller::HTTP_OK);
		} else {
			$data = array('upload_data' => $this->upload->data());

			$data['upload_data']['file_url'] = 'https://fogatacrm.com/api/admin/uploads/' . $data['upload_data']['file_name'];

			$return = $this->Md_aseguradora->putImage($post['nombre'],$post['poliza'],$post['certificado'],$post['user'],$data['upload_data']['file_url'],74,$post['telefono'],$post['monto']);
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Upload successfull', 'data' => $return], 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'];
		if(isset($cleanPost['last'])) $last = $cleanPost['last'];
		else $last = "";
		$msg = FALSE;
		$data = [];
		$data['mensaje'] = '';
		$data['botones'] = '';
		$keyEncId = $cleanPost['keyenc_id'];
		$keyId = $cleanPost['keyenc'];
		$user_id = 0;

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


		$mensaje = strtolower($word);
		$mensaje = urldecode($mensaje);
		$mensaje = normaliza($mensaje);
		$data['last'] = $mensaje;
		$data['nombre'] = '';
		$data['poliza'] = '';
		$data['user'] = '';
		$data['telefono'] = '';
		$data['tipo_telefono'] = '';
		$data['tipo_asistencia'] = '';
		$data['horario'] = '';
		$data['direccion'] = '';
		$data['monto'] = '';

		if (strpos($last, normaliza('iniciar registro')) !== false) {
			$data['nombre'] = $word;
		} else if (strpos($last, normaliza('mañana')) !== false) {
			$data['direccion'] = $word;
			$data['horario'] = "Mañana";
		} else if (strpos($last, normaliza('ingresar monto')) !== false) {
			$data['monto'] = $word;
		}  else if (strpos($last, normaliza('tarde')) !== false) {
			$data['direccion'] = $word;
			$data['horario'] = "Tarde";
		} else if (strpos($last, normaliza('programar cobro')) !== false) {
			$data['nombre'] = $word;
		} else if (strpos($last, normaliza('ingresar certificado')) !== false) {
			$this->Md_aseguradora->putProgramar($cleanPost['poliza'], $word, $cleanPost['user_id'], $cleanPost['nombre'], $cleanPost['telefono'], $cleanPost['direccion'], $cleanPost['horario'], 74);
			$data['certificado'] = $word;
		} else if (strpos($last, normaliza('poliza')) !== false) {
			$data['poliza'] = $word;
		} else if (strpos($last, normaliza('no de poliza')) !== false) {
			$data['poliza'] = $word;
		} else if (strpos($last, normaliza('no de certificado')) !== false) {
			$data['certificado'] = $word;
		} else if (strpos($last, normaliza('asistencia')) !== false) {
			$data['nombre'] = $word;
		} else if (strpos($last, normaliza('movil')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Móvil";
		} else if (strpos($last, normaliza('hogar')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Hogar";
		} else if (strpos($last, normaliza('telefono hogar')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Teléfono Hogar";
		} else if (strpos($last, normaliza('telefono movil')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Teléfono Móvil";
		} else if (strpos($last, normaliza('telefono fijo')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Teléfono Fijo";
		} else if (strpos($last, normaliza('celular')) !== false) {
			$data['telefono'] = $mensaje;
			$data['tipo_telefono'] = "Celular";
		} else if (strpos($last, normaliza('compartir gps')) !== false) {
			$data['poliza'] = $word;
		} else if (strpos($mensaje, normaliza('accidente')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		} else if (strpos($mensaje, normaliza('paso de corriente')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		} else if (strpos($mensaje, normaliza('grua')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		} else if (strpos($mensaje, normaliza('cerrajeria')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		} else if (strpos($mensaje, normaliza('abasto combustible')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		} else if (strpos($mensaje, normaliza('asistencia en hogar')) !== false) {
			$this->Md_aseguradora->putAsistencia($cleanPost['nombre'], $cleanPost['tipo_telefono'], $cleanPost['telefono'], $cleanPost['latitud'], $cleanPost['longitud'], $cleanPost['poliza'], $word, $cleanPost['user_id'], 74);
			$data['tipo_asistencia'] = $word;
		}

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

				$user_id = $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) {

					//$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 (strpos($mensaje, normaliza('tomar foto')) !== false) {

						$class = rand(1000,9999);
						$data = array('mensaje' => '<form action="https://fogatacrm.com/api/admin/index.php/aseguradora/uploadImage" class="fotos-users" id="foto-'.$class.'" method="post" enctype="multipart/form-data">
						<label for="fileToUpload-'.$class.'" style="border: 1px solid #ccc; display: inline-block; padding: 6px 12px;cursor: pointer;" class="custom-file-upload">
							Enviar Foto
						</label>
						<input style="display: none;" type="file" data-id="'.$class.'" name="userfile" class="fogata-send-file fileToUpload-'.$class.'" id="fileToUpload-'.$class.'" >
						<br>
						</form>', 'botones' => '', 'signup' => 1);
						$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

					} else 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://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_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://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>';
								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://fogatacrm.com/admin/advanced/backend/web' . $combo['key_image'] . '" target="_blank"><img style="margin-top: 15px;" src="https://fogatacrm.com/admin/advanced/backend/web' . $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);
						}

						$user_id = $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. ☺';
						}

						$user_id = $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);
					$user_id = $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['user'] = $user_id;
				$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>';
				};

				$user_id = $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://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_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://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>';
								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://fogatacrm.com/admin/advanced/backend/web' . $combo['key_image'] . '" target="_blank"><img style="margin-top: 15px;" src="https://fogatacrm.com/admin/advanced/backend/web' . $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);
						}

						$user_id = $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. ☺';
						}

						$user_id = $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);
					$user_id = $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 webchat_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;

				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);
					$cadena = utf8_encode($cadena);
					return urldecode($cadena);
				}

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

					if ($type == 1) {

				        $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_bot->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_bot->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_bot->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_bot->getCombos($key);

				            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;" class="bots-gallery">';
				            foreach ($combos as $combo) {
											$exp[$key]['mensaje'] .= '<div class="bots-tile">';
				              $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>';
				            };
				            $exp[$key]['mensaje'] .= '</div>';

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

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

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

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

				            };
				            $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_bot->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_bot->putMsgOld($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word);

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


					$buttons = $this->Md_bot->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>';

					$this->Md_bot->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);

		}
	*/
}
