<?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 Meykos 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_express');
		$this->load->model('Md_bot');
		$this->load->model('Md_meykos');
	}

	public function users_get()
	{

		$auth = $this->get('auth');
		$channel = $this->get('channel');

		if (isset($auth) && isset($channel)) {

			$account = $this->Md_express->getUseradm($this->get('auth'));

			if ($account) {
				$users = $this->Md_express->getUsers($account[0]['id'], $this->get('channel'));

				if ($users) {
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Users per channel', 'data' => $users], REST_Controller::HTTP_OK);
				} else {
					$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'No clients found', 'data' => ''], REST_Controller::HTTP_OK);
				}
			} else {
				$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'User not found', 'data' => ''], REST_Controller::HTTP_OK);
			}
		} else {
			$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'Parameter Missing', 'data' => ''], REST_Controller::HTTP_OK);
		}
	}

	public function messages_get()
	{

		$auth = $this->get('auth');
		$channel = $this->get('channel');
		$client_id = $this->get('client_id');

		if (isset($auth) && isset($channel) && isset($client_id)) {

			$account = $this->Md_express->getUseradm($this->get('auth'));

			if ($account) {
				$messages = $this->Md_express->getMessages($this->get('client_id'), $this->get('channel'), $account[0]);

				if ($messages) {
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Client messages', 'data' => $messages], REST_Controller::HTTP_OK);
				} else {
					$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No client found', 'data' => array()], REST_Controller::HTTP_OK);
				}
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'User not found', 'data' => array()], REST_Controller::HTTP_OK);
			}
		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Parameter Missing', 'data' => array()], REST_Controller::HTTP_OK);
		}
	}

	public function messages_post() {

		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		if( isset($cleanPost['auth']) && isset($cleanPost['channel']) && isset($cleanPost['client_id']) && isset($cleanPost['msg']) ) {

			$auth = $cleanPost['auth'];
			$channel = $cleanPost['channel'];
			$client_id = $cleanPost['client_id'];
			$msg = $cleanPost['msg'];

			if(isset($cleanPost['url'])) $url = $cleanPost['url'];
			else $url = FALSE;
			if(isset($cleanPost['caption'])) $caption = $cleanPost['caption'];
			else $caption = FALSE;

			$account = $this->Md_express->getUseradm( $auth );

			if($account){
				$messages = $this->Md_express->putMessages( $client_id, $channel, $msg, $account, $url, $caption);

				if( $messages ) {
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Message sent', 'data' => $messages], REST_Controller::HTTP_OK);
				} else {
					$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'Client not found', 'data' => ''], REST_Controller::HTTP_OK);
				}

			} else{
				$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'User not found', 'data' => ''], REST_Controller::HTTP_OK);
			}

		} else {
			$this->set_response(['status' => TRUE, 'codigo' => 1, 'message' => 'Parameter Missing', 'data' => ''], REST_Controller::HTTP_OK);
		}

	}

	public function welcome_get()
	{

		$mensajes = $this->Md_express->getMensajes($this->get('phone'));

		if (isset($mensajes[0]['response']) && $mensajes[0]['response'] != '') {
			$data = $mensajes[0]['response'];
		} 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_express->getUser($cleanPost['phone']);
		$ip = $cleanPost['user'];
		$device = $cleanPost['usr_dev'];

		$data = [];
		$data['mensaje'] = '';
		$data['bot'] = '';

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

			$return = $this->Md_express->getLive($account[0]['user_id'], $ip, $device);

			if ($return) {
				$data['bot'] = $return[0]['bot'];
				$return2 = $this->Md_express->putLive($return, $account[0]['user_id']);
				if (!empty($return2)) {
					foreach ($return2 as $value) {
						$data['mensaje'] .=  '<div style="width:100%;float:left;">';
						$data['mensaje'] .= '<div class="fogata-bot-response">' . base64_decode($value['message']) . '</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' => 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_put()
	{

		$post = $this->put();
		$cleanPost = $this->security->xss_clean($post);

		$account = $this->Md_express->getUser($cleanPost['phone']);

		$phone_client = $cleanPost['phone_client'];
		$phone = $cleanPost['phone'];
		$account_id = $account[0]['user_id'];

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

			$return = $this->Md_express->putUser($phone_client, $phone, $account_id);

			if ($return)

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

			else

				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'User already exists or not created', '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 response_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		function normaliza($cadena)
		{
			$originales =  'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ?¿';
			$modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr?¿';
			$cadena = utf8_decode($cadena);
			$cadena = strtr($cadena, utf8_decode($originales), $modificadas);
			$cadena = strtolower($cadena);
			return utf8_encode($cadena);
		}

		$data = $this->Md_meykos->getKeys($cleanPost);

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

	}

	public function answer_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		if(isset($cleanPost['msg'])) $word = $cleanPost['msg'];
		else $word = FALSE;
		if(isset($cleanPost['type'])) $type = $cleanPost['type'];
		else $type = FALSE;
		if(isset($cleanPost['account'])) $accountBot = $cleanPost['account'];
		else $accountBot = FALSE;

		$account = $this->Md_bot->getUser($cleanPost['auth']);

		$msg = FALSE;
		$data = array();
		$data['message'] = "";
		$data['buttons'] = array();
		$data['gallery'] = array();
		$data['image'] = array();
		$typeA = 0;
		

		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]['id'])) {

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

			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'];
					$chk[$value['id']] = 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) {
						$maxi = max(array_column($hooman, 'msg'));
						$key = array_search($maxi, array_column($hooman, 'msg'));
						$msg = $hooman[$key]['text'];
						$key = $hooman[$key]['key'];
						$typeA = $exp[$key]['key'];
						$data['message'] = base64_decode($exp[$key]['mensaje']);
						$data['type'] = 1;
					if ($exp[$key]['key'] == 2) {
						$buttons = $this->Md_express->getBotones($key);
						foreach ($buttons as $btn) {
							$data['buttons'][] = $btn['button'];
						};
						$data['type'] = 2;
					} else if ($exp[$key]['key'] == 3) {
						$image = $this->Md_express->getImage($key);
						foreach ($image as $img) {
							$data['image'][] = "https://fogatabot.com/admin/advanced/backend/web" . $img['key_url'];
						};
						$data['type'] = 3;
					} else if ($exp[$key]['key'] == 4) {
						$buttons = $this->Md_express->getEncuestas($key);
						$enc = array();
						foreach ($buttons as $btn) {
							$enc[] = array(
								'bots_keys_id' => $btn['bots_keys_id'],
								'keyenc_id' => $btn['id'],
								'button' => $btn['button'],
							);
						};
						$data['buttonsEnc'] = $enc;
						$data['type'] = 4;
					} else if ($exp[$key]['key'] == 5) {
						$combos = $this->Md_express->getCombos($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'title' => $combo['title'],
								'subtitle' => $combo['subtitle'],
								'image_url' => "https://fogatabot.com/admin/advanced/backend/web" . $combo['key_url'],
								'key_url' => $combo['image_url'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery'] = $combs;
						$data['type'] = 5;
					} else if ($exp[$key]['key'] == 6) {
						$combos = $this->Md_express->getCombots($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'image_url' => "https://fogatabot.com/admin/advanced/backend/web" . $combo['key_image'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery'] = $combs;
						$data['type'] = 6;
					}
				} else {
					$mensajes = $this->Md_express->getMensajes($account[0]['id']);
					if (isset($mensajes[0]['notfound']) && $mensajes[0]['notfound'] != '') {
						$data['message'] = $mensajes[0]['notfound'];
					}
					$data['type'] = 1;
				}

				//$this->Md_express->putMsg($ip, $msg, 0, $account[0]['user_id'], $key, 0, $device, $word, $typeA);

			} else if ($type == 2 && count($keys) > 0) {
				$keyID = $cleanPost['keyenc_id'];
				$key = $cleanPost['bots_key_id'];
				$respuesta = $this->Md_express->getEncResp($key);
				$respuestaID = $this->Md_express->getEncRespId($keyID);
				$data['message'] = $respuesta[0]['text'];
				$msg = $respuestaID[0]['button'];

				$buttons = $this->Md_express->getbuttonsEnc($key);

				foreach ($buttons as $btn) {
					$data['buttons'][] = $btn['button'];
				};

				//$this->Md_express->putMsg($ip, $msg, 3, $account[0]['user_id'], $key, $keyID, $device, $word, $typeA);
			} else {
				$mensajes = $this->Md_express->getMensajes($account[0]['id']);

				if (isset($mensajes[0]['notfound']) && $mensajes[0]['notfound'] != '') {
					$data['message'] = $mensajes[0]['notfound'];
				}
				$data['type'] = 1;
			}


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