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


class Md_fogatachat extends CI_Model {

	public function getLogin($pin, $user, $userWeb, $channel)
	{
		$otherdb = $this->load->database('optimus', TRUE);
		$otherdb->from('colaboradores');
		$otherdb->where('codigo', $user);
		$otherdb->where('pin', $pin);
		$test_usr = $otherdb->get()->result_array();
		$return = false;
		if (empty($test_usr)) {
			$return = FALSE;
		} else if (isset($test_usr[0]['id'])) {
			$return = $test_usr[0];
			$data2 = array(
				'colaboradores_id' => $test_usr[0]['id'],
				'fecha' => date('Y-m-d H:i:s'),
				'usuario' => $userWeb,
				'channel' => $channel,
			);
			$return = $otherdb->insert('colaboradores_login', $data2);
		}
		return $return;
	}

	public function getChatuser($user)
	{
		$otherdb = $this->load->database('optimus', TRUE);
		$otherdb->select('*');
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $user);
		$otherdb->order_by("id", "desc");
		$otherdb->limit(1);
		$test_usr = $otherdb->get()->result_array();

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

	public function getBotuser($user)
	{
		$this->db->select('*');
		$this->db->from('chatbot_web_user');
		$this->db->where('chatbotId', $user);
		$this->db->order_by("id", "desc");
		$this->db->limit(1);
		$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[0];
		}
		return $return;
	}

	public function firebaseOptimusCall($titulo, $body, $fcm)
	{
		if(!empty($fcm)){
			$curl = curl_init();
		
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>'{
			"to":"'.$fcm.'",
			 "notification" : {
			  "sound": "ringtone",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high",
			  "channel_id": "ringtone",
			  "android_channel_id": "ringtone"
			 },
			 "data" : {
			  "sound": "ringtone",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high",
			  "channel_id": "ringtone",
			  "android_channel_id": "ringtone"
			 }
			}',
			  CURLOPT_HTTPHEADER => array(
				'Authorization: key=AAAAjPh4VtI:APA91bHf0VmkpMfoBXxV9C2gYWz7oMX9ypUsNqb7mzQ5gXtt5f_WjBrAoBdRyABInRS4e3rNPd1bWN_1mWLX01KnACmuDgY52wtSpapbMqFo-E0w8vplaA-NhhgSrvLDMNARnu2bDH8O',
				'Content-Type: application/json'
			  ),
			));
			
			$response = curl_exec($curl);
			
			curl_close($curl);
			
			return $response;
		} else {
			return false;
		}
	
	}

	public function firebaseOptimus($titulo, $body, $fcm)
	{
		if(!empty($fcm)){
			$curl = curl_init();
		
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>'{
			"to":"'.$fcm.'",
			 "notification" : {
			  "sound" : "default",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high"
			 },
			 "data" : {
			  "sound" : "default",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high"
			 }
			}',
			  CURLOPT_HTTPHEADER => array(
				'Authorization: key=AAAAjPh4VtI:APA91bHf0VmkpMfoBXxV9C2gYWz7oMX9ypUsNqb7mzQ5gXtt5f_WjBrAoBdRyABInRS4e3rNPd1bWN_1mWLX01KnACmuDgY52wtSpapbMqFo-E0w8vplaA-NhhgSrvLDMNARnu2bDH8O',
				'Content-Type: application/json'
			  ),
			));
			
			$response = curl_exec($curl);
			
			curl_close($curl);
			
			return $response;
		} else {
			return false;
		}
	
	}

	public function firebaseOptimusJson($json)
	{

		$json = json_encode($json);
		if(!empty($json)){
			$curl = curl_init();
		
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>$json,
			  CURLOPT_HTTPHEADER => array(
				'Authorization: key=AAAAjPh4VtI:APA91bHf0VmkpMfoBXxV9C2gYWz7oMX9ypUsNqb7mzQ5gXtt5f_WjBrAoBdRyABInRS4e3rNPd1bWN_1mWLX01KnACmuDgY52wtSpapbMqFo-E0w8vplaA-NhhgSrvLDMNARnu2bDH8O',
				'Content-Type: application/json'
			  ),
			));
			
			$response = curl_exec($curl);
			
			curl_close($curl);
			
			return $response;
		} else {
			return false;
		}
	
	}

	public function firebaseFogata($titulo, $body, $fcm)
	{
		if(!empty($fcm)){
			$curl = curl_init();
		
			curl_setopt_array($curl, array(
			  CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
			  CURLOPT_RETURNTRANSFER => true,
			  CURLOPT_ENCODING => '',
			  CURLOPT_MAXREDIRS => 10,
			  CURLOPT_TIMEOUT => 0,
			  CURLOPT_FOLLOWLOCATION => true,
			  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST => 'POST',
			  CURLOPT_POSTFIELDS =>'{
			"to":"'.$fcm.'",
			 "notification" : {
			  "sound" : "default",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high"
			 },
			 "data" : {
			  "sound" : "default",
			  "body" :  "'.$body.'",
			  "title" : "'.$titulo.'",
			  "content_available" : true,
			  "priority" : "high"
			 }
			}',
			  CURLOPT_HTTPHEADER => array(
				'Authorization: key=AAAAUJx0Yl0:APA91bHnVvk-JN64QfzOPPYRrm2SYaR5fSreJZCgFKfRmnNg8Bgnj1Yn0qtTYu4mxrIYz0dq4g73hxbvgMWbiHA_uKwuJ1TaZ_0ianAsq09VKI8DIvmE0_jIZob1i8BKKUKHqUl7rfal',
				'Content-Type: application/json'
			  ),
			));
			
			$response = curl_exec($curl);

			error_log("fire ".$response." ".$fcm." ".$body."-".$titulo);
			
			curl_close($curl);
			
			return $response;
		} else {
			return false;
		}
	
	}

	public function getKeys($cleanPost)
	{
		//chatbotId

		if(isset($cleanPost['chatbotId'])) $chatbotId = $cleanPost['chatbotId'];
		else $chatbotId = FALSE;
		if(isset($cleanPost['msg'])) $word = $cleanPost['msg'];
		else $word = FALSE;
		if(isset($cleanPost['channel'])) $channel = $cleanPost['channel'];
		else $channel = FALSE;

		$this->db->select('*');
		$this->db->from('chatbot_web_user');
		$this->db->where('chatbotId', $chatbotId);
		$this->db->order_by("id", "desc");
		$this->db->limit(1);
		$bot_user = $this->db->get()->result_array();

		$otherdb = $this->load->database('optimus', TRUE);
		$otherdb->select('*');
		$otherdb->from('chatbot_web_users');
		$otherdb->where('id', $chatbotId);
		$otherdb->limit(1);
		$bot_op = $otherdb->get()->result_array();



		$nombre = $bot_op[0]['name'];
		$telefono = $bot_user[0]['phone'];
		$user = $bot_user[0]['id'];



		$status = 0;

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

		$otherdb = $this->load->database('optimus', TRUE);
		$otherdb->select('*');
		$otherdb->from('ticket_etiquetas');
		$keys = $otherdb->get()->result_array();

		if (count($keys) > 0) {
			$mensaje = strtolower($word);
			$mensaje = urldecode($mensaje);
			$mensaje = normaliza2($mensaje);
			foreach ($keys as $value) {
				$exp[$value['id']]['id'] = $value['id'];
				$exp[$value['id']]['categoria'] = $value['ticket_categoria_id'];
				$exp[$value['id']]['proyecto'] = $value['ticket_proyectos_id'];
				$exp[$value['id']]['grupo'] = $value['est_group_id'];
				$chk[$value['id']] = strtolower($value['nombre']);
			}
			$found = FALSE;
			$count = 0;
			$hooman = array();
			foreach ($chk as $value3) {
				if (strpos($mensaje, normaliza2($value3)) !== false) {
					$key = array_search($value3, $chk);
					$msg = $value3;
					$hooman[$count]['key'] = $key;
					$hooman[$count]['msg'] = strlen(utf8_decode($msg));
					$found = TRUE;
					$count++;
				}
			}

		if ($found == TRUE) {
			
				$otherdb = $this->load->database('optimus', 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('optimus', 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();

				$proyecto = $exp[$value['id']]['proyecto'] ;
				$grupo1 = $exp[$value['id']]['grupo'] ;
				$categoria1 = $exp[$value['id']]['grupo'] ;

				$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'])) {
					$status = 1;
					$agente = $agente->result_array[0]['agente'];
					if( !isset($test[0]['id'])){
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => $categoria1,
							'canal' => $channel,
							'proyecto' => $proyecto,
							'prioridad' => 2,
							'etiquetas' => $key,
							'asunto' => $chk[$key],
							'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();
						$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'])){
						$status = 2;
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => $categoria1,
							'canal' => $channel,
							'proyecto' => $proyecto,
							'prioridad' => 4,
							'etiquetas' => $key,
							'asunto' => $chk[$key],
							'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();
						$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 {
			
			return $status;
		} 
		} 

	}

	

}
