<?php
ini_set("display_errors", 1);
if (!defined('BASEPATH'))
	exit('No direct script access allowed');


class Md_colbot extends CI_Model {
	public function putData( $data )
	{

		$myfile = fopen("/var/www/html/webhook/whatsapp.txt", "a") or die("Unable to open file!");
		fwrite($myfile, $data."\n");
		fclose($myfile);

		return $data;

	}

	public function getMessages( $json )
	{
		$data = json_decode($json);
		
		if (json_last_error() !== JSON_ERROR_NONE) {
			$json = str_replace("\\","\\\\",$json);
			$json = mb_convert_encoding($json, 'UTF-8', 'UTF-8');
			$data = json_decode( $json);
			error_log("test utf8 ".json_encode(json_last_error_msg()));
		}
		
		$isGroup = FALSE;
		if(isset($data->message->id)) {
			
			$timestamp = $data->timestamp;
			if(isset($data->participants)) {
				$isGroup = TRUE;
				$uid = $data->message->id.$data->receiver;
			} else {
				$uid = $data->message->id;
			}
		} else {
			$uid = 0;
			$timestamp = 0;
		}
		
		$testUid = $this->testMsg($uid);
		
		if(isset($data->message->id) && strpos($data->message->id, "false") !== false && $timestamp > (time() - (2*24*60*60)) && $testUid) {
			
			$msgType = $data->message->type;
			$reply = $data->reply;
			$token = $data->phoneId;
			$productId = $data->product_id;
			
			if(isset($data->message->fromMe)) {
				$validate = $data->message->fromMe;
			} else {
				$validate = FALSE;
			}
			
			$to = $data->receiver;
			
			if(isset($data->user->image)) $avatar = $data->user->image;
			else $avatar = "https://fogatabot.com/user-profile/47/Admin.png";
		
			
			$botId = "";
			$lastActive = "";
			$user = 0;
			$cycle = 0;
			$type = 0;
			$key = 0;
			$account_id = 0;
			$agent = 0;
			$chatId = "";
			$key = 0;
			$image = "";
			$msg = "";
			$account = array();
			$ticket = FALSE;
			$webhookMsg = 0;
			$botAnswer = FALSE;
			$pk = 0;

			if($msgType == "text") $type = 1;
			else if($msgType == "vcard") $type = 1;
			else if($msgType == "location") $type = 1;
			else if($msgType == "image") $type = 3;
			else if($msgType == "sticker") $type = 3;
			else if($msgType == "ptt") $type = 6;
			else if($msgType == "audio") $type = 6;
			else if($msgType == "video") $type = 9;
			else if($msgType == "document") $type = 12;
			else if($msgType == "document") $type = 12;

//"subtype":"call/miss",
			
			if(isset($data->participants)) {
				$from = $data->conversation;
				$name = $data->conversation_name;
				$pk = 1;
			} else {
				$from = $data->user->phone;
				$name = $data->user->name;
			}

			//if($from == 50760816607) error_log("quoted audio ".$json);
			
			if($msgType == "location" && isset($data->message->payload)) {
				$location = $data->message->payload;
				$word = "<a href='https://www.google.com/maps/@$location,18z' target='_blank'>https://www.google.com/maps/@$location,18z</a>";
			} else if(isset($data->message->vcardList[0]->vcard)) {
				$vcard = $data->message->vcardList[0]->vcard;
				$word = "";
				$vcard = explode(";", $vcard);
				if(isset($vcard[1])) $word .= "Contact: ".$vcard[1]."<br>";
				if(isset($vcard[5])) $word .= "Type: ".$vcard[5]."<br>";
				if(isset($vcard[6])) $word .= "Number: ".$vcard[6];
			} else if(isset($data->message->text)) {
				$word = $data->message->text;
			} else if(isset($data->message->subtype) && $data->message->subtype == "call/miss") {
				$type = 1;
				$word = "<b>Missed call 📞</b>";
			} else $word = "";

			if(isset($data->message->url)) $url = $data->message->url;
			else $url = "";

			if(isset($data->message->caption) && empty($word)) $word = $data->message->caption;
			
			$message = $word;

			$account = $this->getAccount($to);
			
			$token = $account['token'];



			error_log("visual send 0 ".$from);
			error_log("visual send 1 ".$to);

			//error_log("ticket send 0 ".json_encode($account));
			if($account) {
				
				$contactGroup = $account['group'];
				$ai = $account['ai'];
				$account_id = $account['user_id'];
				$botId = $account['bot_id'];
				$botActive = $account['active'];
				$admin = $this->getAdmin($account_id);
				$botUser = $this->getUser($from, $to, $account_id, $name, $avatar);
				$cycle = $botUser['data']['bot_cycle'];

error_log("visual send 2 ".$cycle);
				if(isset($admin[0]['status'] ) && $admin[0]['status'] == 10) {
					
					$user = $botUser['data']['id'];

			$dataKey = json_decode($json);
			$dataKey->error = 0;
			$dataKey->text = $word;
			$dataKey->bot_key = 0;
			$dataKey->userId = $user;
			$dataKey->receiver = $to;
			$dataKey->botUser = $user;
			$dataKey->cycle = $cycle;
			$dataKey->lastActive = $lastActive;
			$dataKey->chatId = $chatId;
			$json = json_encode($dataKey);


			if(!empty($account['webhook']) && empty($account['webhookai'])) {
				$webhookMsg = $this->sendWebhook($account['webhook'], $json);
				$webhookMsg = json_decode($webhookMsg);

				if(isset($webhookMsg->next_cycle)) {
					$cycle = $webhookMsg->danext_cycleta;
				}
				$this->updateCycle($user, $cycle);
		error_log($webhookMsg);
			error_log($cycle);
				if(isset($webhookMsg->data)) $webhookMsg = $webhookMsg->data;
				else $webhookMsg = 0;
			}

	

					if($pk==1) $this->updateGroup($user);
					$userBotActive = $botUser['data']['active'];

					if (isset($botUser['data']['id']) && $botUser['error'] == 0 && $botUser['data']['deleted'] == 0) { 
						
						if(isset($data->quoted)) {
							if($data->quoted->type == "text") $this->putMessage($user,1,"<b>Reply to: </b>".$data->quoted->text,$key,$account_id,$agent,$uid);
							if($data->quoted->type == "image") $this->putMessage($user,3,$data->quoted->url,$key,$account_id,$agent,$uid);
						}

						if(!empty($word) && $type != 12 && $type != 6) $chatId = $this->putMessage($user,1,$word,$key,$account_id,$agent,$uid);
						if(!empty($url)) $chatId = $this->putMessage($user,$type,$url,$key,$account_id,$agent,$uid);


						$dataKey = json_decode($json);
						$dataKey->error = 0;
						$dataKey->text = $word;
						$dataKey->bot_key = 0;
						$dataKey->userId = $user;
						$dataKey->receiver = $to;
						$dataKey->botUser = $user;
						$dataKey->cycle = $cycle;
						$dataKey->lastActive = $lastActive;
						$dataKey->chatId = $chatId;
						$dataKey->instructions = $account['instructions'];
						$json = json_encode($dataKey);


						/*if(empty($cycle) && empty($webhookMsg) && empty($account['webhookai'])) {

							$botAnswer = $this->findAnswer( $account_id, $word, $botId );
						
							if(!empty($botAnswer['webhook'])) {
								$dataKey = json_decode($json);
								$dataKey->bot_key = $botAnswer['key'];
								$json = json_encode($dataKey);
								$webhookMsg = $this->sendWebhook($botAnswer['webhook'], $json);

								$webhookMsg = json_decode($webhookMsg);
								if(isset($webhookMsg->status) && !empty($webhookMsg->data)) {
									$botAnswer['message'] = $webhookMsg->data;
									$botAnswer['buttons'] = array();
									$botAnswer['alert'] = FALSE;
									$botAnswer['keyWord'] = 0;
								}
							}

							if($botAnswer['cycle']) $this->updateCycle($user, $botAnswer['cycle']);
							else $this->updateCycle($user, 0);
						} else if(empty($cycle) && !empty($account['webhookai']) && $ai) {

							error_log("test key ".$webhookMsg);

							$botAnswer = $this->findAnswer( $account_id, $word, $botId );
							
							if(!empty($botAnswer['webhook'])) {
								$dataKey = json_decode($json);
								$dataKey->bot_key = $botAnswer['key'];
								$json = json_encode($dataKey);
								$webhookMsg = $this->sendWebhook($botAnswer['webhook'], $json);

								$webhookMsg = json_decode($webhookMsg);
								if(isset($webhookMsg->status) && !empty($webhookMsg->data)) {
									$botAnswer['message'] = $webhookMsg->data;
									$botAnswer['buttons'] = array();
									$botAnswer['alert'] = FALSE;
									$botAnswer['keyWord'] = 0;
								}
							}

							if(empty($botAnswer['message'])){

								$webhookMsg = $this->sendWebhook($account['webhookai'], $json);
								$webhookMsg = json_decode($webhookMsg);
								if(isset($webhookMsg->data)) $webhookMsg = $webhookMsg->data;
								else $webhookMsg = 0;


								$botAnswer['message'] = $webhookMsg;
								$botAnswer['buttons'] = array();
								$botAnswer['alert'] = FALSE;
								$botAnswer['keyWord'] = 0;
							}

							if($botAnswer['cycle']) $this->updateCycle($user, $botAnswer['cycle']);
							else $this->updateCycle($user, 0);

						} else if( empty($webhookMsg) ) {

							$answer = $this->getKey($cycle, $account_id);
							if(isset($answer[0]['key'])) {
								$thisKey = strtolower($answer[0]['key']);
								$thisKey = explode(",",$thisKey);
								$botAnswer = $this->findAnswer( $account_id, $thisKey[0], $botId );

								if(!empty($botAnswer['webhook'])) {
									$dataKey = json_decode($json);
									$dataKey->bot_key = $botAnswer['key'];
									$json = json_encode($dataKey);
									$webhookMsg = $this->sendWebhook($botAnswer['webhook'], $json);

									$webhookMsg = json_decode($webhookMsg);
									if(isset($webhookMsg->status) && !empty($webhookMsg->data)) {
										$botAnswer['message'] = $webhookMsg->data;
										$botAnswer['buttons'] = array();
										$botAnswer['alert'] = FALSE;
										$botAnswer['keyWord'] = 0;
									}
								}

								if($botAnswer['cycle']) $this->updateCycle($user, $botAnswer['cycle']);
								else $this->updateCycle($user, 0);
							} else {
								$this->updateCycle($user, 0);
							};
						} else*/ if( !empty($webhookMsg) ) {

							if( !empty($cycle) ) {
								$answer = $this->getKey($cycle, $account_id);
							}

							if(isset($answer[0]['key'])) {
								$thisKey = strtolower($answer[0]['key']);
								$thisKey = explode(",",$thisKey);
								$botAnswer = $this->findAnswer( $account_id, $thisKey[0], $botId );

								if(!empty($botAnswer['webhook'])) {
									$dataKey = json_decode($json);
									$dataKey->bot_key = $botAnswer['key'];
									$dataKey->cycle = $botAnswer['cycle'];
									$json = json_encode($dataKey);


									$webhookMsg = $this->sendWebhook($botAnswer['webhook'], $json);

									$webhookMsg = json_decode($webhookMsg);

									if(isset($webhookMsg->status) && !empty($webhookMsg->data)) {
										$botAnswer['message'] = $webhookMsg->data;
										$botAnswer['buttons'] = FALSE;
									} else {
										if($botAnswer['cycle']) $this->updateCycle($user, $botAnswer['cycle']);
										else $this->updateCycle($user, 0);
									}
								} else {
									if($botAnswer['cycle']) $this->updateCycle($user, $botAnswer['cycle']);
									else $this->updateCycle($user, 0);
								}


							} else {
								$botAnswer['message'] = $webhookMsg;
								$botAnswer['buttons'] = array();
								$botAnswer['alert'] = FALSE;
								$botAnswer['keyWord'] = 0;
							};
							
						}

					/*	if(isset($admin[0]['contact']) && $admin[0]['contact'] == 1 && $botAnswer['alert'] && !$isGroup) $ticket = $this->putTicket($user, 4, $account_id, $word, $key, $botAnswer['keyWord'], $chatId, $contactGroup);
						else if(empty($botAnswer['message']) && isset($admin[0]['contact']) && $admin[0]['contact'] == 1 &&  empty($account['notfound']) && !$isGroup) {
							$ticket = $this->putTicket($user, 4, $account_id, $word, $key, "Auto Generated", $chatId, $contactGroup);
						}
						
						if($ticket && !empty($account['ticket_answer'])) {
							$this->putMessage($user,0,$account['ticket_answer'].$ticket,$key,$account_id,$agent,$uid);
							$this->sendMessage(base64_decode($account['ticket_answer']).$ticket, $url, $token, $reply, $from);
						}*/

						if(isset($botAnswer['image'][0])) { //Imagen sola
							$image = $botAnswer['image'][0];
							$message = $botAnswer['message'];
							$key = $botAnswer['key'];
							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $token, $reply, $from);
								$this->putMessage($user,4,$image,$key,$account_id,$agent,$uid);
								if(!empty($message)) $this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}
	
						} else if(isset($botAnswer['buttons'][0])) { //Mensaje con botones
							$buttons = $botAnswer['buttons'];
							$message = $botAnswer['message'];
							$key = $botAnswer['key'];
							foreach ($buttons as $key => $value) {
								$message .= "\n*".base64_decode($value)."*";
							}
							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $token, $reply, $from);
								$this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}
							
						} else if(isset($botAnswer['gallery'][0]['title'])) { //Galería de imágenes
							$galery = $botAnswer['gallery'];
							$message = $botAnswer['message'];
							$key = $botAnswer['key'];
							$imgMessage="";

							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $token, $reply, $from);
								$this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}
							
