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


class Md_express extends CI_Model {

	public function sendWapiText($reply, $conversation, $data, $token) {

		$curl = curl_init();
		curl_setopt_array($curl, array(
		  CURLOPT_URL => $reply,
		  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_number": "'.$conversation.'",
		  "type": "text",
		  "message": "'.$data.'"
		}',
		  CURLOPT_HTTPHEADER => array(
			'x-maytapi-key: '.$token,
			'Content-Type: application/json',
			'Cookie: __cfduid=d1c4a86aeca1f2822ab8b46d9c775b4fc1614820551'
		  ),
		));
		
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}

	public function sendWapiImg($reply, $conversation, $data, $token) {

		$curl = curl_init();

		curl_setopt_array($curl, array(
			CURLOPT_URL => $reply,
			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_number": "'.$conversation.'",
			"type": "media",
			"message": "'.$data.'"
		  }',
			CURLOPT_HTTPHEADER => array(
			  'x-maytapi-key: '.$token,
			  'Content-Type: application/json',
			  'Cookie: __cfduid=df314b968d3e688844e5610aef92daba81611443255'
			),
		  ));
		
		$response = curl_exec($curl);
		return $response;
	}


	public function getTicket($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;
		if(isset($cleanPost['proyecto'])) $proyecto = $cleanPost['proyecto'];
		else $proyecto = FALSE;
		if(isset($cleanPost['grupo1'])) $grupo1 = $cleanPost['grupo1'];
		else $grupo1 = FALSE;

		$status = 0;

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

		if (count($keys) > 0) {
			$mensaje = strtolower($word);
			$mensaje = urldecode($mensaje);
			$mensaje = normaliza($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'];
				$chk[$value['id']] = strtolower($value['nombre']);
			}
			$found = FALSE;
			$count = 0;
			$hooman = array();
			foreach ($chk as $value3) {
				if (strpos($mensaje, normaliza($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) {
				$maxi = max(array_column($hooman, 'msg'));
				$key = array_search($maxi, array_column($hooman, 'msg'));
				$key = $hooman[$key]['key'];
			} else {
				$key=41;
				$chk[$key];
			}

				$otherdb = $this->load->database('saks', 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('saks', TRUE);
				$otherdb->from('ticket_email');
				$otherdb->where('cliente', $cliente);
				$otherdb->where('canal', $channel);
				$otherdb->where('status', 10);
				$test = $otherdb->get()->result_array();

				/*SELECT COUNT(*) as "cantidad", ss3nu_users.id FROM `ticket_email` JOIN ss3nu_users ON ss3nu_users.id = ticket_email.agente WHERE status = 2 GROUP BY ss3nu_users.id HAVING cantidad < 20 ORDER BY cantidad ASC*/
/*
				$otherdb = $this->load->database('saks', TRUE);
				$otherdb->select('id as "agente"');
				$otherdb->from('ss3nu_users');
				$agentes = $otherdb->get()->result_array();

				$otherdb = $this->load->database('saks', TRUE);
				$otherdb->select('COUNT(*) as "cantidad"');
				$otherdb->select('agente');
				$otherdb->from('ticket_email');
			//	$otherdb->join('ss3nu_users', 'ss3nu_users.id = ticket_email.agente');
				$otherdb->where('status', 2);
				$otherdb->group_by("agente");
				$otherdb->having('cantidad < ', 20);
				$otherdb->order_by('cantidad', 'ASC');
				$agente = $otherdb->get()->result_array();*/
				//50253095931

					$status = 1;
					$agente = 1853;
					if( !isset($test[0]['id'])){
						$data2 = array(
							'cliente' => $cliente,
							'copia' => 1,
							'categoria' => 1,
							'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))),
							'fecha_cierre' => date("Y-m-d H:i:s", (time() + (1*60*60))),
							'creado_por' => 1853,
							'status' => 10,
							'nivel' => "",
							'view' =>  0,
							'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);
					}
				 

				return  $status;
				
		}
		return $status;

		} else return $status;

	}

	public function putLive($user, $account) {

			$timer = time() - strtotime($user[0]['last_active']);

			if($timer >= 600) {
				$bot = 0;
			} else $bot = $user[0]['bot'];

			$data2 = array(
							'live' => 1,
							'active' => 0,
							'bot' => $bot,
							'last_active' => date("Y-m-d H:i:s"),
			);
			$this->db->where('id', $user[0]['id']);
			$return = $this->db->update('chatbot_web_user', $data2);

			$this->db->select('*');
			$this->db->from('bots_send_msg');
			$this->db->where('account_id', $account);
			$this->db->where('chatbot_web_user_id', $user[0]['id']);
			$this->db->where('leido', 0);
			$data = $this->db->get()->result_array();
			if($data) {
				$return2 = $data;
				foreach ($data as $value) {

					$data2 = array(
									'leido' => 1,
					);
					$this->db->where('id', $value['id']);
					$this->db->update('bots_send_msg', $data2);
				}
			} else $return2 = FALSE;

		return $return2;
	}

	public function getAccountWs($phone) {

		$this->db->select('*');
		$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;

		} else 	return false;
	}

	public function updateCycleWs($user, $cycle) {

		$data2 = array(
			'bot_cycle' => $cycle,
		);
		$this->db->where('id', $user);
		$this->db->update('bots_whatsapp_user', $data2);
	}
	
	public function getUserWs($phone_client, $phone_bot, $account_id, $name) {

		$this->db->select('*');
		$this->db->from('bots_whatsapp_user');
		$this->db->where('phone_client', $phone_client);
		$this->db->where('phone', $phone_bot);
		$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 	{

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

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

	public function putMsgWs($phone_client, $phone_bot, $account_id, $msg, $user, $key, $type, $uid, $time) {

		$data3 = array(
				'phone_client' => $phone_client,
				'phone' => $phone_bot,
				'account_id' => $account_id,
				'user' => $user,
				'body' => $msg,
				'uid' => $uid,
				'timex' => $time,
				'type' => $type,
				'mensaje' => base64_encode($msg),
				'bots_key_id' => $key,
		);
		$this->db->insert('bots_whatsapp', $data3);

		$insert_id = $this->db->insert_id();
		return $insert_id;
		
	}

	public function sendImageWs($token, $from, $to, $image, $url)
    {
      $curl = curl_init();
      
      curl_setopt_array($curl, array(
        CURLOPT_URL => "https://www.waboxapp.com/api/send/image",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "token=".$token."&uid=".$from."&to=".$to."&url=".$image."&caption=Imagen&description=".$url,
        CURLOPT_HTTPHEADER => array(
          "cache-control: no-cache",
          "content-type: application/x-www-form-urlencoded",
          "postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
        ),
      ));

      $response = curl_exec($curl);
      $err = curl_error($curl);

      curl_close($curl);
    }

    public function sendTextWs($token, $from, $to, $msg)
      {
        $curl = curl_init();

        //$msg = str_replace(",","",$msg);
        $msg = urlencode( $msg);

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://www.waboxapp.com/api/send/chat",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => "token=".$token."&uid=".$from."&to=".$to."&text=".$msg,
          CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache",
            "content-type: application/x-www-form-urlencoded",
            "postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);
      }

	public function getLive($account, $ip, $device) {

		$this->db->select('*');
		$this->db->from('chatbot_web_user');
		$this->db->where('ip', $ip);
		$this->db->where('device', $device);
		$this->db->where('account_id', $account);
		$test_usr = $this->db->get()->result_array();

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

			return $test_usr;

		} else 	return false;
	}

	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 getUser($username, $account_id) {

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

	public function getUserTigo($username, $account_id) {

		$this->db->select('*');
		$this->db->from('bots_tigo_user');
		$this->db->where('phone', $username);
		$this->db->where('account_id', $account_id);
		return $this->db->get()->result_array();
	}

	public function sendTigo($phone, $msg) {


		$curl = curl_init();

		curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://prod.api.tigo.com/oauth/client_credential/accesstoken?grant_type=client_credentials',
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_SSL_VERIFYHOST => false,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/json',
			'Authorization: Basic YW5TbkRXeFgxWG9mOVlCQUxTdXVKYjJ6cUtLeWxrcjU6alRYQWFaYjBkRGJib1VUSw=='
		),
		));

		$response = curl_exec($curl);
		error_log("tigo 1".$response);
		curl_close($curl);

		$response = json_decode($response);

		if(isset($response->access_token)) {

			$token = $response->access_token;
			$curl = curl_init();

			curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://prod.api.tigo.com/v1/tigo/b2b/gt/comcorp/messages/organizations/5fc7fb16f6128200015ca17d',
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>'{
			"protocol": "sms",
			"shortcodeId": "CruzVerde",
			"shortcodeType": "pretty_code",
			"msisdn": "'.$phone.'",
			"priority": 0,
			"body": "'.$msg.'"
			}',
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json',
				'APIKey: 61DM1sx0Dx40YSZwnrQwZ7iIn0FyVKCs',
				'APISecret: 4s7NH29TefUEPZe2ZOIWIZ5fO1jIgI7DaHsVvzfWwZ65klwU2mXJtfhZ',
				'Authorization: Bearer '.$token
			),
			));
			
			$response = curl_exec($curl);
			
			curl_close($curl);
			
			error_log("tigo 2".$response);
		}

		return $response;
	}

	public function getUserTwitter($username) {

		$this->db->select('*');
		$this->db->from('bots_manager_twitter');
		$this->db->where('tweet_user', $username);
		return $this->db->get()->result_array();
	}

	public function inserTigo($account, $phone) {

		$data3 = array(
					'bot_cycle' => 0,
					'account_id' => $account,
					'date_created' => date('Y-m-d H:i:s'),
					'last_active' => date('Y-m-d H:i:s'),
					'status' => 0,
					'active' => 0,
					'checkx' => 0,
					'deleted' => 0,
					'agent' => 0,
					'name' => "",
					'email' => "",
					'phone' => $phone,
		);
		$this->db->insert('bots_tigo_user', $data3);

		$insert_id = $this->db->insert_id();

		return $insert_id;
	}

	public function inserTigoChat($userId, $word, $keyWord, $account, $botsKey, $agent, $type) {

		$data3 = array(
					'user_id' => $userId,
					'msg' => base64_encode($word),
					'key_word' => $keyWord,
					'time' => date('Y-m-d H:i:s', time() + (60*60*1)),
					'type' => $type,
					'account_id' => $account,
					'bots_key_id' => $botsKey,
					'agent' => $agent,
		);
		$this->db->insert('chats_tigo', $data3);

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

		return FALSE;
	}

	public function inserInstagram($account, $name, $username, $pic, $pk) {

		$data3 = array(
					'bot_cycle' => 0,
					'account_id' => $account,
					'date_created' => date('Y-m-d H:i:s'),
					'last_active' => date('Y-m-d H:i:s'),
					'status' => 0,
					'active' => 0,
					'checkx' => 0,
					'deleted' => 0,
					'agent' => 0,
					'name' => $name,
					'email' => "",
					'phone' => "",
					'username' => $username,
					'profile_pic_url' => $pic,
					'pk' => $pk,
		);
		$this->db->insert('bots_instagram_user', $data3);

		$insert_id = $this->db->insert_id();

		return $insert_id;
	}

	public function inserInstagramChat($userId, $word, $keyWord, $account, $botsKey, $agent,$type) {

		$data3 = array(
					'user_id' => $userId,
					'msg' => base64_encode($word),
					'key_word' => $keyWord,
					'time' => date('Y-m-d H:i:s'),
					'type' => $type,
					'account_id' => $account,
					'bots_key_id' => $botsKey,
					'agent' => $agent,
		);
		$this->db->insert('chats_instagram', $data3);

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

		return FALSE;
	}

	public function inserInstagramChatNew($userId, $word, $keyWord, $account, $botsKey, $agent, $type, $profile_pic_url) {

		$data3 = array(
					'user_id' => $userId,
					'msg' => base64_encode($word),
					'key_word' => $keyWord,
					'time' => date('Y-m-d H:i:s'),
					'type' => $type,
					'account_id' => $account,
					'bots_key_id' => $botsKey,
					'agent' => $agent,
		);
		$this->db->insert('chats_instagram', $data3);

		$data2 = array(
			'last_active' => date('Y-m-d H:i:s'),
			'checkx' => 0,
			'profile_pic_url' => $profile_pic_url,

		);
		$this->db->where('id', $userId);
		$this->db->update('bots_instagram_user', $data2);

		return FALSE;
	}

	public function getUserInstagram($id) {

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

	public function getUseradm($id) {

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

	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 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 getEncResp($id) {

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

	public function getEncRespId($id) {

		$this->db->select('*');
		$this->db->from('bots_keys_encuestas');
		$this->db-> where('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 getCycle($ip, $device, $account) {

		$this->db->select('*');
		$this->db->from('chatbot_web_user');
		$this->db->where('ip', $ip);
		$this->db->where('device', $device);
		$this->db->where('account_id', $account);
		$test_usr = $this->db->get()->result_array();

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

			$this->db->select('*');
			$this->db->from('bot_cycle');
			$this->db->where('user_id', $user);

			$return2 = $this->db->get()->result_array();
			if( empty( $return2 ) ) {
				$return = 0;
			} else if($return2[0]['active']){

				$data2 = array(
								'active' => 0,
				);
				$this->db->where('user_id', $user);
				$this->db->update('bot_cycle', $data2);

				$return = $return2[0]['key_id'];


			} else {
				$return = 0;
			}
		}

		return $return;

	}

	public function getMensajes($id) {

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

	public function getMensajes2($id) {

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

	public function putMsg($phone_client, $msg, $type, $account_id, $botsKeyID, $keyID, $phone, $word, $typeA) {

		$return = FALSE;

		$this->db->select('*');
		$this->db->from('bots_sms_user');
		$this->db->where('phone_client', $phone_client);
		$this->db->where('phone', $phone);
		$this->db->where('account_id', $account_id);
		$test_usr = $this->db->get()->result_array();

		if( empty($test_usr) && !empty($phone_client) ) {

			$data2 = array(
							'phone_client' => $phone_client,
							'phone' => $phone,
							'name' => '',
							'email' => '',
							'account_id' => $account_id,
							'checkx' => 0,
							'timex' => date('Y-m-d H:i:s'),
							'last_active' => date('Y-m-d H:i:s'),
							'bot' => 0,
							'live' => 0,
							'active' => 0,
			);
			$this->db->insert('bots_sms_user', $data2);
			$new_id = $this->db->insert_id();

			if($new_id) {
				$data3 = array(
					'account_id' => $account_id,
					'type' => 20,
					'active' => 1,
					'user_id' => $return,
					'fecha' => date('Y-m-d H:i:s'),
				);
				$this->db->insert('bots_alerts', $data3);
			}
			//true or false
			$data = array(
							'phone_client' => $phone_client,
							'phone' => $phone,
							'user' => $new_id,
							'body' => $msg,
							'uid' => $keyID,
							'mensaje' => $msg,
							'timex' => time(),
							'type' => $type,
							'account_id' => $account_id,
							'bots_key_id' => $botsKeyID,
			);
			$return = $this->db->insert('bots_sms', $data);

		/*	if($typeA == 4){
				$data = array(
								'user_id' => $new_id,
								'active' => 1,
								'key_id' => $botsKeyID,
				);
				$this->db->insert('bot_cycle', $data);
			} else {
				$data = array(
								'user_id' => $new_id,
								'active' => 0,
								'key_id' => $botsKeyID,
				);
				$this->db->insert('bot_cycle', $data);
			}*/

		} else {

			$data2 = array(
							'checkx' => 0,
							'last_active' => date("Y-m-d H:i:s"),
			);

			$this->db->where('id', $test_usr[0]['id']);
			$return = $this->db->update('bots_sms_user', $data2);

			$data = array(
							'phone_client' => $phone_client,
							'phone' => $phone,
							'user' => $test_usr[0]['id'],
							'body' => $msg,
							'uid' => $keyID,
							'mensaje' => $msg,
							'timex' => time(),
							'type' => $type,
							'account_id' => $account_id,
							'bots_key_id' => $botsKeyID,
			);
			$return = $this->db->insert('bots_sms', $data);

			/*if($typeA == 4){

				$this->db->select('*');
				$this->db->from('bot_cycle');
				$this->db->where('user_id', $test_usr[0]['id']);
				$botCycle = $this->db->get()->result_array();

				if( empty($botCycle) ) {
					$data = array(
									'user_id' => $test_usr[0]['id'],
									'active' => 1,
									'key_id' => $botsKeyID,
					);
					$this->db->insert('bot_cycle', $data);
				} else {
					$data2 = array(
									'active' => 1,
									'key_id' => $botsKeyID,
					);
					$this->db->where('user_id', $test_usr[0]['id']);
					$return = $this->db->update('bot_cycle', $data2);
				}

			} else {
				$this->db->select('*');
				$this->db->from('bot_cycle');
				$this->db->where('user_id', $test_usr[0]['id']);
				$botCycle = $this->db->get()->result_array();

				if( empty($botCycle) ) {
					$data = array(
									'user_id' => $test_usr[0]['id'],
									'active' => 0,
									'key_id' => $botsKeyID,
					);
					$this->db->insert('bot_cycle', $data);
				} else {
					$data2 = array(
									'active' => 0,
									'key_id' => $botsKeyID,
					);
					$this->db->where('user_id', $test_usr[0]['id']);
					$return = $this->db->update('bot_cycle', $data2);
				}
			}*/

		}

		return $return;
	}

	public function putMsgOld($user, $msg, $type, $accountID, $botsKeyID, $keyID, $device, $word) {

		$return = FALSE;
		$this->db->select('*');
		$this->db->from('chatbot_web_user');
		$this->db->where('ip', $user);
		$this->db->where('device', $device);
		$this->db->where('account_id', $accountID);
		$test_usr = $this->db->get()->result_array();

		if( empty($test_usr) && !empty($user) ) {

			$data2 = array(
							'ip' => $user,
							'device' => $device,
							'account_id' => $accountID,
							'time' => date('Y-m-d H:i:s'),
							'last_active' => date('Y-m-d H:i:s'),
							'check' => 0,
							'live' => 0,
							'active' => 0,
							'bot' => 0,
			);
			$this->db->insert('chatbot_web_user', $data2);
			$new_id = $this->db->insert_id();
			//true or false
			$data = array(
							'user' => $new_id,
							'msg' => $msg,
							'time' => time(),
							'type' => $type,
							'account_id' => $accountID,
							'bots_key_id' => $botsKeyID,
							'keyenc_id' => $keyID,
							'message' => $this->db->escape($word),
							'live' => 0,
			);
			$return = $this->db->insert('chatbot_web', $data);

		} else {

			$timer = time() - strtotime($test_usr[0]['last_active']);

				if($timer >= 600) {
					$bot = 0;
				} else $bot = $test_usr[0]['bot'];

			$data2 = array(
							'check' => 0,
							'last_active' => date("Y-m-d H:i:s"),
							'bot' => $bot,
			);
			$this->db->where('id', $test_usr[0]['id']);
			$return = $this->db->update('chatbot_web_user', $data2);

			$data = array(
							'user' => $test_usr[0]['id'],
							'msg' => $msg,
							'time' => time(),
							'type' => $type,
							'account_id' => $accountID,
							'bots_key_id' => $botsKeyID,
							'keyenc_id' => $keyID,
							'message' => $this->db->escape($word),
							'live' => $test_usr[0]['bot'],
			);
			$return = $this->db->insert('chatbot_web', $data);

		}

		return $return;
	}

	public function putUser($phone_client, $phone, $account_id) {

		$this->db->select('*');
		$this->db->from('bots_sms_user');
		$this->db->where('phone_client', $phone_client);
		$this->db->where('phone', $phone);
		$this->db->where('account_id', $account_id);
		$test_usr = $this->db->get()->result_array();
		$return = FALSE;

		if( empty($test_usr) ) {

			$data2 = array(
							'phone_client' => $phone_client,
							'phone' => $phone,
							'name' => '',
							'email' => '',
							'account_id' => $account_id,
							'checkx' => 0,
							'timex' => date('Y-m-d H:i:s'),
							'last_active' => date('Y-m-d H:i:s'),
							'bot' => 0,
							'live' => 0,
							'active' => 0,
			);
			$this->db->insert('bots_sms_user', $data2);
			$return = $this->db->insert_id();

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


		} else $return = FALSE;

		return $return;
	}


		public function getUsers($user, $channel) {

			$return = FALSE;

			if($channel == 'facebook'){

				$this->db->select('*');
				$this->db->from('facebook_accounts');
				$this->db->where('user_id', $user);
				$facebookAc = $this->db->get()->result_array();

				$return = $facebookAc;

				if($facebookAc){

					$this->db->select('id, user_id, CONCAT(first_name, " ", last_name) AS name, email, phone, date_created, last_active');
					$this->db->from('bots_manager');
					$this->db->where('account_id', $facebookAc[0]['id']);
					$this->db->order_by("id", "ASC");
					$return = $this->db->get()->result_array();
				}

			} else if($channel == 'web'){

				$this->db->select('id, id AS user_id, name, email, phone, time AS date_created, last_active');
				$this->db->from('chatbot_web_user');
				$this->db->where('account_id', $user);
				$this->db->order_by("id", "ASC");
				$return = $this->db->get()->result_array();

			} else if($channel == 'twitter'){

				$this->db->select('*');
				$this->db->from('twitter_accounts');
				$this->db->where('user_id', $user);
				$twitterAc = $this->db->get()->result_array();

				if($twitterAc){

					$this->db->select('id, tweet_user AS user_id, date AS date_created');
					$this->db->from('bots_manager_twitter');
					$this->db->where('account_id', $twitterAc[0]['id']);
					$return = $this->db->get()->result_array();
				}

			} else if($channel == 'whatsapp'){

					$this->db->select('id, phone_client AS user_id, name, email, phone_client AS phone, timex AS date_created, last_active');
					$this->db->from('bots_whatsapp_user');
					$this->db->where('account_id', $user);
					$this->db->order_by("id", "ASC");
					$return = $this->db->get()->result_array();

			}

			return $return;

		}

		public function putMessages( $client_id, $channel, $msg, $account, $url, $caption) {

			if($account[0]['role'] == 0){
				$account = $account[0]['id'];
			} else {
				$account = $account[0]['account_id'];
			}

			//$return = $account;
			$new_id = FALSE;

			if($channel == 'facebook'){

				$user_id = 0;


				$this->db->select('*');
				$this->db->from('chatbot');
				$this->db->where('user', $client_id);
				$this->db->order_by("id", "desc");
				$this->db->limit(1);
				$test = $this->db->get()->result_array();


				if($test){
					$chat =  $test[0]['id'];
				} else {
					$chat = 0;
				}


				$this->db->select('*');
				$this->db->from('bots_manager');
				$this->db->where('account_id', $account);
				$this->db->where('user_id', $client_id);
				$this->db->order_by("id", "desc");
				$this->db->limit(1);
				$test2 = $this->db->get()->result_array();

				if($test2){
					$user_id =  $test2[0]['id'];
				} else {
					$user_id = 0;
				}

				if(!empty($msg)){

					$data2 = array(
						'account_id' => $account,
						'message' => base64_encode($msg),
						'chatbot_web_user_id' => $user_id,
						'time' => date('Y-m-d H:i:s'),
						'leido' => 0,
						'user_id' => $account,
						'chatbot_web_id' => $chat,
					);
					$this->db->insert('bots_send_msg_fb', $data2);
					$new_id = $this->db->insert_id();

					$return = $new_id;


					$this->db->select('*');
					$this->db->from('facebook_accounts');
					$this->db->where('user_id', $account);
					$this->db->order_by("id", "desc");
					$this->db->limit(1);
					$test3 = $this->db->get()->result_array();

							$jsonData = "{
								'recipient': {
									'id': $client_id
								},
								'message': {
										'text':'$msg',
									}
							}";

					  $url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$test3[0]['token'];

					  if(isset($jsonData)) {
						$ch = curl_init($url);
						curl_setopt($ch, CURLOPT_POST, true);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
						curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
						curl_exec($ch);
					  }
				}



			} else if($channel == 'web'){

				$this->db->select('*');
				$this->db->from('chatbot_web_user');
				$this->db->where('id', $client_id);
				$test2 = $this->db->get()->result_array();

				if($test2) {

					if($test2[0]['live']){

						$this->db->select('*');
						$this->db->from('chatbot_web');
						$this->db->where('user', $client_id);
						$this->db->where('type', 0);
						$this->db->order_by("id", "desc");
						$this->db->limit(1);
						$test = $this->db->get()->result_array();

						if($test){
							$chat = $test[0]['id'];
						} else {
							$chat = 0;
						}

						if(!empty($msg)){

							$data2 = array(
									'account_id' => $account,
									'message' => base64_encode($msg),
									'chatbot_web_user_id' => $client_id,
									'time' => date('Y-m-d H:i:s'),
									'leido' => 0,
									'user_id' => $account,
									'chatbot_web_id' => $chat,
							);
							$this->db->insert('bots_send_msg', $data2);
							$new_id = $this->db->insert_id();

							$return = $new_id;

						}
					} else $return = 'User not active';

				} else $return = 'User not found';


			} else if($channel == 'whatsapp'){


				$this->db->select('*');
				$this->db->from('bots_whatsapp');
				$this->db->where('phone_client', $client_id);
				$this->db->order_by("id", "desc");
				$this->db->limit(1);
				$test = $this->db->get()->result_array();

				$this->db->select('*');
				$this->db->from('whatsapp_accounts');
				$this->db->where('user_id', $account);
				$this->db->limit(1);
				$fromWs = $this->db->get()->result_array();

				if($test){
					$chat = $test[0]['id'];
					$clientId = $test[0]['user'];
					$from = $test[0]['phone'];
				} else {
					$chat = 0;
					$clientId = 0;
					$from = 0;
				}

				if(!empty($msg)){

					$data2 = array(
						'account_id' => $account,
						'message' => base64_encode($msg),
						'chatbot_web_user_id' => $clientId,
						'time' => date('Y-m-d H:i:s'),
						'leido' => 0,
						'user_id' => $account,
						'chatbot_web_id' => $chat,
					);
					$this->db->insert('bots_send_msg_ws', $data2);
					$new_id = $this->db->insert_id();

					$return = $new_id;

					$curl = curl_init();

							curl_setopt_array($curl, array(
								CURLOPT_URL => "https://www.waboxapp.com/api/send/chat",
								CURLOPT_RETURNTRANSFER => true,
								CURLOPT_ENCODING => "",
								CURLOPT_MAXREDIRS => 10,
								CURLOPT_TIMEOUT => 30,
								CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
								CURLOPT_CUSTOMREQUEST => "POST",
								CURLOPT_POSTFIELDS => "token=a13316d6a35849afffa8fbef4fd00ffd5c7545568340f&uid=".$fromWs[0]['phone']."&to=".$client_id."&text=".$msg,
								CURLOPT_HTTPHEADER => array(
									"cache-control: no-cache",
									"content-type: application/x-www-form-urlencoded",
									"postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
								),
							));

							$response = curl_exec($curl);
							$err = curl_error($curl);

					curl_close($curl);

				}

				if($url){

					$data2 = array(
						'account_id' => $account,
						'message' => base64_encode($url),
						'chatbot_web_user_id' => $clientId,
						'time' => date('Y-m-d H:i:s'),
						'leido' => 0,
						'user_id' => $account,
						'chatbot_web_id' => $chat,
					);
					$this->db->insert('bots_send_msg_ws', $data2);
					$new_id = $this->db->insert_id();

					$return = $new_id;


					$curl = curl_init();

					curl_setopt_array($curl, array(
						CURLOPT_URL => "https://www.waboxapp.com/api/send/media",
						CURLOPT_RETURNTRANSFER => true,
						CURLOPT_ENCODING => "",
						CURLOPT_MAXREDIRS => 10,
						CURLOPT_TIMEOUT => 30,
						CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
						CURLOPT_CUSTOMREQUEST => "POST",
						CURLOPT_POSTFIELDS => "token=a13316d6a35849afffa8fbef4fd00ffd5c7545568340f&uid=".$fromWs[0]['phone']."&to=".$client_id."&url=".$url."&caption=".$caption."&url_thumb=".$url,
						CURLOPT_HTTPHEADER => array(
							"cache-control: no-cache",
							"content-type: application/x-www-form-urlencoded",
							"postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
						),
					));

					$response = curl_exec($curl);
					$err = curl_error($curl);

					if($err) {
						print_r($err);
						exit;
					}

					curl_close($curl);

				}

			}

			return $return;

		}

		public function getMessages($user, $channel, $account) {

			$return = FALSE;

			$id = $account['id'];

			if($channel == 'facebook') {

				$this->db->select('id');
				$this->db->from('facebook_accounts');
				$this->db->where('user_id', $id);
				$account = $this->db->get()->result_array();

				if($account) {
					$this->db->select('id, user AS user_id, FROM_BASE64(msg) AS message, time');
					$this->db->from('chatbot');
					$this->db->where('user', $user);
					$this->db->where('type', 0);
					$this->db->where('account_id', $account[0]['id']);
					$this->db->order_by("id", "ASC");
					$return = $this->db->get()->result_array();
				} else {
					$return = FALSE;
				}

			} else if($channel == 'web') {

				$this->db->select('id, user AS user_id, msg AS message, time');
				$this->db->from('chatbot_web');
				$this->db->where('user', $user);
				$this->db->where('type', 0);
				$this->db->order_by("id", "ASC");
				$return = $this->db->get()->result_array();

			} else if($channel == 'twitter') {

				$this->db->select('id');
				$this->db->from('twitter_accounts');
				$this->db->where('user_id', $id);
				$account = $this->db->get()->result_array();

				if($account) {
					$this->db->select('id, user AS user_id, msg AS message, time');
					$this->db->from('chats_twitter');
					$this->db->where('user', $user);
					$this->db->where('type', 0);
					$this->db->where('account_id', $account[0]['id']);
					$this->db->order_by("id", "ASC");
					$return = $this->db->get()->result_array();
				} else {
					$return = FALSE;
				}

			} else if($channel == 'whatsapp') {

				$this->db->select('id, phone_client AS user_id, FROM_BASE64(mensaje) AS message, timex AS time');
				$this->db->from('bots_whatsapp');
				$this->db->where('phone_client', $user);
				$this->db->where('account_id', $id);
				$this->db->order_by("id", "ASC");
				//$this->db->where('type', 'chat');
				$return = $this->db->get()->result_array();

			}

			return $return;

		}
}
