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

	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_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_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_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])) {
			
			$keys = $this->Md_bot->getKeys($account[0]['id']);
			$typeA = 0;
			$found = FALSE;
			$count = 0;

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

				$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'];
					$exp[$value['id']]['mail_alert'] = $value['mail_alert'];
					$chk[$value['id']] = strtolower($value['key']);
				}

				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 ($type == 2 && count($keys) > 0) {
				$userId = $this->Md_bot->putMsgArray($ip, $msg, 3, $account[0]['id'], $key, $keyId, $device, $word, $typeA);
			} else $userId = $this->Md_bot->putMsgArray($ip, $msg, 0, $account[0]['id'], $key, 0, $device, $word, $typeA);

			$cycles = $this->Md_bot->getCycle($ip, $device, $account[0]['id']);
			//aki
			
			if ($cycles) {
				$respuesta = $this->Md_bot->getEncResp($cycles);
				$data['mensaje'] =  getEncodeUrl2($respuesta[0]['text']);
				$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);
				$data = json_encode($data);
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
			} else {

				if ($userId['bot_cycle'] > 0) {

					if ($userId['bot_cycle'] == 1) {

						if(str_word_count($word,0) > 1) {
							$this->Md_bot->updateOption($userId['id'], array('nombre' => $word), 'web', $account[0]['id']);
							$this->Md_bot->updateCycle(3, $userId['id']);
							$msg = "¡Perfecto! Escribe tu número de teléfono ☎️ Ej: 63745392 sin guiones o espacios";
							$botones = '';
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
						} else {
							$msg = "Debe escribir al menos un apellido Ej: Carlos Sánchez";
							$botones = '';
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
						}
						$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

					} else if ($userId['bot_cycle'] == 3) {

						if(is_numeric($word)) {
							$this->Md_bot->updateOption($userId['id'], array('numero' => $word), 'web', $account[0]['id']);
							$this->Md_bot->updateCycle(4, $userId['id']);
							$msg = "Ahora, escribe tu correo electrónico / email 📧";
							$botones = '';
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
						} else {
							$msg = "Debe escribir el número de teléfono sin guiones, letras, signos o espacios ☎️ Ej: 63745392";
							$botones = '';
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
						}
						$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

					} else if ($userId['bot_cycle'] == 4) {

						if(filter_var($word, FILTER_VALIDATE_EMAIL)) {
							$this->Md_bot->updateOption($userId['id'], array('correo' => $word), 'web', $account[0]['id']);
							$this->Md_bot->updateCycle(5, $userId['id']);
							$msg = "Por favor indícanos tu ingreso familiar 💵 👨‍👩‍👧‍👦 <br>Ej: 1500";
							$botones = '';
	
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
						} else {
							$msg = "Debe escribir una dirección de correo electrónico 📧 válida";
							$botones = '';
	
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
						}

					} else if ($userId['bot_cycle'] == 5) {

						if(is_numeric($word)) {
							$this->Md_bot->updateOption($userId['id'], array('ingreso' => $word), 'web', $account[0]['id']);
							$this->Md_bot->updateCycle(6, $userId['id']);
							$msg = "Por favor indícanos cuanto tiempo llevas laborando en la empresa. Selecciona o escribe la opción que corresponda.";
							$botones = '<div class="option-button fogata-option-button">0 - 6 meses</div>
							<div class="option-button fogata-option-button">6 – 12 meses</div>
							<div class="option-button fogata-option-button">12 meses en adelante</div>';
					
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
						} else {
							$msg = "Debe escribir escribir su ingreso en un número válido, si necesita usar decimales por favor usar punto decimal Ej: 1105.75";
							$botones = '';
					
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
						}

					} else if ($userId['bot_cycle'] == 6) {
						
						if(strpos($mensaje, normaliza('0 - 6 meses')) !== false 
						|| strpos($mensaje, normaliza('6 – 12 meses')) !== false
						|| strpos($mensaje, normaliza('12 meses en adelante')) !== false
						|| strpos($mensaje, normaliza('año')) !== false
						|| strpos($mensaje, normaliza('años')) !== false
						|| strpos($mensaje, normaliza('anos')) !== false
						|| strpos($mensaje, normaliza('ano')) !== false) {

							if(strpos($mensaje, normaliza('0 - 6 meses')) !== false) $test = '0 - 6 meses';
							if(strpos($mensaje, normaliza('6 – 12 meses')) !== false) $test = '6 – 12 meses';
							if(strpos($mensaje, normaliza('12 meses en adelante')) !== false) $test = '12 meses en adelante';
							if(strpos($mensaje, normaliza('año')) !== false) $test = '12 meses en adelante';
							if(strpos($mensaje, normaliza('años')) !== false) $test = '12 meses en adelante';
							if(strpos($mensaje, normaliza('anos')) !== false) $test = '12 meses en adelante';
							if(strpos($mensaje, normaliza('ano')) !== false) $test = '12 meses en adelante';

							$this->Md_bot->updateOption($userId['id'], array('tiempo' => $test), 'web', $account[0]['id']);
							$this->Md_bot->updateCycle(0, $userId['id']);

							$msg = "🙂 Gracias por tu información. Un ejecutivo de ventas se contactará contigo. 
							<br><br>
							Te invitamos a conocer nuestros tour virtuales: <br>
							🖱️ <a style='text-decoration: underline;color: #fff' href='https://inmerso3d.online/3d-model/casapropia-lafloresta/fullscreen/' target='_blank'>Floresta Casa Modelo</a> 
							<br><br>
							Si deseas conocer más opciones por favor escribe o selecciona “Volver al Menú”
							";
							$botones = '<div class="option-button fogata-option-button">Volver al Menú</div>';

							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

						} else {

							$msg = "Debe seleccionar una de las siguientes opciones";
							$botones = '<div class="option-button fogata-option-button">0 - 6 meses</div>
							<div class="option-button fogata-option-button">6 – 12 meses</div>
							<div class="option-button fogata-option-button">12 meses en adelante</div>';
					
							$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
							$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

						}

					}
					


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

					if (strpos($mensaje, normaliza('aplicar')) !== false) {
						$this->Md_bot->updateCycle(1, $userId['id']);
						$msg = "¡Gracias! Por favor escribe tu nombre y apellido ⌨️ <br>Ej: Carlos Sanchez";
						$botones = '';
						//$botones = '<div class="option-button fogata-option-button">Cupones Acumulados</div>';
						//<div class="option-button fogata-option-button">Solicitud Canje de cupones</div>

						$data = array('mensaje' => $msg, 'botones' => $botones, 'signup' => 1);
						$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

					} else if ($found == TRUE && $userId['bot_cycle'] == 0) {

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