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

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

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

		return $data;

	}

	public function getMessages( $data )
	{
		/*{"object":"instagram",
			"entry":[
				{
					"time":1643641273876,
					"id":"17841449117225722",
					"messaging":[{
						"sender":{
							"id":"5066843503359886"},
							"recipient":{
								"id":"17841449117225722"},
								"timestamp":1643641272795,
								"message":{
									"mid":"aWdfZAG1faXRlbToxOklHTWVzc2FnZAUlEOjE3ODQxNDQ5MTE3MjI1NzIyOjM0MDI4MjM2Njg0MTcxMDMwMDk0OTEyODIxNTcyMTE0MTkyNTM2NDozMDMxOTgyOTkwODI0OTgzMTYwMTY5NTg5Mjg2MDU2NzU1MgZDZD",
									"text":"prueba 2"}}]}]}*/

	/*{"object":"instagram",
		"entry":[{
			"time":1645500950326,
			"id":"17841406249704999",
			"messaging":[{
				"sender":{
					"id":"4765193740230317"},
					"recipient":{"id":"17841406249704999"},
					"timestamp":1645500949755,
					"message":{
						"mid":"aWdfZAG1faXRlbToxOklHTWVzc2FnZAUlEOjE3ODQxNDA2MjQ5NzA0OTk5OjM0MDI4MjM2Njg0MTcxMDMwMDk0OTEyODM5Njg1NDM3NjM1Nzc1ODozMDM1NDEzNDg5MzE3ODYyNDczMjQ1NTc0NTM2MjA2NzQ1NgZDZD",
						"attachments":[{
							"type":"story_mention",
							"payload":{
								"url":"https:\/\/lookaside.fbsbx.com\/ig_messaging_cdn\/?asset_id=17914241111495558&signature=AbzkXqVQuoPaqy4qqE4EGxaiUnS5JKaLVSXr-nzvnIIP3HjWt_E3T62Phm1xBCPZvUWTfmHoIH-E3nM1Ls_1QnzHvvkQ0TGhdRtM2ONuvF-4wMF02Ea2p3BarLusePVgl3TPiKJQbjspd2UebWZ2cXJvfBI3IwnYCDvhcHHxMfXMWSyf"
							}}]}}]}]}*/
									

		$data = json_decode($data);

		if(isset($data->entry)) {

			$data = $data->entry[0];
			$user = 0;
			$type = FALSE;
			$key = 0;
			$account_id = 0;
			$agent = 0;
			$chatId = "";
			$key = 0;
			$image = "";
			$msg = "";
			$account = array();
			
			$name = $data->messaging[0]->sender->id;

			$avatar = "https://myjuicybots.juicyboxtech.com/img/new-logo-header-3.png";

			$timestamp = time();

			$ticket = FALSE;
			$botones = "";
			$typeFile = "";

			$userID = $data->messaging[0]->sender->id;
			$accountID = $data->messaging[0]->recipient->id;
			$from = $data->messaging[0]->sender->id;
			$type = 1;

			$userArray = "";
			if(isset($data->messaging[0]->message->text) && !empty($data->messaging[0]->message->text)) {
				$word = $data->messaging[0]->message->text;
			} else $word = "";
		
			if(isset($data->messaging[0]->message->attachments[0]->payload->url) && !empty($data->messaging[0]->message->attachments[0]->payload->url)) {
				$word = $data->messaging[0]->message->attachments[0]->payload->url;
				$type = 3;
			} 

			

			if(isset($data->id)) $uIdmsg =  $data->time.$data->id;
			else $uIdmsg = 0;
			
			$username = $data->messaging[0]->sender->id;
			$url = "";
			$message = "";
			$account = $this->getAccount($accountID);
			error_log(json_encode($account));
			if($account) {

				//$contactGroup = $account['group'];
				$token = $account['token'];
				$account_id = $account['user_id'];
				$botActive = $account['active'];
				$admin = $this->getAdmin($account_id);

				$userProfile = $this->getProfile($userID, $token);

				$userProfile = json_decode($userProfile);

				if(isset($userProfile->name)) {
					$name = $userProfile->name;
				}
				if(isset($userProfile->profile_pic)) {
					$avatar = $userProfile->profile_pic;
				}


				$botUser = $this->getUser($userID, $account['id'], $account_id, $name, $avatar, $username);
error_log(json_encode($botUser));
				if(isset($admin[0]['status'] ) && $admin[0]['status'] == 10) {
		
					if (isset($botUser['data']['id']) && $botUser['error'] == 0 && $botUser['data']['deleted'] == 0) { 

						$activeBot = $timestamp - strtotime($botUser['data']['last_active']);

						$uIdmsg2 = $botUser['data']['id'].$uIdmsg;

						$user = $botUser['data']['id'];

						$userBotActive = $botUser['data']['active'];

						if($activeBot >= 3600) {
							$this->activateBot( $user );
							$userBotActive = 1;
						}

						
						if(!empty($word) && $type != 12) $chatId = $this->putMessage($user,$type,$word,$key,$account_id,$agent,$uIdmsg2);
						if(!empty($url)) $chatId = $this->putMessage($user,$type,$url,$key,$account_id,$agent,$uIdmsg2);
		
						$botAnswer = $this->findAnswer( $account_id, $word );

						//if(isset($admin[0]['contact']) && $admin[0]['contact'] == 1 && $botAnswer['alert']) $ticket = $this->putTicket($user, 3, $account_id, $word, $key, $botAnswer['keyWord'], $chatId, $contactGroup);
						if($botAnswer['alert']) {
							$this->insertAlert($account_id, 5, 1, $user);
						}

						if($ticket && !empty($account['ticket_answer'])) {
							$this->putMessage($user,0,$account['ticket_answer'].$ticket,$key,$account_id,$agent,$uIdmsg);
							$this->sendMessage($account['ticket_answer'].$ticket, $url, $token, $from, $botones);
						}

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

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

								if($botActive == 1 && $userBotActive == 1 ) {
									$this->sendMessage($imgMessage, $image, $token, $from, $botones);
									$this->putMessage($user,4,$image,$key,$account_id,$agent,$uIdmsg.$uIdmsg.$value['bots_keys_id']."4");
									$this->putMessage($user,0,$imgMessage,$key,$account_id,$agent,$uIdmsg.$value['bots_keys_id']);
								}

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

							if($botActive == 1 && $userBotActive == 1 ) {
								$this->sendMessage(base64_decode($message), $image, $token, $from, $botones);
								$this->putMessage($user,0,base64_decode($message),$key,$account_id,$agent,$uIdmsg);
							}

							foreach ($galery as $key => $value) {
								$image = $value['image_url'];
								$imgMessage = $value['button'];

								if($botActive == 1 && $userBotActive == 1 ) {
									$this->sendMessage($imgMessage, $image, $token, $from, $botones);
									$this->putMessage($user,4,$image,$key,$account_id,$agent,$uIdmsg.$value['bots_keys_id']."4");
									$this->putMessage($user,0,$imgMessage,$key,$account_id,$agent,$uIdmsg.$value['bots_keys_id']);
								}

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

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

						} 
	
					} else if (isset($botUser['data']['id']) && $botUser['error'] == 1) { //New user response

						$uIdmsg2 = $botUser['data']['id'].$uIdmsg;
						$user = $botUser['data']['id'];
						if(!empty($word) && $type != 12) $chatId = $this->putMessage($user,$type,$word,$key,$account_id,$agent,$uIdmsg2);
						if(!empty($url)) $chatId = $this->putMessage($user,$type,$url,$key,$account_id,$agent,$uIdmsg2);

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

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

						}
					}
				}


			}

		}

		return $data;

	}
	
	public function sendMessage( $msg, $url, $token, $userID, $botones )
	{
		$response = "";
        if(!empty($msg)) {

          //$token = $account->token; // cebollines gt
          /*$curl = curl_init();
  
          curl_setopt_array($curl, array(
           CURLOPT_URL => "http://146.71.78.240:5000/",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_SSL_VERIFYPEER => false,
		  CURLOPT_SSL_VERIFYHOST => false,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => '{"identifier":"'.$token.'","username":"'.$userID.'","message":"'.base64_decode($msg).'","imageUrl":""}',
          CURLOPT_HTTPHEADER => array(
              "Content-Type: application/json"
          ),
          ));
		  
		  error_log('{"identifier":"'.$token.'","username":"'.$userID.'","message":"'.base64_decode($msg).'","imageUrl":""}');
          $response = curl_exec($curl);
		  error_log($response);
      
          curl_close($curl);*/
		  $msg = str_replace('"', "*", $msg);
		  $msg = str_replace("'","\'",$msg);

		  $curl = curl_init();

			curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://graph.facebook.com/v12.0/me/messages?access_token='.$token,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>'{"recipient":{"id":"'.$userID.'"},"message":{"text":"'.$msg.'"}}',
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json'
			),
			));

			$response = curl_exec($curl);
			error_log(json_encode($response));
			curl_close($curl);

		}

		if(!empty($botones)) { 
			$botones = str_replace('"', "*", $botones);
			$botones = str_replace("'","\'",$botones);

			$curl = curl_init();
  
			  curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://graph.facebook.com/v12.0/me/messages?access_token='.$token,
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_SSL_VERIFYPEER => false,
			  CURLOPT_SSL_VERIFYHOST => false,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>'{"recipient":{"id":"'.$userID.'"},"message":{"text":"'.$botones.'"}}',
			  CURLOPT_HTTPHEADER => array(
				  'Content-Type: application/json'
			  ),
			  ));
  
			  $response = curl_exec($curl);
			  error_log(json_encode($response));
			  curl_close($curl);
		}

		if(!empty($url)) { 
			$url = str_replace('"', "", $url);
			$url = str_replace("'","",$url);

			$curl = curl_init();
  
			  curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://graph.facebook.com/v12.0/me/messages?access_token='.$token,
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_SSL_VERIFYPEER => false,
			  CURLOPT_SSL_VERIFYHOST => false,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>'{"recipient":{"id":"'.$userID.'"},"message":{"attachment":{"type":"image", "payload":{"url":"'.$url.'"}}}}',
			  CURLOPT_HTTPHEADER => array(
				  'Content-Type: application/json'
			  ),
			  ));
  
			  $response = curl_exec($curl);
			  error_log(json_encode($response));
			  curl_close($curl);
		}
		return $response;
	}

	public function findAnswer( $account, $msg )
	{

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

			
			$keyWord = "";
			$botsKey = 0;

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

			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'];
					$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'] = $exp[$key]['mensaje'];
						$data['type'] = 1;
						$data['key'] = $key;
						$data['alert'] = $exp[$key]['alert'];

					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://myjuicybots.juicyboxtech.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://myjuicybots.juicyboxtech.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://myjuicybots.juicyboxtech.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 getKeys($id) {

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

	public function getProfile($id, $token) {

		$curl = curl_init();
		
		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://graph.facebook.com/v12.0/'.$id.'?fields=name,profile_pic,follower_count&access_token='.$token,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => '',
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => true,
		  CURLOPT_SSL_VERIFYPEER => false,
		  CURLOPT_SSL_VERIFYHOST => false,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => 'GET',
		));
		
		$response = curl_exec($curl);
		
		curl_close($curl);
		return $response;
		
	}

	public function getUser($user_id, $instagram_id, $account_id, $name, $avatar, $username) {
		$this->db->select('id,active,deleted,last_active');
		$this->db->from('bots_instagram_user');
		$this->db->where('instagram_id', $instagram_id);
		$this->db->where('pk', $user_id);
		$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 {

			$dir ="/var/www/html/juicy/backend/web/bot-img/".$account_id."/";
			if (!file_exists($dir)) {
				mkdir($dir, 0755);
			}

			$filename = "ig_".$user_id."_".time().".jpg";

			if($filename) {
				file_put_contents($dir.$filename, file_get_contents($avatar));
				$avatarUrl = 'https://myjuicybots.juicyboxtech.com/bot-img/'.$account_id.'/'.$filename;
			} else {
				$avatarUrl = 'https://myjuicybots.juicyboxtech.com/img/new-logo-header-3.png';
			}

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

			$data3 = array(
				'instagram_id' => $instagram_id,
				'pk' => $user_id,
				'account_id' => $account_id,
				'checkx' => 0,
				'name' => $name,
				'date_created' => date('Y-m-d H:i:s'),
				'last_active' => date('Y-m-d H:i:s'),
				'bot_cycle' => 0,
				'profile_pic_url' => $avatarUrl,
				'username' => $username,
				'active' => 1,
			);

			

			$test = $this->db->insert('bots_instagram_user', $data3);
			$insert_id = $this->db->insert_id();
			$return = array('error' => 1, 'data' => array('id' => $insert_id));
			return $return;
		};
	}

	public function getAccount($id) {

		$this->db->select('id,user_id,response,key,image,notfound,active,ticket_answer,group,token');
		$this->db->from('instagram_accounts');
		$this->db->where('instagram_account', $id);
		$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 insertAlert($account_id, $type, $active, $user_id) {

	/*	$whatsClient = array(
			'fecha' => date('Y-m-d H:i:s'),
			'account_id' => $account_id,
			'type' => $type,
			'active' => $active,
			'user_id' => $user_id,
		);
		$this->db->insert('bots_alerts', $whatsClient);

		return 1;*/
	}

	public function putMessage($user,$type,$msg,$key,$account_id,$agent,$uIdmsg) {
		$return = "";
		if(!empty($user)) {
			$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' => $uIdmsg,
			);

			$this->db->insert('bots_instagram', $data);
			$return = $this->db->insert_id();

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

		}
		return $return;
	}

	public function activateBot($user) {

			$whatsClient = array(
				'active' => 1,
			);
			$this->db->where('id', $user);
			$this->db->update('bots_instagram_user', $whatsClient);

	
	}

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

				$this->db->select('id,username,name,email,alerts');
				$this->db->from('user');
				$this->db->where('account_id', $account_id);
				$this->db->where('find_in_set("'.$group.'", groups)');
				$this->db->where('alerts', 1);
				
				$agente = $this->db->get()->result_array();

				$str = $this->db->last_query();

				$status = 0;

				$return = FALSE;

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

					if( empty($test)){

						$whatsClient = array(
							'active' => 0,
							'agent' => $agente,
						);
						$this->db->where('id', $cliente);
						$this->db->update('bots_instagram_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);

					}
				} 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_instagram_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;
		
		
	}

}


											/*$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',
						  ];*/