<?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 Testa extends REST_Controller {

		function __construct() {
		parent::__construct();
		//$this->load->model('Md_facebook');
		$this->load->model('Md_bota');
	}

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

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

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

			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_bota->getKeys($account[0]['id']);

				if ($type == 1) {

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

			        //$hilos = json_decode($keys);

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

							$found = FALSE;
							$count = 0;

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

			        if($found == TRUE){

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

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

								if(	$exp[$key]['key'] == 2  ){
									$buttons = $this->Md_bota->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_bota->getImage($key);
			            $exp[$key]['mensaje'] .= '<div style="width:100%;float:left;">';
			            foreach ($image as $img) {
			              $exp[$key]['mensaje'] .= '<img src="https://bots.aldeamo.com'.$img['key_url'].'" width="100%">';
			            };
			            $exp[$key]['mensaje'] .= '</div>';

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

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

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

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

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

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

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

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

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

			          };

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

			        } else {

								$mensajes = $this->Md_bota->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 = $this->put('keyenc_id');
				$key = $this->put('keyenc');
				$respuesta = $this->Md_bota->getEncResp( $key );
				$respuestaID = $this->Md_bota->getEncRespId( $keyID );
			  $data =  /*$respuesta[0]['text']*/  getEncodeUrl2( $respuesta[0]['text'] );
			  $msg = $respuestaID[0]['button'];

			}

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

	}



}
