<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Hector Luna
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Web extends REST_Controller {

	function __construct() {
		header('Access-Control-Allow-Origin: *');
		header("Access-Control-Allow-Headers: Content-Type, Cache-Control");
		header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");
		$method = $_SERVER['REQUEST_METHOD'];
		if($method == "OPTIONS") {
				die();
		}

		parent::__construct();
		//$this->load->model('Md_facebook');
		$this->load->model('Md_bot');
		$this->load->model('Md_optimus');
		$this->load->model('Md_optsupport');
		$this->load->library('form_validation');
	}

	public function welcome_get() {

			$account = $this->Md_bot->getUser($this->get('auth'));
			$mensajes = $this->Md_bot->getMensajes($account[0]['id']);

			if( isset( $mensajes[0]['bienvenida'] ) && $mensajes[0]['bienvenida'] != '' ) {
				$data = $mensajes[0]['bienvenida'];
			} else {
				$data = '';
			}

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
	}

	public function threads_get() {

			$account = $this->Md_bot->getUser($this->get('auth'));

			if( isset( $account[0]['id'] )) {
				$data = $this->Md_optimus->getHilos($this->get('user'));
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Results', 'data' => $data], REST_Controller::HTTP_OK);
			} else {
				$data = array();
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Auth key not found', 'data' => $data], REST_Controller::HTTP_OK);
			}

	}

	public function killroom_get() {

		$test = $this->Md_optimus->kill();

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Results', 'data' => $test ], REST_Controller::HTTP_OK);
		

	}

	public function sendfire_get() {

			$this->Md_optsupport->firebaseOptimus($this->get('title'), $this->get('body'), $this->get('fcm'));

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Results', 'data' => array()], REST_Controller::HTTP_OK);

	}

	public function sendfire_post() {

		
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		$this->Md_optsupport->firebaseOptimusJson($cleanPost);


			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Results', 'data' => array()], REST_Controller::HTTP_OK);

	}

	public function pending_get() {

			$data = $this->Md_optimus->pending($this->get('id'));

			if( isset( $data['room'] )) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Results', 'data' => $data], REST_Controller::HTTP_OK);
			} else {
				$data = array();
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No Call found', 'data' => $data], REST_Controller::HTTP_OK);
			}

	}

	public function status_post() {

		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

			$room = $this->Md_optimus->callstatus($cleanPost);

			if( $room ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Room', 'data' => $room], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error ', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function allusers_get() {

			$room = $this->Md_optimus->allusers();

			if( $room ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Room', 'data' => $room], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error ', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function call_post() {

		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		$userTo = $this->Md_optimus->getUser($post['userTo']);
		$userFrom = $this->Md_optimus->getUser($post['userFrom']);

		if(isset($userFrom['name']) && isset($userTo['token_firebase']) && !empty($userTo['token_firebase'])) {
			$this->Md_optsupport->firebaseOptimusCall('Optimus Connect', 'New Call From '.$userFrom['name'], $userTo['token_firebase']);
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'New Call From '.$userFrom['name'], 'data' => array()], REST_Controller::HTTP_OK);

		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error', 'data' => array()], REST_Controller::HTTP_OK);

		}

			/*$room = $this->Md_optimus->createcall($cleanPost);

			if( $room['error'] == 2 ) {
				$userTo = $this->Md_optimus->getUser($post['userTo']);
				$userFrom = $this->Md_optimus->getUser($post['userFrom']);

				$this->Md_optsupport->firebaseOptimus('Optimus Connect', 'New Call From '.$userFrom['name'], $userTo['token_firebase']);
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Room', 'data' => $room], REST_Controller::HTTP_OK);
			} else if( $room['error'] == 1 ) {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'On Another Call', 'data' => array()], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error', 'data' => array()], REST_Controller::HTTP_OK);
			}*/

	}

	public function groups_get() {

			$groups = $this->Md_optimus->getGroups($this->get('user'));

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Grupos', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existen grupos para este usuario', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function all_get() {

			$groups = $this->Md_optimus->getAll($this->get('user'));

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Grupos', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existen grupos para este usuario', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function users_get() {

			$groups = $this->Md_optimus->getUsers($this->get('user'));

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Usuarios', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No hay usuarios', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function user_get() {

			$groups = $this->Md_optimus->getUser($this->get('user'));

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Usuarios', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No hay usuarios', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function token_post() {

		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

			$groups = $this->Md_optimus->putToken($cleanPost);

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'usuario', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function username_get() {

			$groups = $this->Md_optimus->getUsername($this->get('user'),$this->get('password'),$this->get('AndroidID'),$this->get('FCMToken'));

			if( $groups ) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'usuario', 'data' => $groups], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			}

	}

	public function setReminder_get() {

			$test = $this->Md_optimus->getReminders($this->get('user'));

		//	if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Reminders', 'data' => $test], REST_Controller::HTTP_OK);

		//	} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			
	}

	public function deleteReminder_get() {

			$test = $this->Md_optimus->deleteReminders($this->get('user'),$this->get('id'));

			if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Reminders', 'data' => $test], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			
	}

	public function setReminder_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);
		error_log("opt ".json_encode($cleanPost));
			$test = $this->Md_optimus->setReminder($cleanPost);

			if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $test], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => '', 'data' => array()], REST_Controller::HTTP_OK);
			

	}

	public function setLater_get() {

			$test = $this->Md_optimus->getLaters($this->get('user'));

	//		if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Notifications', 'data' => $test], REST_Controller::HTTP_OK);

	//		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			
	}

	public function deleteLater_get() {

			$test = $this->Md_optimus->deleteLater($this->get('user'),$this->get('id'));

			if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Notifications', 'data' => $test], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No existe el usuario', 'data' => array()], REST_Controller::HTTP_OK);
			
	}

	public function setLater_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);
			error_log("opt ".json_encode($cleanPost));

			$test = $this->Md_optimus->setLater($cleanPost);

			if ( $test ) {

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $test], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => '', 'data' => array()], REST_Controller::HTTP_OK);
			
	}

	public function uploadAvatar_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$chatbotId = $cleanPost['chatbotId'];

			$config['upload_path']          = './uploads/';
			$config['allowed_types']        = 'gif|jpg|png|jpeg|GIF|JPG|PNG|JPEG';
			$config['max_size']             = 8192;
			$config['max_width']            = 8192;
			$config['max_height']           = 8192;

			$this->load->library('upload', $config);

			if ( ! $this->upload->do_upload('userfile')) {
					$error = array('error' => $this->upload->display_errors());
					$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error uploading', 'data' => $error], REST_Controller::HTTP_OK);
			} else {
					$data = array('upload_data' => $this->upload->data());

					$data['upload_data']['file_url'] = 'https://api.fogatabot.com/api/admin/uploads/' . $data['upload_data']['file_name'];

					$return = $this->Md_optimus->putAvatar($data['upload_data']['file_url'], $chatbotId);
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Upload successfull', 'data' => $data['upload_data']['file_url']], REST_Controller::HTTP_OK);
			}
			

		}

	public function uploadFile_post() {

		$posts = $this->post();
		$cleanPost = $this->security->xss_clean($posts);

			$user = $cleanPost['user'];
			$type = $cleanPost['type'];
			$usr_dev = $cleanPost['usr_dev'];
			$chatbotId = $cleanPost['chatbotId'];
			$fogataTo = $cleanPost['fogataTo'];


			$account = $this->Md_bot->getUser($cleanPost['auth']);

			if(isset($account[0])) {
				$config['upload_path']          = './uploads/';
				$config['allowed_types']        = '*';
				$config['max_size']             = 8192;
				$config['max_width']            = 8192;
				$config['max_height']           = 8192;

				$this->load->library('upload', $config);

				if ( ! $this->upload->do_upload('userfile')) {
						$error = array('error' => $this->upload->display_errors());
						$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error uploading', 'data' => $error], REST_Controller::HTTP_OK);
				} else {
						$data = array('upload_data' => $this->upload->data());
						
						$tester = strpos($data['upload_data']['file_name'], '.');

						if ($tester) {
							$data['upload_data']['file_url'] = 'https://api.fogatabot.com/api/admin/uploads/' . $data['upload_data']['file_name'];
							$file = strtolower($data['upload_data']['file_name']);
						} else {


							$mime_map = [
								'video/3gpp2'                                                               => '3g2',
								'video/3gp'                                                                 => '3gp',
								'video/3gpp'                                                                => '3gp',
								'application/x-compressed'                                                  => '7zip',
								'audio/x-acc'                                                               => 'aac',
								'audio/ac3'                                                                 => 'ac3',
								'application/postscript'                                                    => 'ai',
								'audio/x-aiff'                                                              => 'aif',
								'audio/aiff'                                                                => 'aif',
								'audio/x-hx-aac-adts'                                                       => 'mp3',
								'audio/x-au'                                                                => 'au',
								'video/x-msvideo'                                                           => 'avi',
								'video/msvideo'                                                             => 'avi',
								'video/avi'                                                                 => 'avi',
								'application/x-troff-msvideo'                                               => 'avi',
								'application/macbinary'                                                     => 'bin',
								'application/mac-binary'                                                    => 'bin',
								'application/x-binary'                                                      => 'bin',
								'application/x-macbinary'                                                   => 'bin',
								'image/bmp'                                                                 => 'bmp',
								'image/x-bmp'                                                               => 'bmp',
								'image/x-bitmap'                                                            => 'bmp',
								'image/x-xbitmap'                                                           => 'bmp',
								'image/x-win-bitmap'                                                        => 'bmp',
								'image/x-windows-bmp'                                                       => 'bmp',
								'image/ms-bmp'                                                              => 'bmp',
								'image/x-ms-bmp'                                                            => 'bmp',
								'application/bmp'                                                           => 'bmp',
								'application/x-bmp'                                                         => 'bmp',
								'application/x-win-bitmap'                                                  => 'bmp',
								'application/cdr'                                                           => 'cdr',
								'application/coreldraw'                                                     => 'cdr',
								'application/x-cdr'                                                         => 'cdr',
								'application/x-coreldraw'                                                   => 'cdr',
								'image/cdr'                                                                 => 'cdr',
								'image/x-cdr'                                                               => 'cdr',
								'zz-application/zz-winassoc-cdr'                                            => 'cdr',
								'application/mac-compactpro'                                                => 'cpt',
								'application/pkix-crl'                                                      => 'crl',
								'application/pkcs-crl'                                                      => 'crl',
								'application/x-x509-ca-cert'                                                => 'crt',
								'application/pkix-cert'                                                     => 'crt',
								'text/css'                                                                  => 'css',
								'text/x-comma-separated-values'                                             => 'csv',
								'text/comma-separated-values'                                               => 'csv',
								'application/vnd.msexcel'                                                   => 'csv',
								'application/x-director'                                                    => 'dcr',
								'application/vnd.openxmlformats-officedocument.wordprocessingml.document'   => 'docx',
								'application/x-dvi'                                                         => 'dvi',
								'message/rfc822'                                                            => 'eml',
								'application/x-msdownload'                                                  => 'exe',
								'video/x-f4v'                                                               => 'f4v',
								'audio/x-flac'                                                              => 'flac',
								'video/x-flv'                                                               => 'flv',
								'image/gif'                                                                 => 'gif',
								'application/gpg-keys'                                                      => 'gpg',
								'application/x-gtar'                                                        => 'gtar',
								'application/x-gzip'                                                        => 'gzip',
								'application/mac-binhex40'                                                  => 'hqx',
								'application/mac-binhex'                                                    => 'hqx',
								'application/x-binhex40'                                                    => 'hqx',
								'application/x-mac-binhex40'                                                => 'hqx',
								'text/html'                                                                 => 'html',
								'image/x-icon'                                                              => 'ico',
								'image/x-ico'                                                               => 'ico',
								'image/vnd.microsoft.icon'                                                  => 'ico',
								'text/calendar'                                                             => 'ics',
								'application/java-archive'                                                  => 'jar',
								'application/x-java-application'                                            => 'jar',
								'application/x-jar'                                                         => 'jar',
								'image/jp2'                                                                 => 'jp2',
								'video/mj2'                                                                 => 'jp2',
								'image/jpx'                                                                 => 'jp2',
								'image/jpm'                                                                 => 'jp2',
								'image/jpeg'                                                                => 'jpeg',
								'image/pjpeg'                                                               => 'jpeg',
								'application/x-javascript'                                                  => 'js',
								'application/json'                                                          => 'json',
								'text/json'                                                                 => 'json',
								'application/vnd.google-earth.kml+xml'                                      => 'kml',
								'application/vnd.google-earth.kmz'                                          => 'kmz',
								'text/x-log'                                                                => 'log',
								'audio/x-m4a'                                                               => 'm4a',
								'audio/mp4'                                                                 => 'm4a',
								'application/vnd.mpegurl'                                                   => 'm4u',
								'audio/midi'                                                                => 'mid',
								'application/vnd.mif'                                                       => 'mif',
								'video/quicktime'                                                           => 'mov',
								'video/x-sgi-movie'                                                         => 'movie',
								'audio/mpeg'                                                                => 'mp3',
								'audio/mpg'                                                                 => 'mp3',
								'audio/mpeg3'                                                               => 'mp3',
								'audio/mp3'                                                                 => 'mp3',
								'video/mp4'                                                                 => 'mp4',
								'video/mpeg'                                                                => 'mpeg',
								'application/oda'                                                           => 'oda',
								'audio/ogg'                                                                 => 'ogg',
								'video/ogg'                                                                 => 'ogg',
								'application/ogg'                                                           => 'ogg',
								'font/otf'                                                                  => 'otf',
								'application/x-pkcs10'                                                      => 'p10',
								'application/pkcs10'                                                        => 'p10',
								'application/x-pkcs12'                                                      => 'p12',
								'application/x-pkcs7-signature'                                             => 'p7a',
								'application/pkcs7-mime'                                                    => 'p7c',
								'application/x-pkcs7-mime'                                                  => 'p7c',
								'application/x-pkcs7-certreqresp'                                           => 'p7r',
								'application/pkcs7-signature'                                               => 'p7s',
								'application/pdf'                                                           => 'pdf',
								'application/octet-stream'                                                  => 'pdf',
								'application/x-x509-user-cert'                                              => 'pem',
								'application/x-pem-file'                                                    => 'pem',
								'application/pgp'                                                           => 'pgp',
								'application/x-httpd-php'                                                   => 'php',
								'application/php'                                                           => 'php',
								'application/x-php'                                                         => 'php',
								'text/php'                                                                  => 'php',
								'text/x-php'                                                                => 'php',
								'application/x-httpd-php-source'                                            => 'php',
								'image/png'                                                                 => 'png',
								'image/x-png'                                                               => 'png',
								'application/powerpoint'                                                    => 'ppt',
								'application/vnd.ms-powerpoint'                                             => 'ppt',
								'application/vnd.ms-office'                                                 => 'ppt',
								'application/msword'                                                        => 'doc',
								'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
								'application/x-photoshop'                                                   => 'psd',
								'image/vnd.adobe.photoshop'                                                 => 'psd',
								'audio/x-realaudio'                                                         => 'ra',
								'audio/x-pn-realaudio'                                                      => 'ram',
								'application/x-rar'                                                         => 'rar',
								'application/rar'                                                           => 'rar',
								'application/x-rar-compressed'                                              => 'rar',
								'audio/x-pn-realaudio-plugin'                                               => 'rpm',
								'application/x-pkcs7'                                                       => 'rsa',
								'text/rtf'                                                                  => 'rtf',
								'text/richtext'                                                             => 'rtx',
								'video/vnd.rn-realvideo'                                                    => 'rv',
								'application/x-stuffit'                                                     => 'sit',
								'application/smil'                                                          => 'smil',
								'text/srt'                                                                  => 'srt',
								'image/svg+xml'                                                             => 'svg',
								'application/x-shockwave-flash'                                             => 'swf',
								'application/x-tar'                                                         => 'tar',
								'application/x-gzip-compressed'                                             => 'tgz',
								'image/tiff'                                                                => 'tiff',
								'font/ttf'                                                                  => 'ttf',
								'text/plain'                                                                => 'txt',
								'text/x-vcard'                                                              => 'vcf',
								'application/videolan'                                                      => 'vlc',
								'text/vtt'                                                                  => 'vtt',
								'audio/x-wav'                                                               => 'wav',
								'audio/wave'                                                                => 'wav',
								'audio/wav'                                                                 => 'wav',
								'application/wbxml'                                                         => 'wbxml',
								'video/webm'                                                                => 'webm',
								'image/webp'                                                                => 'webp',
								'audio/x-ms-wma'                                                            => 'wma',
								'application/wmlc'                                                          => 'wmlc',
								'video/x-ms-wmv'                                                            => 'wmv',
								'video/x-ms-asf'                                                            => 'wmv',
								'font/woff'                                                                 => 'woff',
								'font/woff2'                                                                => 'woff2',
								'application/xhtml+xml'                                                     => 'xhtml',
								'application/excel'                                                         => 'xl',
								'application/msexcel'                                                       => 'xls',
								'application/x-msexcel'                                                     => 'xls',
								'application/x-ms-excel'                                                    => 'xls',
								'application/x-excel'                                                       => 'xls',
								'application/x-dos_ms_excel'                                                => 'xls',
								'application/xls'                                                           => 'xls',
								'application/x-xls'                                                         => 'xls',
								'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'         => 'xlsx',
								'application/vnd.ms-excel'                                                  => 'xlsx',
								'application/xml'                                                           => 'xml',
								'text/xml'                                                                  => 'xml',
								'text/xsl'                                                                  => 'xsl',
								'application/xspf+xml'                                                      => 'xspf',
								'application/x-compress'                                                    => 'z',
								'application/x-zip'                                                         => 'zip',
								'application/zip'                                                           => 'zip',
								'application/x-zip-compressed'                                              => 'zip',
								'application/s-compressed'                                                  => 'zip',
								'multipart/x-zip'                                                           => 'zip',
								'text/x-scriptzsh'                                                          => 'zsh',
							];

							$oldname = $data['upload_data']['file_name'];

							if(isset($mime_map[$data['upload_data']['file_type']] )) {
								$fileName = $mime_map[$data['upload_data']['file_type']];
								$fileName = $data['upload_data']['file_name']."_".time().$chatbotId . "." .$fileName;
							} else {
								$mime = $data['upload_data']['file_type'];    
								$fileName = substr($mime, strpos($mime, "/") + 1);    
								$fileName = $data['upload_data']['file_name']."_".time().$chatbotId  . "." .$fileName;
							}
							
							rename("/var/www/html/api/admin/uploads/".$oldname, "/var/www/html/api/admin/uploads/".$fileName);


							$data['upload_data']['file_url'] = 'https://api.fogatabot.com/api/admin/uploads/' . $fileName;
							$file = strtolower($fileName);
						}


			

					/*	if(strpos($file, "jpg")  || strpos($file, "png") || strpos($file, "jpeg") || strpos($file, "gif")) {
							$type = 10;
						} else {
							$type = 11;
						}*/

						$return = $this->Md_bot->putImageuser($data['upload_data']['file_url'], $chatbotId, $fogataTo, $user, $type, $usr_dev, $account[0]['id']);
						$this->set_response(['status' => TRUE, 'codigo' => $type, 'message' => 'Upload successfull', 'data' => $data['upload_data']['file_url']], REST_Controller::HTTP_OK);
				}
			}

		}

	public function live_get() {

//      jQuery.get( "https://fogatacrm.com/chatbot/chat.php?user="+chatbotId+"&to="+fogataTo+"&type="+fogataTypeSearch+"&auth="+fogataAuthKey, function( data ) {
			$user = $this->get("user");
			$to = $this->get("to");
			$type = $this->get("type");
			$auth = $this->get("auth");
			$liveMsgID = $this->get("liveMsgID");

			if( isset($user) && isset($to) && isset($type) && isset($auth) ) {
				
				$account = $this->Md_bot->getUser($auth);

				if ( isset($account[0]) ) {

					if ($this->get("type") == 8) $return = $this->Md_optimus->getChats($this->get("user"), $this->get("to"), $this->get("type"), $liveMsgID);
					if ($this->get("type") == 7) $return = $this->Md_optimus->getChatsGroup($this->get("user"), $this->get("to"), $this->get("type"), $liveMsgID);
	
					/*if($return) {
						$data['bot'] = $return[0]['bot'];
						$return2 = $this->Md_bot->putLive($return, $account[0]['id']);
	
						if(!empty($return2)) {
							foreach ($return2 as $value) {
								$name = $this->Md_bot->getUsername($value['user_id']);
								$data['mensaje'] .=  '<div style="width:100%;float:left;">';
								$data['mensaje'] .= '<div class="fogata-bot-response">'.base64_decode($value['message']).'</div>';
								$data['mensaje'] .= '</div>';
								if($name[0]['name'] != '') {
									$data['mensaje'] .=  '<div style="width:100%;float:left;">';
									$data['mensaje'] .= '<div style="font-size: 9px"><b>Agent: </b>'.$name[0]['name'].'</div>';
									$data['mensaje'] .= '</div>';
								}
	
							}
						}
					}*/
	
					//$data = json_encode($data);
	
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Messages', 'data' => $return], REST_Controller::HTTP_OK);
	
				} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);
		
			} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'datos incompletos', 'data' => array()], REST_Controller::HTTP_OK);


	}

	public function live_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$device = $cleanPost['usr_dev'];

			$data = [];
			$data['mensaje'] = '';
			$data['bot'] = '';

			if ( isset($account[0]) ) {

				$return = $this->Md_bot->getLive($account[0]['id'], $ip, $device);

				if($return) {
					$data['bot'] = $return[0]['bot'];
					$return2 = $this->Md_bot->putLive($return, $account[0]['id']);

					if(!empty($return2)) {
						foreach ($return2 as $value) {
							$name = $this->Md_bot->getUsername($value['user_id']);
							$data['mensaje'] .=  '<div style="width:100%;float:left;">';
							$data['mensaje'] .= '<div class="fogata-bot-response">'.base64_decode($value['message']).'</div>';
							$data['mensaje'] .= '</div>';
							if($name[0]['name'] != '') {
								$data['mensaje'] .=  '<div style="width:100%;float:left;">';
								$data['mensaje'] .= '<div style="font-size: 9px"><b>Agent: </b>'.$name[0]['name'].'</div>';
								$data['mensaje'] .= '</div>';
							}

						}
					}
				}

				$data = json_encode($data);

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);
	}

	public function user_post() {


			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$name = $cleanPost['name'];
			$email = $cleanPost['email'];
			$phone = $cleanPost['phone'];
			$device = $cleanPost['usr_dev'];

			if ( isset($account[0]) ) {

				$return = $this->Md_bot->putUser($account[0]['id'], $ip, $name, $email, $phone, $device);

				if($return)

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $return], REST_Controller::HTTP_OK);

				else

				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $return], REST_Controller::HTTP_OK);

			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => '', 'data' => 'User not found. For more information contact us at info@fogatagroup.com.<br><br><i>Usuario no encontrado, escriba a info@fogatagroup.com si cree que no debería ver este mensaje.</i>'], REST_Controller::HTTP_OK);
	}

	public function newchat_post() {

			$post = $this->post();
			$cleanPost = $this->security->xss_clean($post);

			$account = $this->Md_bot->getUser($cleanPost['auth']);
			$ip = $cleanPost['user'];
			$word = $cleanPost['msg'];
			$type = $cleanPost['type'];
			$key = $cleanPost['bots_key_id'];
			$device = $cleanPost['usr_dev'];
			$chatbotId = $cleanPost['chatbotId'];
			$to = $cleanPost['fogataTo'];
			$msg = FALSE;
			$data = [];
			$data['mensaje'] = '';
			$data['botones'] = '';
			$data['buttons'] = array();
			$keyEncId = $cleanPost['keyenc_id'];
			$keyId = $cleanPost['keyenc'];
			$cleanPost['channel'] = 1;

			$entry = $type;

			if($to == 0 || $to == 1) {
				$ticket = $this->Md_optsupport->getKeys($cleanPost);
				$entry = 1;
			}

			function getEncodeUrl($text) {
				$retu =  base64_decode($text);
				$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
						return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
				return $replace;
			}

			function getEncodeUrl2($text) {
				$retu =  $text;
				$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
				$replace = preg_replace_callback($url, function($matches) {
						if( strlen($matches[0]) > 20 ) {
							$urlTxt = substr($matches[0], 0, 20).'...';
						} else {
							$urlTxt = $matches[0];
						}
						return '<b><a href="'.$matches[0].'" target="_blank" title="'.$matches[0].'">'.$urlTxt.'</a></b>';
				}, $retu);
				return $replace;
			}

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



			if ( isset($account[0]) && !empty($word)) {

				$chatUser = $this->Md_optsupport->getChatuser($to);
				$chatSender = $this->Md_optsupport->getChatuser($chatbotId);
				$botUser = $this->Md_optsupport->getBotuser($chatbotId);
				
				if(isset($botUser['device'])) $device = $botUser['device'];
		
				if(isset($chatUser['token_firebase']) && !empty($chatUser['token_firebase'])){
					$this->Md_optsupport->firebaseOptimus($chatSender['name'], $word, $chatUser['token_firebase']);
				}

				$cycles = $this->Md_bot->getCycle($ip, $device, $account[0]['id']);
				//aki
				$typeA = 0;
				if($cycles){
					//error_log( 'llega mierda ' . $type);
					$respuesta = $this->Md_bot->getEncResp( $cycles );
					//$respuestaID = $this->Md_bot->getEncRespId( $keyID );
					$data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
					//$msg = $respuestaID[0]['button'];
					$buttons = $this->Md_bot->getBotonesEnc( $cycles );
					foreach ($buttons as $btn) {
						$data['botones'] .= '<div data-id="'.$respuesta[0]['id'].'" class="fogata-encuesta-callback">'.$btn['button'].'</div>';
						$data['buttons'][] = $btn['button'];
					};

					$this->Md_bot->putMsgWeb($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA, $chatbotId, $to);

					$data = json_encode($data);
					$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);

				} else {

				$keys = $this->Md_bot->getKeys($account[0]['id']);

				if ($entry == 1 && count($keys) > 0) {

							$mensaje = strtolower($word);
							$mensaje = urldecode($mensaje);
							$mensaje = normaliza($mensaje);
							$this->Md_bot->putMsgWeb($ip, $msg, 8, $account[0]['id'], 0, 0, $device, $word, $typeA, $chatbotId, $to);
							//$hilos = json_decode($keys);

							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'] ]['mail_alert']= $value['mail_alert'];
								$chk[ $value['id'] ] = strtolower($value['key']);
								//echo normaliza(strtolower($value->key)).'  //  ';
							}

							$found = FALSE;
							$count = 0;

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

								$esta = max(array_column($hooman, 'msg'));
								$key = array_search($esta, array_column($hooman, 'msg'));
								$msg = $hooman[$key]['text'];
								$key = $hooman[$key]['key'];

								$typeA = $exp[$key]['key'];

								$data['mensaje'] = getEncodeUrl($exp[$key]['mensaje']);

								if($data['mensaje'] !="") {
									$this->Md_bot->putMsgWeb($ip, $data['mensaje'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $data['mensaje'], $typeA, $to, $chatbotId);
								}

								if(	$exp[$key]['key'] == 2  ){

									$buttons = $this->Md_bot->getBotones($key);

									foreach ($buttons as $btn) {
										$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
										$data['buttons'][] = $btn['button'];
										$this->Md_bot->putMsgWebChat($ip, $btn['button'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $btn['button'], $typeA, $to, $chatbotId);
									};

								} else if(	$exp[$key]['key'] == 3 ){

									$image = $this->Md_bot->getImage($key);

									foreach ($image as $img) {
										$data['mensaje'] .= '</br><a href="https://fogatabot.com'.$img['key_url'].'" target="_blank"><img src="https://fogatabot.com'.$img['key_url'].'" width="100%"></a>';
										$this->Md_bot->putImageuser('https://fogatabot.com'.$img['key_url'], $chatbotId, $to, $ip, 8, $device, $account[0]['id']);
									};

								} else if( $exp[$key]['key'] == 4 ){

									$buttons = $this->Md_bot->getEncuestas($key);

									foreach ($buttons as $btn) {
										 $data['botones'] .= '<div data-id="'.$btn['bots_keys_id'].'" data-key="'.$btn['id'].'" class="encuesta-response fogata-encuesta-response">'.$btn['button'].'</div>';
										 $data['buttons'][] = $btn['button'];
										 $this->Md_bot->putMsgWebChat($ip, $btn['button'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $btn['button'], $typeA, $to, $chatbotId);
									};

								} else if( $exp[$key]['key'] == 5 ){

									$combos = $this->Md_bot->getCombos($key);

									$galWidth = count($combos);
									$galWidth = 224 * $galWidth;

									$data['mensaje'] .= '<div class="fogata-gallery">';
									$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																					<i class="fas fa-chevron-right"></i>
																				</div>
																			 </div>';

									$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

									foreach ($combos as $combo) {

										$this->Md_bot->putMsgWeb($ip, $combo['title'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $combo['title'], $typeA, $to, $chatbotId);
										$this->Md_bot->putMsgWeb($ip, $combo['image_url'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $combo['image_url'], $typeA, $to, $chatbotId);
										$this->Md_bot->putImageuser('https://fogatabot.com'.$combo['key_url'], $chatbotId, $to, $ip, 8, $device, $account[0]['id']);

										$data['mensaje'] .= '<div class="fogata-tile">';
										$data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_url'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_url'].'" width="100%"></a>';
										$data['mensaje'] .= '<p style="margin: 2px 0 1px"><b>'.$combo['title'].'</b></p>';
										if($combo['subtitle'] != '')
										$data['mensaje'] .= '<p style="margin: 1px 0 2px">'.$combo['subtitle'].'</p>';
										$data['mensaje'] .= '<a href="'.$combo['image_url'].'" target="_blank"><div class="bot-button fogata-bot-button">'.$combo['button'].'</div></a>';
										$data['mensaje'] .= '</div>';
									};

									$data['mensaje'] .= '</div>';
									$data['mensaje'] .= '</div>';

								} else if( $exp[$key]['key'] == 6 ){

										$combos = $this->Md_bot->getCombots($key);


										$galWidth = count($combos);
										$galWidth = 224 * $galWidth;

										$data['mensaje'] .= '<div class="fogata-gallery">';
										$data['mensaje'] .= '<div class="fogata-controls">
																				<div class="fogata-left-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-left"></i>
																				</div>
																				<div class="fogata-right-control" data-id="'.$key.'">
																						<i class="fas fa-chevron-right"></i>
																				</div>
																				</div>';

										$data['mensaje'] .= '<div style="width: '.$galWidth.'px" class="fogata-scroll fogata-scroll-'.$key.'">';

										foreach ($combos as $combo) {

											$this->Md_bot->putMsgWeb($ip, $combo['button'], 8, $account[0]['id'], $keyId, $keyEncId, $device, $combo['button'], $typeA, $to, $chatbotId);
											$this->Md_bot->putImageuser('https://fogatabot.com'.$combo['key_image'], $chatbotId, $to, $ip, 8, $device, $account[0]['id']);

												$data['mensaje'] .= '<div class="fogata-tile">';
												$data['mensaje'] .= '<a href="https://fogatabot.com'.$combo['key_image'].'" target="_blank"><img style="margin-top: 15px;" src="https://fogatabot.com'.$combo['key_image'].'" width="100%"></a>';
												$data['mensaje'] .= '<div class="bot-button fogata-option-button">'.$combo['button'].'</div>';
												$data['mensaje'] .= '</div>';
										};

										$data['mensaje'] .= '</div>';
										$data['mensaje'] .= '</div>';

								} else if(strlen($exp[$key]['mensaje']) <= 7 && $exp[$key]['key'] == 1){

									$data['mensaje'] = '<h2 style="color:#fff">'.$exp[$key]['mensaje'].'</h2>';

								} else if(strlen($exp[$key]['mensaje']) <= 9 && $exp[$key]['key'] == 1){

									$data['mensaje'] = '<h3 style="color:#fff">'.$exp[$key]['mensaje'].'</h3>';

								};
								if($exp[$key]['mail_alert'] == 1) {
									$this->Md_bot->putAlerts($account[0]['id'], $ip, $device);
								}
							} else {
								$mensajes = $this->Md_bot->getMensajes($account[0]['id']);

								if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
									$data['mensaje'] = $mensajes[0]['notfound'];
								} else {
									$data['mensaje'] = '';
								}
							}



			} else if ($type == 4) {
				$this->Md_bot->putMsgWeb($ip, $msg, 7, $account[0]['id'], 0, 0, $device, $word, $typeA, $chatbotId, $to);
			} else if ($type == 5) {
				$this->Md_bot->putMsgWeb($ip, $msg, 8, $account[0]['id'], 0, 0, $device, $word, $typeA, $chatbotId, $to);
			} else if ($type == 2) {
				$respuesta = $this->Md_bot->getEncResp( $key );
				$respuestaID = $this->Md_bot->getEncRespId( $keyEncId );
				$data['mensaje'] =  getEncodeUrl2( $respuesta[0]['text'] );
				$msg = $respuestaID[0]['button'];
				$buttons = $this->Md_bot->getBotonesEnc($key);
				foreach ($buttons as $btn) {
					$data['botones'] .= '<div class="option-button fogata-option-button">'.$btn['button'].'</div>';
					$data['buttons'][] = $btn['button'];
				};
				$this->Md_bot->putMsgWeb($ip, $msg, 3, $account[0]['id'], $keyId, $keyEncId, $device, $word, $typeA, $chatbotId, $to);
			} else {
				$mensajes = $this->Md_bot->getMensajes($account[0]['id']);

				if( isset( $mensajes[0]['notfound'] ) && $mensajes[0]['notfound'] != '' ) {
					$data['mensaje'] = $mensajes[0]['notfound'];
				} else {
					$data['mensaje'] = '';
				}
			}


			

			$data = json_encode($data);

			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => '', 'data' => $data], REST_Controller::HTTP_OK);
		}
	} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'User not found or empty message', 'data' => array()], REST_Controller::HTTP_OK);

	}


}