							foreach ($galery as $key => $value) {
								$image = $value['image_url'];
								$imgMessage .= "\n*".$value['title']."*";
								$imgMessage .= "\n".$value['subtitle']."";
								$imgMessage .= "\n*".$value['button']."*";
								$imgMessage .= "\n*".$value['key_url']."*";

								if($botActive == 1 && $userBotActive == 1 ) {
									$this->sendMessage($imgMessage, $image, $token, $reply, $from);
									$this->putMessage($user,4,$image,$key,$account_id,$agent,$uid);
									$this->putMessage($user,0,$imgMessage,$key,$account_id,$agent,$uid);
								}

								$imgMessage="";
							}
						} else if(isset($botAnswer['gallery'][0]['image_url'])) { //Botones con imágenes
							$galery = $botAnswer['gallery'];
							$message = $botAnswer['message'];
							$key = $botAnswer['key'];
							$imgMessage="";

							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $token, $reply, $from);
								$this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}
							
							foreach ($galery as $key => $value) {
								$image = $value['image_url'];
								$imgMessage .= "\n*".$value['button']."*";
								if($botActive == 1 && $userBotActive == 1 ) {
									$this->sendMessage($imgMessage, $image, $token, $reply, $from);
									$this->putMessage($user,4,$image,$key,$account_id,$agent,$uid);
									$this->putMessage($user,0,$imgMessage,$key,$account_id,$agent,$uid);
								}

								$imgMessage="";
							}
						} else if(!empty($botAnswer['message'])) { //Mensaje sólo
							$message = $botAnswer['message'];
							$key = $botAnswer['key'];
							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $token, $reply, $from);
								$this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}

						} else if(!empty($word)) { //Mensaje no encontrado
							$message = base64_decode($account['notfound']);
							$key = 0;
							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage($message, $image, $productId, $reply, $from);
								$this->putMessage($user,0,$message,$key,$account_id,$agent,$uid);
							}

						}  
	
						/*$bottype = [
							'0' => 'bot',
							'1' => 'user',
							'2' => 'agent',
							'3' => 'userimage',
							'4' => 'botimage',
							'5' => 'agentimage',
							'6' => 'useraudio',
							'7' => 'botaudio',
							'8' => 'agentaudio',
							'9' => 'uservideo',
							'10' => 'botvideo',
							'11' => 'agentvideo',
							'12' => 'userdocument',
							'13' => 'botdocument',
							'14' => 'agentdocument',
						  ];*/
	
	
					} else if (isset($botUser['data']['id']) && $botUser['error'] == 1) { //New user response
	
						$user = $botUser['data']['id'];
						if(!empty($word) && $type != 12) $chatId = $this->putMessage($user,1,$word,$key,$account_id,$agent,$uid);
						if(!empty($url)) $chatId = $this->putMessage($user,$type,$url,$key,$account_id,$agent,$uid);

						$msg = base64_decode($account['response']);
						$url = $account['image'];
						if(!empty($account['key'])){
							$keys = explode(',', $account['key']);
							foreach ($keys as $key => $value) {
								$msg .= "\n*".base64_decode($value)."*";
							}
						}

						$dataKey = json_decode($json);
						$dataKey->bot_key = 0;
						$dataKey->error = $botUser['error'];
						$dataKey->text = $word;
						$dataKey->userId = $user;
						$dataKey->botUser = $user;
						$dataKey->chatId = $chatId;
						$json = json_encode($dataKey);

						if(!empty($account['webhook'])) {
							$webhookMsg = $this->sendWebhook($account['webhook'], $json);
						}

						if($botActive == 1) {
							if(!empty($url)) {
								$this->sendMessage("", $url, $token, $reply, $from);
								$this->putMessage($user,0,$url,$key,$account_id,$agent,$uid);
							}
							if(!empty($msg)) {
								$this->sendMessage($msg, "", $token, $reply, $from);
								$this->putMessage($user,0,$msg,$key,$account_id,$agent,$uid);
							}

						}
					}
				}


			}

		}

		return $data;

	}

	public function sendMessage( $msg, $url, $productId, $reply, $from )
	{
		$response = FALSE;
		setlocale(LC_CTYPE, 'es_CO.UTF-8');

        $msg = str_replace("\\\n", "\\n", $msg);
        $msg = str_replace("\n", "\\n", $msg);
        $msg = str_replace("\t", " ", $msg);
        $msg = str_replace("\\t", " ", $msg);
        $msg = str_replace("\b", " ", $msg);
        $msg = str_replace("\\b", " ", $msg);
        $msg = str_replace("\a", " ", $msg);
        $msg = str_replace("\\a", " ", $msg);
        $msg = str_replace("\r", " ", $msg);
        $msg = str_replace("\\r", " ", $msg);
        $msg = str_replace('"', "*", $msg);

		if(!empty($url)) {
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => $reply,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => '',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 3,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => 'POST',
				CURLOPT_POSTFIELDS =>'{"to_number": "'.$from.'","type": "media","message": "'.$url.'","text": "'.$msg.'"}',
				CURLOPT_HTTPHEADER => array(
				'x-maytapi-key: '.$productId,
				'Content-Type: application/json',
				'Cookie: __cfduid=df314b968d3e688844e5610aef92daba81611443255'
				),
			));
			$response = curl_exec($curl);

			/*error_log('{"to_number": "'.$from.'","type": "media","message": "'.$url.'","text": "'.$msg.'"}');
			error_log("maytapi ".$productId);
			error_log("maytapi ".$response);*/

			curl_close($curl);
		} else if(!empty($msg)) {
			$curl = curl_init();
			curl_setopt_array($curl, array(
			CURLOPT_URL => $reply,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 3,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>'{"to_number": "'.$from.'","type": "text","message": "'.$msg.'"}',
			CURLOPT_HTTPHEADER => array(
				'x-maytapi-key: '.$productId,
				'Content-Type: application/json',
				'Cookie: __cfduid=df314b968d3e688844e5610aef92daba81611443255'
			),
			));
			$response = curl_exec($curl);

			/*error_log('{"to_number": "'.$from.'","type": "media","message": "'.$url.'","text": "'.$msg.'"}');
			error_log("maytapi ".$productId);
			error_log("maytapi ".$response);*/

			curl_close($curl);
		}

		return $response;


	}

	
	public function updateCycle($id, $cycle) {
		$whatsClient = array(
			'bot_cycle' => $cycle,
		);
		$this->db->where('id', $id);
		$this->db->update('bots_whatsapp_user', $whatsClient);
	}

	public function updateGroup($id) {
		$whatsClient = array(
			'pk' => 1,
		);
		$this->db->where('id', $id);
		$this->db->update('bots_whatsapp_user', $whatsClient);
	}

	/*public function findAnswer( $account, $msg, $botId  )
	{

		$data = array();
		$data['message'] = "";
		$data['buttons'] = array();
		$data['gallery'] = array();
		$data['image'] = array();
		$data['alert'] = 0;
		$data['key'] = 0;
		$data['keyWord'] = "";
		$data['webhook'] = "";
		$data['cycle'] = 0;
		$typeA = 0;
		$key = 0;
			
			$keyWord = "";
			$botsKey = 0;

			$keys = $this->getKeys($account, $botId);

			if (count($keys) > 0) {

				$mensaje = strtolower($msg);
				$mensaje = urldecode($mensaje);
				$mensaje = $this->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'];
					$exp[$value['id']]['alert'] = $value['mail_alert'];
					$exp[$value['id']]['cycle'] = $value['bot_cycle'];
					$exp[$value['id']]['webhook'] = $value['webhook'];
					$chk[$value['id']] = strtolower($value['key']);
				}

				$found = FALSE;
				$count = 0;

				foreach ($chk as $value) {
					$value2 = explode(",", $value);
					foreach ($value2 as $value3) {
						if (strpos($mensaje, $this->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;

						$data['keyWord'] = $keyWord;

						$typeA = $exp[$key]['key'];
						$data['message'] = base64_decode($exp[$key]['mensaje']);
						$data['type'] = 1;
						$data['key'] = $key;
						$data['alert'] = $exp[$key]['alert'];
						$data['cycle'] = $exp[$key]['cycle'];
						$data['webhook'] = $exp[$key]['webhook'];

					if ($exp[$key]['key'] == 2) {
						$buttons = $this->getBotones($key);
						foreach ($buttons as $btn) {
							$data['buttons'][] = $btn['button'];
						};
						$data['type'] = 2;
					} else if ($exp[$key]['key'] == 3) {
						$image = $this->getImage($key);
						foreach ($image as $img) {
							$data['image'][] = "https://fogatabots.com" . $img['key_url'];
						};
						$data['type'] = 3;
					} else if ($exp[$key]['key'] == 4) {
						$buttons = $this->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->getCombos($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'title' => $combo['title'],
								'subtitle' => $combo['subtitle'],
								'image_url' => "https://fogatabots.com" . $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->getCombots($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'image_url' => "https://fogatabots.com" . $combo['key_image'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery'] = $combs;
						$data['type'] = 6;
					}
				}


			}

			return $data;
	}*/

	public function findAnswer( $account, $msg, $botId )
	{

		$data = array();
		$data['message'] = "";
		$data['buttons'] = array();
		$data['gallery'] = array();
		$data['image'] = array();
		$data['alert'] = 0;
		$data['key'] = 0;
		$data['keyWord'] = "";
		$data['webhook'] = "";
		$data['cycle'] = 0;
		$typeA = 0;
		$key = 0;

			
			$keyWord = "";
			$botsKey = 0;

			$keys = $this->getKeys($account, $botId);

			if (count($keys) > 0) {

				$mensaje = strtolower($msg);
				$mensaje = urldecode($mensaje);
				$mensaje = $this->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'];
					$exp[$value['id']]['alert'] = $value['mail_alert'];
					$exp[$value['id']]['cycle'] = $value['bot_cycle'];
					$exp[$value['id']]['webhook'] = $value['webhook'];
					$chk[$value['id']] = strtolower($value['key']);
				}

				$found = FALSE;
				$count = 0;

				foreach ($chk as $value) {
					$value2 = explode(",", $value);
					foreach ($value2 as $value3) {
						if (strpos($mensaje, $this->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;

						$data['keyWord'] = $keyWord;

						$typeA = $exp[$key]['key'];
						$data['message'] = base64_decode($exp[$key]['mensaje']);
						$data['type'] = 1;
						$data['key'] = $key;
						$data['alert'] = $exp[$key]['alert'];
						$data['cycle'] = $exp[$key]['cycle'];
						$data['webhook'] = $exp[$key]['webhook'];

					if ($exp[$key]['key'] == 2) {
						$buttons = $this->getBotones($key);
						foreach ($buttons as $btn) {
							$data['buttons'][] = $btn['button'];
						};
						$data['type'] = 2;
					} else if ($exp[$key]['key'] == 3) {
						$image = $this->getImage($key);
						foreach ($image as $img) {
							$data['image'][] = "https://fogatabots.com" . $img['key_url'];
						};
						$data['type'] = 3;
					} else if ($exp[$key]['key'] == 4) {
						$buttons = $this->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->getCombos($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'title' => $combo['title'],
								'subtitle' => $combo['subtitle'],
								'image_url' => "https://fogatabots.com" . $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->getCombots($key);
						$combs = array();
						foreach ($combos as $combo) {
							$combs[] = array(
								'image_url' => "https://fogatabots.com" . $combo['key_image'],
								'button' => $combo['button'],
								'bots_keys_id' => $combo['id'],
							);
						};
						$data['gallery'] = $combs;
						$data['type'] = 6;
					}
				}


			}

			return $data;
	}

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

	public function getKey($id, $account) {
		$this->db->select('key,bot_cycle,id');
		$this->db->from('bots_keys');
		$this->db->where('id', $id);
		$this->db->where('account_id', $account);
		return $this->db->get()->result_array();
	}

	public function getKeys($id, $botId) {

		if(!empty($botId)){
			$this->db->select('*');
			$this->db->from('bots_keys');
			$this->db->where('account_id', $id);
			$this->db->where('bot_id', $botId);
			return $this->db->get()->result_array();
		} else return array();

	}

	public function getUser($phone_client, $phone_bot, $account_id, $name, $avatar) {

		$this->db->select('id,active,deleted,bot_cycle');
		$this->db->from('bots_whatsapp_user');
		$this->db->where('phone_client', $phone_bot);
		$this->db->where('phone', $phone_client);
		$this->db->where('account_id', $account_id);
		$this->db->limit(1);
		$test_usr = $this->db->get()->result_array();

		if(isset($test_usr[0]['id'])) {

			$return = array('error' => 0, 'data' => $test_usr[0]);
			return $return;

		} else {



	
				$avatarUrl = 'https://fogatabot.com/user-profile/47/Admin.png';
			

			if(empty($name)) $name = $phone_client;

			$data3 = array(
				'phone' => $phone_client,
				'account_phone' => $phone_bot,
				'phone_client' => $phone_bot,
				'account_id' => $account_id,
				'checkx' => 0,
				'active' => 1,
				'name' => $name,
				'timex' => date('Y-m-d H:i:s'),
				'last_active' => date('Y-m-d H:i:s'),
				'bot_cycle' => 0,
			);
			$test = $this->db->insert('bots_whatsapp_user', $data3);

			if(!$test) error_log("error create user ". $phone_client . " ".$name);

			$insert_id = $this->db->insert_id();
			$return = array('error' => 1, 'data' => array('id' => $insert_id, 'bot_cycle'=> 0, 'active' => 1));
			return $return;
		};
	}

	public function getAccount($phone) {

		$this->db->select('id,user_id,response,key,image,notfound,active,ticket_answer,group,webhook,token,bot_id,ai,webhookai,instructions');
		$this->db->from('whatsapp_accounts');
		$this->db->where('phone', $phone);
		$this->db->limit(1);
		$test_usr = $this->db->get()->result_array();

		if(isset($test_usr[0]['id'])) {

			return $test_usr[0];

		} else return false;
	}

	public function putMessage($user,$type,$msg,$key,$account_id,$agent,$uid) {

		$return = "";
		if(!empty($user) && !empty($msg)) {
			$data = array(
				'user' => $user,
				'time' => date('Y-m-d H:i:s'),
				'type' => $type,
				'mensaje' => base64_encode($msg),
				'bots_key_id' => $key,
				'account_id' => $account_id,
				'agent' => $agent,
				'uid' => $uid,
			);
			$this->db->insert('bots_whatsapp', $data);
			$return = $this->db->insert_id();

			$whatsClient = array(
				'last_active' => date('Y-m-d H:i:s'),
				'checkx' => 0,
			);
			$this->db->where('id', $user);
			$return2 = $this->db->update('bots_whatsapp_user', $whatsClient);

		}
		return $return;
	}

	public function testMsg($uid) {
		$status = TRUE;		
		$this->db->select('id');
		$this->db->from('bots_whatsapp');
		$this->db->where('uid', $uid);

		$test = $this->db->get()->result_array();

		if (isset($test[0]['id'])) {
			$status = FALSE;
		}
		return $status;
	}

	public function getAdmin($id) {

		$this->db->select('alerts,status');
		$this->db->from('user');
		$this->db-> where('id', $id);
		return $this->db->get()->result_array();
	}

	public function getBotones($id) {

		$this->db->select('*');
		$this->db->from('bots_keys_buttons');
		$this->db-> where('bots_keys_id', $id);
		$this->db->order_by('id', 'asc');
		return $this->db->get()->result_array();
	}

	public function getBotonesEnc($id) {

		$this->db->select('*');
		$this->db->from('bots_encuestas_buttons');
		$this->db-> where('bots_keys_id', $id);
		$this->db->order_by('id', 'asc');
		return $this->db->get()->result_array();
	}

	public function getEncuestas($id) {

		$this->db->select('*');
		$this->db->from('bots_keys_encuestas');
		$this->db-> where('bots_keys_id', $id);
		return $this->db->get()->result_array();
	}

	public function getImage($id) {

		$this->db->select('*');
		$this->db->from('bots_keys_image');
		$this->db->where('bots_keys_id', $id);
		return $this->db->get()->result_array();
	}

	public function getCombos($id) {

		$this->db->select('*');
		$this->db->from('bots_gallery');
		$this->db->where('bots_keys_id', $id);
		return $this->db->get()->result_array();
	}
	
	public function getCombots($id) {

		$this->db->select('*');
		$this->db->from('bots_keys_buttons_img');
		$this->db->where('bots_keys_id', $id);
		return $this->db->get()->result_array();
	}
	
	public function testTicket($cliente, $channel ) {
					
				$this->db->from('contact_tickets');
				$this->db->where('cliente', $cliente);
				$this->db->where('canal', $channel);
				$this->db->where('status', 0);

				$test = $this->db->get()->result_array();
				$status = 0;
				if (isset($test[0]['id'])) {
					$status = 1;
				}
				return  $status;
		
	}
	
	public function putTicket($cliente, $channel, $account_id, $msg, $key, $asunto, $chatId, $group) {
					
				$this->db->from('contact_tickets');
				$this->db->where('cliente', $cliente);
				$this->db->where('canal', $channel);
				$this->db->where('status', 0);

				$test = $this->db->get()->result_array();

				if(!empty($group)) $agente = $this->db->query('SELECT user.id AS agente, (SELECT count(*) FROM contact_tickets WHERE contact_tickets.agente = user.id AND contact_tickets.status = 0) AS "cantidad" FROM user LEFT JOIN contact_tickets ON user.id = contact_tickets.agente WHERE user.alerts = 1 AND user.account_id = '.$account_id.' AND FIND_IN_SET(\''.$group.'\', user.groups) > 0 GROUP BY user.id HAVING cantidad < 20 ORDER BY cantidad, user.id ASC'); 
				else $agente = $this->db->query('SELECT user.id AS agente, (SELECT count(*) FROM contact_tickets WHERE contact_tickets.agente = user.id AND contact_tickets.status = 0) AS "cantidad" FROM user LEFT JOIN contact_tickets ON user.id = contact_tickets.agente WHERE user.alerts = 1 AND user.account_id = '.$account_id.' GROUP BY user.id HAVING cantidad < 20 ORDER BY cantidad, user.id ASC'); 
				
				$agente->result_array();

				$status = 0;
				$return = FALSE;

				if (isset($agente->result_array[0]['agente'])) {

					$agente = $agente->result_array[0]['agente'];

					if( empty($test)){

						$whatsClient = array(
							'active' => 0,
							'agent' => $agente,
						);
						$this->db->where('id', $cliente);
						$this->db->update('bots_whatsapp_user', $whatsClient);
						
						$status = 1;
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => 1,
							'canal' => $channel,
							'proyecto' => 0,
							'prioridad' => 2,
							'etiquetas' => $key,
							'asunto' => $asunto,
							'descripcion' => $msg,
							'chat_id' => $chatId,
							'fecha_creacion' => date("Y-m-d H:i:s", (time())),
							'fecha_final' => date("Y-m-d H:i:s", (time() + (1*60*60))),
							'creado_por' => $account_id,
							'status' => 0,
							'nivel' => "",
							'grupo' => $group,
							'view' =>  0,
							'agente' => $agente,
						);

						$test5 = $this->db->insert('contact_tickets', $data2);
						$return = $this->db->insert_id();

						$data3 = array(
							'ticket_id' => $return,
							'agente' => $agente,
							'type' => 0,
							'time' => date("Y-m-d H:i:s", (time())),
						);
						$this->db->insert('contact_auditoria', $data3);

						$dataAlert = array(
							'account_id' => $agente,
							'type' => 20,
							'active' => 1,
							'user_id' => $return,
							'fecha' => date('Y-m-d H:i:s'),
						);
						$this->db->insert('bots_alerts', $dataAlert);

					}
				} else if( empty($test) ){
					$status = 2;
					$data2 = array(
						'cliente' => $cliente,
						'copia' => 1,
						'categoria' => 1,
						'canal' => $channel,
						'proyecto' => 0,
						'prioridad' => 2,
						'etiquetas' => $key,
						'asunto' => $asunto,
						'descripcion' => $msg,
						'chat_id' => $chatId,
						'fecha_creacion' => date("Y-m-d H:i:s", (time())),
						'fecha_final' => date("Y-m-d H:i:s", (time() + (1*60*60))),
						'creado_por' => $account_id,
						'status' => 0,
						'nivel' => "",
						'grupo' => $group,
						'view' =>  0,
						'agente' => 0,
					);

					$test = $this->db->insert('contact_tickets', $data2);
					$return = $this->db->insert_id();

					$whatsClient = array(
						'active' => 0,
						'agent' => 0,
					);
					$this->db->where('id', $cliente);
					$this->db->update('bots_whatsapp_user', $whatsClient);

					$data3 = array(
						'ticket_id' => $return,
						'agente' => "",
						'type' => 0,
						'time' => date("Y-m-d H:i:s", (time())),
					);
					$this->db->insert('contact_auditoria', $data3);

			}

				return  $return;
		
		
	}
	
	public function putTicketAgent($cliente, $channel, $account_id, $msg, $key, $asunto, $chatId, $group) {
	
				$this->db->from('contact_tickets');
				$this->db->where('cliente', $cliente);
				$this->db->where('canal', $channel);
				$this->db->where('status', 0);

				$test = $this->db->get()->result_array();

				if(!empty($group)) $agente = $this->db->query('SELECT user.id AS agente, (SELECT count(*) FROM contact_tickets WHERE contact_tickets.agente = user.id AND contact_tickets.status = 0) AS "cantidad" FROM user LEFT JOIN contact_tickets ON user.id = contact_tickets.agente WHERE user.alerts = 1 AND user.account_id = '.$account_id.' AND FIND_IN_SET(\''.$group.'\', user.groups) > 0 GROUP BY user.id HAVING cantidad < 20 ORDER BY cantidad, user.id ASC'); 
				else $agente = $this->db->query('SELECT user.id AS agente, (SELECT count(*) FROM contact_tickets WHERE contact_tickets.agente = user.id AND contact_tickets.status = 0) AS "cantidad" FROM user LEFT JOIN contact_tickets ON user.id = contact_tickets.agente WHERE user.alerts = 1 AND user.account_id = '.$account_id.' GROUP BY user.id HAVING cantidad < 20 ORDER BY cantidad, user.id ASC'); 
				
				$agente->result_array();

				$status = 0;
				$return = FALSE;

				if (isset($agente->result_array[0]['agente'])) {

					$agente = $agente->result_array[0]['agente'];

					if( empty($test) ){

						$this->db->from('contact_tickets');
						$this->db->where('cliente', $cliente);
						$this->db->where('canal', $channel);
						$this->db->order_by('id', 'desc');
						$this->db->limit(1);
						$agentGet = $this->db->get()->result_array();

						if(isset($agentGet[0]['agente'])) {
							$agente = $agentGet[0]['agente'];
						}

						$whatsClient = array(
							'active' => 0,
							'agent' => $agente,
						);
						$this->db->where('id', $cliente);
						$this->db->update('bots_whatsapp_user', $whatsClient);
						
						$status = 1;
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => 1,
							'canal' => $channel,
							'proyecto' => 0,
							'prioridad' => 2,
							'etiquetas' => $key,
							'asunto' => $asunto,
							'descripcion' => $msg,
							'chat_id' => $chatId,
							'fecha_creacion' => date("Y-m-d H:i:s", (time())),
							'fecha_final' => date("Y-m-d H:i:s", (time() + (1*60*60))),
							'creado_por' => $account_id,
							'status' => 0,
							'nivel' => "",
							'grupo' => $group,
							'view' =>  0,
							'agente' => $agente,
						);

						$test5 = $this->db->insert('contact_tickets', $data2);
						$return = $this->db->insert_id();

						$data3 = array(
							'ticket_id' => $return,
							'agente' => $agente,
							'type' => 0,
							'time' => date("Y-m-d H:i:s", (time())),
						);
						$this->db->insert('contact_auditoria', $data3);

						$dataAlert = array(
							'account_id' => $agente,
							'type' => 20,
							'active' => 1,
							'user_id' => $return,
							'fecha' => date('Y-m-d H:i:s'),
						);
						$this->db->insert('bots_alerts', $dataAlert);

					}
				} else if( empty($test) ){


					$this->db->from('contact_tickets');
					$this->db->where('cliente', $cliente);
					$this->db->where('canal', $channel);
					$this->db->order_by('id', 'desc');
					$this->db->limit(1);
					$agentGet = $this->db->get()->result_array();
					
					if(isset($agentGet[0]['agente'])) {
						$agente = $agentGet[0]['agente'];

					}
					else $agente = 0;



					$status = 2;
					$data2 = array(
						'cliente' => $cliente,
						'copia' => 1,
						'categoria' => 1,
						'canal' => $channel,
						'proyecto' => 0,
						'prioridad' => 2,
						'etiquetas' => $key,
						'asunto' => $asunto,
						'descripcion' => $msg,
						'chat_id' => $chatId,
						'fecha_creacion' => date("Y-m-d H:i:s", (time())),
						'fecha_final' => date("Y-m-d H:i:s", (time() + (1*60*60))),
						'creado_por' => $account_id,
						'status' => 0,
						'nivel' => "",
						'grupo' => $group,
						'view' =>  0,
						'agente' => $agente,
					);

					$test = $this->db->insert('contact_tickets', $data2);
					$return = $this->db->insert_id();

					$whatsClient = array(
						'active' => 0,
						'agent' => 0,
					);
					$this->db->where('id', $cliente);
					$this->db->update('bots_whatsapp_user', $whatsClient);

					$data3 = array(
						'ticket_id' => $return,
						'agente' => "",
						'type' => 0,
						'time' => date("Y-m-d H:i:s", (time())),
					);
					$this->db->insert('contact_auditoria', $data3);

			}

				return  $return;
		
		
	}

	public function sendWebhook($webhook, $post)
	{
	  $result = FALSE;
	  if(!empty($webhook) ) {
		$opts = array('http' =>
			array(
				'method'  => 'POST',
				'header'  => 'Content-Type: application/json',
				'content' => $post
			)
		);
		$context  = stream_context_create($opts);
		$result = file_get_contents($webhook, false, $context);
	  }
	  return $result;
	}

}



		/*$data = '{
			"product_id":"f6757a0e-99f2-4749-a69a-fe5e1ef2c0b3",
			"phone_id":16734,
			"message":
			{
				"type":"text",
				"text":"co\xc3\xb1o q beyo",
				"id":"false_50760816607@c.us_3EB01DB330D6BB6953D8",
				"_serialized":"false_50760816607@c.us_3EB01DB330D6BB6953D8",
				"fromMe":false
			},
				"user":
				{
					"id":"50760816607@c.us",
					"name":"Hector Panama",
					"phone":"50760816607",
					"image":"https://pps.whatsapp.net/v/t61.24694-24/161210654_851896828850980_1176648097975677754_n.jpg?ccb=11-4&oh=c0a9aa30c94f852db582f08abee88b8e&oe=61673B4D"
				},
					"conversation":"50760816607@c.us",
					"conversation_name":"Hector Panama",
					"receiver":"50760657458",
					"timestamp":1633948431,
					"type":"message",
					"reply":"https://api.maytapi.com/api/f6757a0e-99f2-4749-a69a-fe5e1ef2c0b3/16734/sendMessage",
					"productId":"f6757a0e-99f2-4749-a69a-fe5e1ef2c0b3",
					"phoneId":16734
		}';*/