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


class Md_chat extends CI_Model {

	public function getChats($user, $to, $type, $liveMsgID)
    {
		if(empty($liveMsgID)) {
		  
			$otherdb = $this->load->database('fogata', TRUE);
			$this->db->select('chatbot_web.id, chatbot_web.user, chatbot_web.type, chatbot_web.type, chatbot_web.chatbotId, chatbot_web.isfile, chatbot_web.isbutton, chatbot_web_user.image, FROM_BASE64(chatbot_web.message) AS message, DATE_FORMAT(FROM_UNIXTIME(chatbot_web.time), "%Y-%m-%d %H:%i:%s ") AS "time" ');
			$this->db->from('chatbot_web');
			$this->db->join('chatbot_web_user', 'chatbot_web.user = chatbot_web_user.id');

			$this->db->group_start(); // Open bracket

			$this->db->where('type', $type);
			$this->db->where('user', $user);
			$this->db->where('to', $to);

			$this->db->group_end(); // Close bracket
			$this->db->or_group_start(); // Open bracket

			$this->db->where('type', $type);
			$this->db->where('user', $to);
			$this->db->where('to', $user);

			$this->db->group_end(); // Close bracket

			$this->db->order_by("time", "asc");
	
		  	return $this->db->get()->result_array();

		} else {
			$otherdb = $this->load->database('fogata', TRUE);
			$this->db->select('chatbot_web.id, chatbot_web.user, chatbot_web.type, chatbot_web.type, chatbot_web.chatbotId, chatbot_web.isfile, chatbot_web.isbutton, chatbot_web_user.image, FROM_BASE64(chatbot_web.message) AS message, DATE_FORMAT(FROM_UNIXTIME(chatbot_web.time), "%Y-%m-%d %H:%i:%s ") AS "time" ');
			$this->db->from('chatbot_web');
			$this->db->join('chatbot_web_user', 'chatbot_web.user = chatbot_web_user.id');

			$this->db->group_start(); // Open bracket

			$this->db->where('type', $type);
			$this->db->where('user', $user);
			$this->db->where('to', $to);
			$this->db->where('id >', $liveMsgID);

			$this->db->group_end(); // Close bracket
			$this->db->or_group_start(); // Open bracket

			$this->db->where('type', $type);
			$this->db->where('user', $to);
			$this->db->where('to', $user);
			$this->db->where('id >', $liveMsgID);

			$this->db->group_end(); // Close bracket

			$this->db->order_by("time", "asc");
	
		  	return $this->db->get()->result_array();

		}


    }

	public function getChatsGroup($user, $to, $type, $liveMsgID)
    {
		if(empty($liveMsgID)) {

			$otherdb = $this->load->database('fogata', TRUE);
			$this->db->select('*, chatbot_web.id AS id, FROM_BASE64(message) message, DATE_FORMAT(FROM_UNIXTIME(time), "%Y-%m-%d %H:%i:%s ") AS "time" ');
			$this->db->from('chatbot_web');
			$this->db->join('support_optimus_db.chatbot_web_users', 'chatbot_web.chatbotId = chatbot_web_users.id');
			$this->db->where('type', $type);
			$this->db->where('to', $to);
			$this->db->order_by("time", "asc");
			return $this->db->get()->result_array();
		
		} else {

			$otherdb = $this->load->database('fogata', TRUE);
			$this->db->select('*, chatbot_web.id AS id, FROM_BASE64(message) message, DATE_FORMAT(FROM_UNIXTIME(time), "%Y-%m-%d %H:%i:%s ") AS "time" ');
			$this->db->from('chatbot_web');
			$this->db->join('support_optimus_db.chatbot_web_users', 'chatbot_web.chatbotId = chatbot_web_users.id');
			$this->db->where('type', $type);
			$this->db->where('to', $to);
			$this->db->where('chatbot_web.id >', $liveMsgID);
			$this->db->order_by("time", "asc");
			return $this->db->get()->result_array();

		}
    }

