<?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 Auto 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_auto');
		$this->load->model('Md_bot');
	}

	public function welcome_get() {

			$account = $this->Md_auto->getUser($this->get('auth'));
			$mensajes = $this->Md_auto->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 user_put() {
			$account = $this->Md_auto->getUser($this->put('auth'));
			$ip = $this->put('user');
			$name = $this->put('name');
			$email = $this->put('email');
			$phone = $this->put('phone');
			$device = $this->put('usr_dev');

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

				$return = $this->Md_auto->putUser($account[0]['id'], $ip, $name, $email, $phone, $device);

				if( !empty($name) && !empty($email)) {
					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "http://207.180.216.245/test/odoo/create.php",
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 30,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "POST",
					CURLOPT_POSTFIELDS => "name=$name&email=$email&title=Web%20Bot%20Lead&phone=$phone&website=https%3A%2F%2Fautounioncompany.com&birthdate=&=",
					CURLOPT_HTTPHEADER => array(
						"cache-control: no-cache",
						"content-type: application/x-www-form-urlencoded",
						"postman-token: c44f1b31-bd6f-1ac5-50c7-80a43301683c"
					),
					));

					$response = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);
				}



				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $return, 'odoo' => $response], 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() {
			$account = $this->Md_auto->getUser($this->put('auth'));
			$ip = $this->put('user');
			$word = $this->put('msg');
			$type = $this->put('type');
			$key = $this->put('bots_key_id');
			$device = $this->put('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]) ) {
//aki

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

						$keys = $this->Md_auto->getKeys($account[0]['id']);

						if (strpos($mensaje, normaliza('buscar por precio')) !== false) {

							//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';
									$botones = '<div data-id="1" class="option-button fogata-auto-precio fogata-option-button">Q. 0.00 - Q. 50,000</div>
									<div data-id="2" class="option-button fogata-auto-precio fogata-option-button">Q. 50,000 - Q. 100,000</div>
									<div data-id="3" class="option-button fogata-auto-precio fogata-option-button">Q. 100.000 - Q. 150,000</div>
									<div data-id="4" class="option-button fogata-auto-precio fogata-option-button">Q. 150,000 - Q. 250,000</div>
									<div data-id="5" class="option-button fogata-auto-precio fogata-option-button">Más de Q. 250.000</div>';

									$data = array('mensaje' => 'Selecciona un rango de precio', 'botones' => $botones, 'signup' => 3);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

									$this->Md_auto->putMsg($ip, 'buscar por precio', 0, $account[0]['id'], 0, 0, $device, $word);

						} else if (strpos($mensaje, normaliza('buscar por linea')) !== false) {

						//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';

								$data = array('mensaje' => 'Excelente, por favor escribe la línea del vehículo que estás buscando.', 'botones' =>'', 'signup' => 1, 'carUser' => $word);
								$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

								$this->Md_auto->putMsg($ip, 'buscar por linea', 0, $account[0]['id'], 0, 0, $device, $word);

						} else if (strpos($mensaje, normaliza('buscar por marca')) !== false) {

						//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';

								$data = array('mensaje' => 'Excelente, por favor escribe la marca que estás buscando.', 'botones' =>'', 'signup' => 2, 'modelUser' => $word);
								$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

								$this->Md_auto->putMsg($ip, 'buscar por marca', 0, $account[0]['id'], 0, 0, $device, $word);

								$keyEnc = $this->put('keyenc');

						} else if (strpos($mensaje, normaliza('buscar tipo de caja')) !== false) {

								//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';
								$botones = '<div data-id="1" class="option-button fogata-auto-caja fogata-option-button">Automática</div>
								<div data-id="2" class="option-button fogata-auto-caja fogata-option-button">Mecánica</div>';

								$data = array('mensaje' => 'Excelente, por favor selecciona el tipo de caja que estás buscando.', 'botones' => $botones, 'signup' => 7);
								$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

								$this->Md_auto->putMsg($ip, 'buscar por marca', 0, $account[0]['id'], 0, 0, $device, $word);

								$keyEnc = $this->put('keyenc');

						} else if ($type == 11) {


								$name = $this->put('name');
								$email = $this->put('email');
								$phone = $this->put('phone');

								$curl = curl_init();

								curl_setopt_array($curl, array(
								CURLOPT_URL => "http://207.180.216.245/test/odoo/update.php",
								CURLOPT_RETURNTRANSFER => true,
								CURLOPT_ENCODING => "",
								CURLOPT_MAXREDIRS => 10,
								CURLOPT_TIMEOUT => 30,
								CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
								CURLOPT_CUSTOMREQUEST => "POST",
								CURLOPT_POSTFIELDS => "&title=$word&name=$name&email=$email&phone=$phone",
								CURLOPT_HTTPHEADER => array(
									"cache-control: no-cache",
									"content-type: application/x-www-form-urlencoded",
									"postman-token: c44f1b31-bd6f-1ac5-50c7-80a43301683c"
								),
								));

								$response = curl_exec($curl);
								$err = curl_error($curl);

								curl_close($curl);
							

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

							$this->Md_auto->putMsg($ip, 'actualizar Odoo', 0, $account[0]['id'], 0, 0, $device, $word);


					  }	else if ($type == 3) {

							//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';

									$data = array('mensaje' => 'Excelente, por favor escribe la línea del vehículo que estás buscando.', 'botones' =>'', 'signup' => 4);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

									$this->Md_auto->putMsg($ip, 'buscar por precio modelo', 0, $account[0]['id'], 0, 0, $device, $word);

						}	else if ($type == 7) {

							//	$botones = '<div class="option-button fogata-option-button">Atrás</div>';

									$data = array('mensaje' => 'Excelente, por favor escribe la línea del vehículo que estás buscando.', 'botones' =>'', 'signup' => 5);
									$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

									$this->Md_auto->putMsg($ip, 'buscar por caja modelo', 0, $account[0]['id'], 0, 0, $device, $word);

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



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

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

									$buttons = $this->Md_auto->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_auto->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_auto->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_auto->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_auto->getCombots($key);

								foreach ($combos as $combo) {

									$data['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>';
									$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_auto->getMensajes($account[0]['id']);

								if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
									$data['mensaje'] = $mensajes[0]['notfound'];
								} else {
									$data['mensaje'] = '';
								}

			        }

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

			} else if ($type == 2 && count($keys) > 0) {
				$keyID = $this->put('keyenc_id');
				$key = $this->put('keyenc');
				$respuesta = $this->Md_auto->getEncResp( $key );
				$respuestaID = $this->Md_auto->getEncRespId( $keyID );
			  $data['mensaje'] =  /*$respuesta[0]['text']*/  getEncodeUrl2( $respuesta[0]['text'] );
			  $msg = $respuestaID[0]['button'];


				$buttons = $this->Md_auto->getBotonesEnc($key);


				foreach ($buttons as $btn) {
					$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
				};


				/*$test = 'Únete Al Marketing Inteligente \ud83d\ude00';
				$rest = strpos($data, '\u');
				$rest2 = substr($data, $rest, ($rest + 12)); // devuelve "d"
				$emo = json_decode('"'.$rest2.'"');

				$data =  str_replace($rest2, $emo, $data);*/


				$this->Md_auto->putMsg($ip, $msg, 3, $account[0]['id'], $key, $keyID, $device, $word);
//buscar por linea
} /*else if($type == 4) {
								$carros = '';
								$newArray = $this->Md_auto->getTitles($word);

								if( isset($newArray->data) ) {
									if( isset($newArray->data[0]) ) {
										$carros .= '<div style="width:100%;float:left;">';
										foreach ($newArray->data as $value) {

												$carros .= '</br><a href="'.$value->image.'" target="_blank"><img style="margin-top: 15px;" src="'.$value->image.'" width="100%"></a>';
												$carros .= '<p style="margin: 2px 0 1px"><b>'.$value->post_title.'</b></p>';
												$carros .= '<p style="margin: 1px 0 2px">'.$value->price.' ('.$value->year.')</p>';
												$carros .= '<a href="'.$value->guid.'" target="_blank"><div class="bot-button fogata-bot-button">VER</div></a>';

										}
										$carros .= '</div>';
									} else {
										$carros = 'No hemos conseguido resultados para ese vehículo, puede intentar con otro o buscar por marca.';
									}

								} else{
									$carros = 'No hemos conseguido resultados para ese vehículo, puede intentar con otro o buscar por marca.';
								}
								$botones = '<div class="option-button fogata-option-button">Buscar por Marca</div>
								<div class="option-button fogata-option-button">Buscar por Nombre</div>
								<div class="option-button fogata-option-button">Menú</div>';
								$data = array('mensaje' => $carros, 'botones' => $botones, 'signup' => 0);
								$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
				$this->Md_auto->putMsg($ip, $msg, 3, $account[0]['id'], $key, 0, $device, $word);
// buscar por marca
			} else if($type == 5) {
				$carros = '';
				$newArray = $this->Md_auto->getApi($word);

				if( isset($newArray->data) ) {
					if( isset($newArray->data[0]) ) {
						$carros .= '<div style="width:100%;float:left;">';
						foreach ($newArray->data as $value) {

								$carros .= '</br><a href="'.$value->image.'" target="_blank"><img style="margin-top: 15px;" src="'.$value->image.'" width="100%"></a>';
								$carros .= '<p style="margin: 2px 0 1px"><b>'.$value->post_title.'</b></p>';
								$carros .= '<p style="margin: 1px 0 2px">'.$value->price.' ('.$value->year.')</p>';
								$carros .= '<a href="'.$value->guid.'" target="_blank"><div class="bot-button fogata-bot-button">VER</div></a>';

						}
						$carros .= '</div>';
					} else {
						$carros = 'No hemos conseguido resultados para esa marca de vehículo, puede intentar otra marca.';
					}

				} else{
					$carros = 'No hemos conseguido resultados para esa marca de vehículo, puede intentar otra marca.';
				}
				$botones = '<div class="option-button fogata-option-button">Buscar por Marca</div>
				<div class="option-button fogata-option-button">Buscar por Nombre</div>
				<div class="option-button fogata-option-button">Menú</div>';
				$data = array('mensaje' => $carros, 'botones' => $botones, 'signup' => 0);
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
				$this->Md_auto->putMsg($ip, $msg, 3, $account[0]['id'], $key, 0, $device, $word);
			} */else {
				$mensajes = $this->Md_auto->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);

	}

}
