<?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 Test 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 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' => array()], REST_Controller::HTTP_OK);
	}

	public function webchat_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;

			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://api.fogatabot.com/admin/advanced/backend/web'.$img['key_url'].'" target="_blank"><img src="https://api.fogatabot.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;">';
			            foreach ($combos as $combo) {

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

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

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

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

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

			              $exp[$key]['mensaje'] .= '</br><a href="https://api.fogatabot.com/admin/advanced/backend/web'.$combo['key_image'].'" target="_blank"><img style="margin-top: 15px;" src="https://api.fogatabot.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. ☺';
								}

			        }

			} else if ($type == 2) {
				$keyID = $cleanPost['keyenc_id'];
				$key = $cleanPost['keyenc'];
				$respuesta = $this->Md_bot->getEncResp( $key );
				$respuestaID = $this->Md_bot->getEncRespId( $keyID );
			  $data =  /*$respuesta[0]['text']*/  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->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'] = '';

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

					$respuesta = $this->Md_bot->getEncResp( $cycles );
					//$respuestaID = $this->Md_bot->getEncRespId( $keyID );
					$data['mensaje'] =  /*$respuesta[0]['text']*/  getEncodeUrl2( $respuesta[0]['text'] );
					//$msg = $respuestaID[0]['button'];
					$buttons = $this->Md_bot->getBotonesEnc( $cycles );
					foreach ($buttons as $btn) {
						$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
					};

					$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'];
								$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://api.fogatabot.com/admin/advanced/backend/web'.$img['key_url'].'" target="_blank"><img src="https://api.fogatabot.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);

			            foreach ($combos as $combo) {

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

			            };

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

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

										foreach ($combos as $combo) {

											$data['mensaje'] .= '</br><a href="https://api.fogatabot.com/admin/advanced/backend/web'.$combo['key_image'].'" target="_blank"><img style="margin-top: 15px;" src="https://api.fogatabot.com/admin/advanced/backend/web'.$combo['key_image'].'" width="100%"></a>';
											$data['mensaje'] .= '<div class="bot-button fogata-option-button">'.$combo['button'].'</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>';

			          };

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

			        }

			} else if ($type == 2 && count($keys) > 0) {
				$keyID = $cleanPost['keyenc_id'];
				$key = $cleanPost['keyenc'];
				$respuesta = $this->Md_bot->getEncResp( $key );
				$respuestaID = $this->Md_bot->getEncRespId( $keyID );
			  $data['mensaje'] =  /*$respuesta[0]['text']*/  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>';
				};

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

	}

}
