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


	public function response_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		error_log("test ".json_encode($cleanPost ));
		if(isset($cleanPost['message']['url'])) $word = $cleanPost['message']['url'];
		else if(isset($cleanPost['message']['text'])) $word = $cleanPost['message']['text'];
		else $word = FALSE;

		if(isset($cleanPost['message']['type'])) $msgType = $cleanPost['message']['type'];
		else $msgType = FALSE;

		if(isset($cleanPost['user']['name'])) $username = $cleanPost['user']['name'];
		else $username = FALSE;
		if(isset($cleanPost['conversation_name'])) $full_name = $cleanPost['conversation_name'];
		else $full_name = FALSE;
		if(isset($cleanPost['user']['image'])) $profile_pic_url = $cleanPost['user']['image'];
		else $profile_pic_url = FALSE;
		if(isset($cleanPost['conversation'])) $conversation = $cleanPost['conversation'];
		else $conversation = FALSE;
		if(isset($cleanPost['user']['id'])) $pk = $cleanPost['user']['id'];
		else $pk = FALSE;
		if(isset($cleanPost['reply'])) $reply = $cleanPost['reply'];
		else $reply = FALSE;
		if(isset($cleanPost['receiver'])) $accountBot = $cleanPost['receiver'];
		else $accountBot = FALSE;
		if(isset($cleanPost['phoneId'])) $phoneId = $cleanPost['phoneId'];
		else $phoneId = FALSE;

		if($phoneId == 10228) $token = "76e36da0-e199-42ba-88d2-88c396904d2f";
		
		if($phoneId == 10318) $token = "4eddb245-cfd0-4f35-ac1e-9b37313a38a7";

		$type = 1;
		$msg = FALSE;
		$data = array();
		$data['message'] = "";
		$data['buttons'] = array();
		$data['gallery1'] = array();
		$data['gallery2'] = array();
		$data['image'] = FALSE;
		$typeA = 0;
		$account = $this->Md_express->getUserInstagram($accountBot);
		error_log("test ".json_encode($account ));
		if($msgType == "image") $msgType = 3;
		else $msgType = 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])) {

			$botUser = $this->Md_express->getUser($username, $account[0]['id'], $profile_pic_url);
			$keyWord = "";
			$botsKey = 0;

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

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

			if ($type == 1 && count($keys) > 0 && $msgType == 0 && $botUser[0]['active'] == 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'];

						$keyWord = $msg;
						$botsKey = $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://api.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://api.fogatabot.com/admin/advanced/backend/web" . $combo['key_url'],
								'key_url' => $combo['image_url'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery1'] = $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://api.fogatabot.com/admin/advanced/backend/web" . $combo['key_image'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery2'] = $combs;
						$data['type'] = 6;
					}
				} else {
					$mensajes = $this->Md_express->getMensajes2($account[0]['id']);
					if (isset($mensajes[0]['notfound']) && $mensajes[0]['notfound'] != '') {
						$data['message'] = $mensajes[0]['notfound'];
					}
					$data['type'] = 1;
				}

			} else if ($type == 2 && count($keys) > 0 && $msgType == 0 && $botUser[0]['active'] == 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'];
				};

			} else if( $botUser[0]['active'] == 0) {
				$mensajes = $this->Md_express->getMensajes2($account[0]['user_id']);

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

			$this->Md_express->inserInstagramChatNew($botUser[0]['id'], $word, $keyWord, $account[0]['id'], $botsKey,0, $msgType, $profile_pic_url);

			if($data['message']  != "" && $conversation && $reply) {

				$this->Md_express->sendWapiText($reply, $conversation, $data['message'], $token);
				if($data['image']) $this->Md_express->sendWapiImg($reply, $conversation, $data['image'], $token);

				if(!empty($data['buttonsEnc'])) {
					foreach ($data['buttonsEnc'] as $value) {
						$this->Md_express->sendWapiText($reply, $conversation, $value['button'], $token);
					}
				}

				if(!empty($data['buttons'])) {
					foreach ($data['buttons'] as $value) {
						$this->Md_express->sendWapiText($reply, $conversation, $value, $token);
					}
				}

				if(!empty($data['gallery1'])) {
					foreach ($data['gallery1'] as $value) {
						$this->Md_express->sendWapiImg($reply, $conversation, $value['title'], $token);
						$this->Md_express->sendWapiText($reply, $conversation, $value['image_url'], $token);
						
					}
				}

				if(!empty($data['gallery2'])) {
					foreach ($data['gallery2'] as $value) {
						$this->Md_express->sendWapiImg($reply, $conversation, $value['button'], $token);
						$this->Md_express->sendWapiText($reply, $conversation, $value['image_url'], $token);
					}
				}
				
				$this->Md_express->inserInstagramChatNew($botUser[0]['id'], $data['message'], $keyWord, $account[0]['id'], $botsKey,0, 1, $profile_pic_url);

			}

			

				$data['user'] = $username;
				$data['message'] = $word;
				$data['buttons'] =$account[0]['id'];
				$data['gallery'] = $msgType;
				$data['image'] = $pk;
			


			} else {
				$data['type'] = 1;
				$mensajes = $this->Md_express->getMensajes2($account[0]['user_id']);
				$user_id = $this->Md_express->inserInstagram($account[0]['id'], $full_name, $username, $profile_pic_url, $pk);
				if($user_id) $this->Md_express->inserInstagramChatNew($user_id, $word, $keyWord, $account[0]['id'], $botsKey,0, $msgType, $profile_pic_url);
				if (isset($mensajes[0]['response']) && $mensajes[0]['response'] != '') {
					$data['message'] = $mensajes[0]['response'];
				}
			}

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

}