	public function getAll($user)
    {
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$otherdb = $this->load->database('fogata', TRUE);
			$otherdb->select('chatbot_web_groups.id, chatbot_web_groups.name, chatbot_web_groups.image, 7 AS type');
			$otherdb->from('chatbot_web_groups_users_groups');
			$otherdb->join('chatbot_web_groups', 'chatbot_web_groups_users_groups.chatbot_web_groups_id = chatbot_web_groups.id');
			$otherdb->where('chatbot_web_groups_users_groups.chatbot_web_users_id', $user);
			$array1 = $otherdb->get()->result_array();

			$otherdb = $this->load->database('fogata', TRUE);
			$otherdb->select('chatbot_web_groups_id');
			$otherdb->from('chatbot_web_groups_users_groups');
			$otherdb->where('chatbot_web_users_id', $user);
			$search = $otherdb->get()->result();

			$ids = array();
			foreach ($search as $r)
			$ids[] = $r->chatbot_web_groups_id;

			if(!empty($ids)) {
				$otherdb = $this->load->database('fogata', TRUE);
				$otherdb->select('chatbot_web_users.id, chatbot_web_users.name, chatbot_web_users.image, 8 AS type');
				$otherdb->from('chatbot_web_groups_users_groups');
				$otherdb->join('chatbot_web_users', 'chatbot_web_groups_users_groups.chatbot_web_users_id = chatbot_web_users.id');
				$otherdb->where_in('chatbot_web_groups_users_groups.chatbot_web_groups_id', $ids);
				$otherdb->group_by("chatbot_web_users.id");
				$array2 = $otherdb->get()->result_array();
			} else {
				$array2 = array();
			}

			$return = array_merge($array1, $array2);
		}
		return $return;
		
    }

	public function getHilos($user)
    {


		$this->db->select('chatbot_web.type, chatbot_web.to, chatbot_web_user.name AS name, chatbot_web_user.image AS image');
		$this->db->from('chatbot_web');
		$this->db->join('chatbot_web_user', 'chatbot_web.to = chatbot_web_user.id');
	//	$this->db->join('support_optimus_db.chatbot_web_groups', 'chatbot_web.to = chatbot_web_groups.id');
		$this->db->where('chatbot_web.chatbotId', $user);
		$this->db->where('chatbot_web.type', 8);
		$this->db->group_by(array("chatbot_web.to", "chatbot_web.type"));
		//$this->db->order_by();
		$array2 = $this->db->get()->result_array();
		//(SELECT count(*) FROM chatbot_web WHERE leido=0 AND chatbot_web.chatbotId = '.$user.') AS unread
		$x = 0;
		if($array2) {
			foreach ($array2 as $value) {
				$this->db->select('count(*) AS count, (select FROM_BASE64(message) FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS message, 
				(select id FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS id, (select isfile FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS isfile
				, (select `time` FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS `time`');
				$this->db->from('chatbot_web');
				$this->db->where('chatbotId', $value['to']);
				$this->db->where('to',$user);
				$this->db->where('type',8);
				$this->db->where('leido',0);
				
				$count = $this->db->get()->result_array();

				if(!empty($count )) {
					$array2[$x]['unread'] = $count[0]['count'];
					$array2[$x]['lastMsg'] = $count[0]['message'];
					$array2[$x]['lastMsgId'] = $count[0]['id'];
					$array2[$x]['isfile'] = $count[0]['isfile'];
					$array2[$x]['lastMsgTime'] = $count[0]['time'];
					$array2[$x]['isBot'] = 0;
				} else {
					$array2[$x]['unread'] = 0;
					$array2[$x]['lastMsg'] = "";
					$array2[$x]['lastMsgId'] = 0;
					$array2[$x]['isfile'] = 0;
					$array2[$x]['lastMsgTime'] = 0;
					$array2[$x]['isBot'] = 0;
				}
				$x++;
			}
		}


		$this->db->select('chatbot_web.type, chatbot_web.chatbotId AS to, chatbot_web_user.name AS name, chatbot_web_user.image AS image');
		$this->db->from('chatbot_web');
		$this->db->join('chatbot_web_user', 'chatbot_web.chatbotId = chatbot_web_user.id');
	//	$this->db->join('support_optimus_db.chatbot_web_groups', 'chatbot_web.to = chatbot_web_groups.id');
		$this->db->where('chatbot_web.to', $user);
		$this->db->where('chatbot_web.type', 8);
		$this->db->group_by(array("chatbot_web.chatbotId", "chatbot_web.type"));
		//$this->db->order_by();
		$array3 = $this->db->get()->result_array();
		//(SELECT count(*) FROM chatbot_web WHERE leido=0 AND chatbot_web.chatbotId = '.$user.') AS unread
		$x = 0;
		if($array3) {
			foreach ($array3 as $key => $value) {

				//$testUser = array_search($value['to'], $array2); // $clave = 2;
				$testUser = array_search($value['to'], array_column($array2, 'to'));

				if($testUser === false) {
					$this->db->select('count(*) AS count, (select FROM_BASE64(message) FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS message, 
					(select id FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS id, (select isfile FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS isfile
					, (select `time` FROM chatbot_web WHERE chatbotId='.$value['to'].' AND `to` = '.$user.' AND type = 8 ORDER BY id DESC LIMIT 1) AS `time`');
					$this->db->from('chatbot_web');
					$this->db->where('chatbotId', $value['to']);
					$this->db->where('to',$user);
					$this->db->where('type',8);
					$this->db->where('leido',0);
					
					$count = $this->db->get()->result_array();

					if(!empty($count )) {
						$array3[$x]['unread'] = $count[0]['count'];
						$array3[$x]['lastMsg'] = $count[0]['message'];
						$array3[$x]['lastMsgId'] = $count[0]['id'];
						$array3[$x]['isfile'] = $count[0]['isfile'];
						$array3[$x]['lastMsgTime'] = $count[0]['time'];
						$array3[$x]['isBot'] = 0;
					} else {
						$array3[$x]['unread'] = 0;
						$array3[$x]['lastMsg'] = "";
						$array3[$x]['lastMsgId'] = 0;
						$array3[$x]['isfile'] = 0;
						$array3[$x]['lastMsgTime'] = 0;
						$array3[$x]['isBot'] = 0;
					}
					$x++;
				} else {
					unset($array3[$key]);
					$x++;
				}

			}
		}

		$resultado = array_merge($array3, $array2);

		return $resultado;
		
    }

	public function setReminder($cleanPost)
	{
		if(isset($cleanPost['title'])) $title = $cleanPost['title'];
		else $title = FALSE;
		if(isset($cleanPost['time'])) $time = $cleanPost['time'];
		else $time = FALSE;
		if(isset($cleanPost['days'])) $days = $cleanPost['days'];
		else $days = FALSE;
		if(isset($cleanPost['chatbotId'])) $chatbotId = $cleanPost['chatbotId'];
		else $chatbotId = FALSE;
		if(isset($cleanPost['toUser'])) $toUser = $cleanPost['toUser'];
		else $toUser = FALSE;
		if(isset($cleanPost['type'])) $type = $cleanPost['type'];
		else $type = FALSE;
		if(isset($cleanPost['msg'])) $msg = $cleanPost['msg'];
		else $msg = FALSE;

		$otherdb = $this->load->database('fogata', TRUE);
		$data2 = array(
			'title' => $title,
			'time' => $time,
			'days' => $days,
			'chatbotId' => $chatbotId,
			'toUser' => $toUser,
			'type' => $type,
			'msg' => $msg,
		);

		$otherdb->insert('set_reminder', $data2);
		$cliente = $otherdb->insert_id();
		
		return $cliente;
	}

	public function setLater($cleanPost)
	{
		if(isset($cleanPost['title'])) $title = $cleanPost['title'];
		else $title = FALSE;
		if(isset($cleanPost['time'])) $time = $cleanPost['time'];
		else $time = FALSE;
		if(isset($cleanPost['chatbotId'])) $chatbotId = $cleanPost['chatbotId'];
		else $chatbotId = FALSE;
		if(isset($cleanPost['toUser'])) $toUser = $cleanPost['toUser'];
		else $toUser = FALSE;
		if(isset($cleanPost['type'])) $type = $cleanPost['type'];
		else $type = FALSE;
		if(isset($cleanPost['msg'])) $msg = $cleanPost['msg'];
		else $msg = FALSE;

		$otherdb = $this->load->database('fogata', TRUE);
		$data2 = array(
			'title' => $title,
			'time' => $time,
			'chatbotId' => $chatbotId,
			'toUser' => $toUser,
			'type' => $type,
			'msg' => $msg,
		);

		$otherdb->insert('set_later', $data2);
		$cliente = $otherdb->insert_id();
		
		return $cliente;
	}

	public function deleteUser($cleanPost)
	{

		if(isset($cleanPost['user'])) $ip = $cleanPost['user'];
		else $ip = FALSE;

		$otherdb = $this->load->database('fogata', TRUE);
		$this->db->from('chatbot_web_user');
		$this->db->where('ip', $ip);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$user = array(
				'FCMToken' => 0,
				'ip' => 0,
			);
			$this->db->where('id', $test_usr[0]['id']);
			$return = $this->db->update('chatbot_web_user', $user);
		}
		return $test_usr[0]['id'];
	}

	public function putUser($cleanPost)
	{

		if(isset($cleanPost['name'])) $name = $cleanPost['name'];
		else $name = FALSE;
		if(isset($cleanPost['email'])) $email = $cleanPost['email'];
		else $email = FALSE;
		if(isset($cleanPost['phone'])) $phone = $cleanPost['phone'];
		else $phone = FALSE;
		if(isset($cleanPost['ip'])) $ip = $cleanPost['ip'];
		else $ip = FALSE;
		if(isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = FALSE;
		if(isset($cleanPost['device'])) $device = $cleanPost['device'];
		else $device = FALSE;

		$otherdb = $this->load->database('fogata', TRUE);
		$this->db->from('chatbot_web_user');
		$this->db->where('ip', $ip);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (empty($test_usr)) {

			$user = array(
				'bot_cycle' => 0,
				'check' => 0,
				'live' => 0,
				'active' => 0,
				'bot' => 0,
				'name' => $name,
				'email' => $email,
				'phone' => $phone,
				'ip' => $ip,
				'time' => date("Y-m-d H:i:s"),
				'last_active' => date("Y-m-d H:i:s"),
				'FCMToken' => $token,
				'device' => $device,
				'account_id' => 47,
				'image' => "",
			);

			$return = $this->db->insert('chatbot_web_user', $user);
			$new_id = $this->db->insert_id();
			$user['id'] = $new_id;
			$return = $user;

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

	public function putAvatar($file, $user)
	{
			
		$this->db->from('chatbot_web_user');
		$this->db->where('id', $user);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$image = array(
				'image' => $file,
			);
			$this->db->where('id', $user);
			$return = $this->db->update('chatbot_web_user', $image);

		}
		return $return;
	}

	public function getLaters($user)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$otherdb = $this->load->database('fogata', TRUE);
			$otherdb->from('set_later');
			$otherdb->where('chatbotId', $user);
			$otherdb->where('active', 1);
			$return = $otherdb->get()->result_array();
		}
		return $return;
	}

	public function deleteReminders($user, $id)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {

			$update = array(
				'active' => 0,
			);
			$otherdb->where('id', $id);
			$return = $otherdb->update('set_reminder', $update);

		}
		return $return;
	}

	public function deleteLater($user, $id)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {

			$update = array(
				'active' => 0,
			);
			$otherdb->where('id', $id);
			$return = $otherdb->update('set_later', $update);

		}
		return $return;
	}

	public function getReminders($user)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$otherdb = $this->load->database('fogata', TRUE);
			$otherdb->from('set_reminder');
			$otherdb->where('chatbotId', $user);
			$otherdb->where('active', 1);
			$return = $otherdb->get()->result_array();
		}
		return $return;
	}

	public function getGroups($user)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$otherdb = $this->load->database('fogata', TRUE);
			$otherdb->select('chatbot_web_groups.id, chatbot_web_groups.name, chatbot_web_groups.image');
			$otherdb->from('chatbot_web_groups_users_groups');
			$otherdb->join('chatbot_web_groups', 'chatbot_web_groups_users_groups.chatbot_web_groups_id = chatbot_web_groups.id');
			$otherdb->where('chatbot_web_groups_users_groups.chatbot_web_users_id', $user);
			$return = $otherdb->get()->result_array();
		}
		return $return;
	}

	public function getUsername($user,$password,$android,$token)
	{
		$otherdb = $this->load->database('fogata', TRUE);
		$this->db->from('chatbot_web_user');
		$this->db->like('id', $user);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (isset($test_usr[0]['id'])) {
			$otherdb = $this->load->database('fogata', TRUE);
			$userClient = array(
				'ip' => $android,
				'FCMToken' => $token,
			);
			$this->db->where('id', $test_usr[0]['id']);
			$this->db->update('chatbot_web_user', $userClient);

			$return = $test_usr[0];
		}
		return $return;
	}

	public function putToken($cleanPost)
	{

		if(isset($cleanPost['AndroidID'])) $AndroidID = $cleanPost['AndroidID'];
		else $AndroidID = FALSE;
		if(isset($cleanPost['FCMToken'])) $FCMToken = $cleanPost['FCMToken'];
		else $FCMToken = FALSE;

		$otherdb = $this->load->database('fogata', TRUE);
		$this->db->from('chatbot_web_user');
		$this->db->like('ip', $AndroidID);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (isset($test_usr[0]['id'])) {
		
			$userClient = array(
				'FCMToken' => $FCMToken,
			);
			$this->db->where('id', $test_usr[0]['id']);
			$return = $this->db->update('chatbot_web_user', $userClient);

		}
		return $return;
	}

	public function getUser($user)
	{
		$this->db->from('chatbot_web_user');
		$this->db->where('id', $user);
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (isset($test_usr[0]['id'])) {
			$return = $test_usr[0];
		}
		return $return;
	}

	public function getUsers($user)
	{
		$this->db->from('chatbot_web_user');
		$this->db->where('`FCMToken` != "0"');
		$test_usr = $this->db->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$return = $test_usr;
		}
		return $return;
	}

	public function getKeys($cleanPost)
	{
		//log_message('error', json_encode($cleanPost)); 

		if(isset($cleanPost['msg'])) $word = $cleanPost['msg'];
		else $word = FALSE;
		if(isset($cleanPost['channel'])) $channel = $cleanPost['channel'];
		else $channel = FALSE;
		if(isset($cleanPost['nombre'])) $nombre = $cleanPost['nombre'];
		else $nombre = FALSE;
		if(isset($cleanPost['telefono'])) $telefono = $cleanPost['telefono'];
		else $telefono = FALSE;
		if(isset($cleanPost['correo'])) $correo = $cleanPost['correo'];
		else $correo = FALSE;
		if(isset($cleanPost['id'])) $user = $cleanPost['id'];
		else $user = FALSE;

		$status = 0;

		if($user) {
			
				$key=41;
			
				$otherdb = $this->load->database('fogata', TRUE);
				$otherdb->from('ticket_users');
				$otherdb->where('bot_user', $user);
				$otherdb->where('channel', $channel);
				$test_usr = $otherdb->get()->result_array();

				if (empty($nombre)) $nombre = $telefono;
				
				if (empty($test_usr)) {
					$data2 = array(
						'bot_user' => $user,
						'channel' => $channel,
						'nombre' => $nombre,
						'email' => "",
						'telefono' => $telefono,
						'created' => date("Y-m-d H:i:s", (time())),
						'avatar' => "https://soporte.fogatacrm.com/img/no-user.jpg",
						'created_by' => 1853,
						'cliente' => 4,
						'type' => 1,
					);

					$otherdb->insert('ticket_users', $data2);
					$cliente = $otherdb->insert_id();
				} else if (isset($test_usr[0]['id'])) {
					$cliente = $test_usr[0]['id'];
				}
				
				$otherdb = $this->load->database('fogata', TRUE);
				$otherdb->from('ticket_email');
				$otherdb->where('cliente', $cliente);
				$otherdb->where('canal', $channel);
				$otherdb->where('status != ', 3);
				$otherdb->where('status != ', 10);
				$otherdb->where('status != ', 4);
				$otherdb->where('status != ', 11);
				$otherdb->where('status != ', 12);
				$otherdb->where('status != ', 14);
				$test = $otherdb->get()->result_array();

				if($channel == 4) {
						$proyecto = 13;
						$grupo1 = 15;
						$whatsClient = array(
							'checkx' => 0,
						);
						$this->db->where('id', $user);
						$error = $this->db->update('bots_whatsapp_user', $whatsClient);
						//log_message('ERROR', $user.' - WS - '.$error);

				} else if($channel == 2) {
					if($correo == 385275178211751){ //meykos
						$proyecto = 14;
						$grupo1 = 14;
					} else if($correo == 140773966122401){ //cv
						$proyecto = 13;
						$grupo1 = 15;
					} else if($correo == 1456870381269830){ // del ahorro
						//$proyecto = 21;
						//$grupo1 = 21;
						$proyecto = 14;
						$grupo1 = 14;
					}  else {
						$proyecto = 13;
						$grupo1 = 15;
					} 
				} else {
					$proyecto = 13;
					$grupo1 = 15;
				}


				$agente = $otherdb->query('SELECT ss3nu_users.id AS agente, (SELECT count(*) FROM ticket_email WHERE ticket_email.status=2 AND ticket_email.agente = ss3nu_users.id) AS "cantidad" FROM ticket_email RIGHT JOIN ss3nu_users ON ss3nu_users.id = ticket_email.agente WHERE ss3nu_users.params = 1 AND ss3nu_users.grupo LIKE "%'.$grupo1.'%" GROUP BY ss3nu_users.id HAVING cantidad < 20 ORDER BY cantidad, ss3nu_users.id ASC'); 
		
				$agente->result_array();
				//log_message('error', json_encode($agente)); 
				if (isset($agente->result_array[0]['agente'])) {
					
					$agente = $agente->result_array[0]['agente'];
					if( !isset($test[0]['id'])){
						
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => 1,
							'canal' => $channel,
							'proyecto' => $proyecto,
							'prioridad' => 2,
							'etiquetas' => $key,
							'asunto' => 'Agente',
							'descripcion' => $word,
							'adjunto' => '',
							'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' => 1853,
							'status' => 2,
							'view' =>  0,
							'nivel' => "",
							'agente' => $agente,
						);
						$otherdb->insert('ticket_email', $data2);
						$return = $otherdb->insert_id();

						//log_message('error', json_encode($return)); 

						if(!empty($return)) $status = 1;

						$data3 = array(
							'ticket_id' => $return,
							'agente' => $agente,
							'descripcion' => 15,
							'time' => date("Y-m-d H:i:s", (time())),
						);
						$otherdb->insert('ticket_auditoria', $data3);

					}
				} else if( !isset($test[0]['id'])){
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => 1,
							'canal' => $channel,
							'proyecto' => $proyecto,
							'prioridad' => 2,
							'etiquetas' => $key,
							'asunto' => 'Agente',
							'descripcion' => $word,
							'adjunto' => '',
							'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' => 1853,
							'status' => 1,
							'view' =>  0,
							'nivel' => "",
						);
						$otherdb->insert('ticket_email', $data2);
						$return = $otherdb->insert_id();

						//log_message('error', json_encode($return)); 

						if(!empty($return)) $status = 2;

						$data3 = array(
							'ticket_id' => $return,
							'agente' => 1853,
							'descripcion' => 5,
							'time' => date("Y-m-d H:i:s", (time())),
						);
						$otherdb->insert('ticket_auditoria', $data3);
				}

				return  $status;


		} else {
			log_message('error', json_encode($cleanPost)); 
			return $status;
		} 

	}

}
