<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$request = file_get_contents('php://input');

if($request){
    header("HTTP/1.1 200 OK");
}

$rq = json_decode($request, true);
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $request, FILE_APPEND );

$notificationType = $rq["notificationType"];
//file_put_contents("notificacion.log",$notificationType . "\n", FILE_APPEND);
$channelOwnerId = $rq["content"]["channel"]["channelOwnerId"];
//file_put_contents("channelOwnerId.log",$channelOwnerId . "\n", FILE_APPEND);
$name = $rq["content"]["owner"]["name"];
//file_put_contents("name.log",$name . "\n", FILE_APPEND);
$email = $rq["content"]["owner"]["email"];
//file_put_contents("email.log",$email . "\n", FILE_APPEND);
$deliveredTo = $rq["content"]["messages"][0]["senderId"];
//file_put_contents("deliveredTo.log",$deliveredTo . "\n", FILE_APPEND);
$senderId = $rq["content"]["messages"][0]["deliveredTo"];
//file_put_contents("senderId.log",$senderId . "\n", FILE_APPEND);
$channel = $rq["content"]["messages"][0]["channelId"];
//$channel1 = $rq["content"]["messages"][0]["channelId"];
//file_put_contents("channel.log",$channel . "\n", FILE_APPEND);
//$ticketId = $rq["content"]["ticket"]["id"];
$ticketId = $rq["content"]["messages"][0]["senderId"];
//file_put_contents("ticketId.log",$ticketId . "\n", FILE_APPEND);
$type = $rq["content"]["messages"][0]["type"];
//file_put_contents("type.log",$type . "\n", FILE_APPEND);
$msg = $rq["content"]["messages"][0]["content"];
file_put_contents("messages.log",$msg . "\n", FILE_APPEND);
$subtype = $rq["content"]["messages"][0]["subtype"];
//file_put_contents("subtype.log",$subtype . "\n", FILE_APPEND);
$phone_number = $rq["content"]["messages"][0]["senderId"];
$from = $rq["content"]["messages"][0]["senderId"];
//file_put_contents("phone_number.log",$phone_number . "\n", FILE_APPEND);
//file_put_contents("phone_log.log",$phone_number);

if($notificationType == 'conversation.closed'){
    if(file_exists("{$ticketId}.log")){
        $chatId = file_get_contents("{$ticketId}.log");
        @unlink("{$ticketId}.log");
        @unlink("{$chatId}.csv");
    }
    exit();
}

/* Check if ticket is active */
if(file_exists("{$ticketId}.log")) 
{
   file_put_contents("log_guschat.log","llego aqui\n",FILE_APPEND);
   $chatId = file_get_contents("{$ticketId}.log");
   $mf = file_put_contents("{$chatId}.csv","{$messages},".time()."\n",FILE_APPEND);
}

$senderId = htmlspecialchars($_GET['senderId']);
$deliveredTo =  htmlspecialchars($_GET['deliveredTo']);
$ticketId = htmlspecialchars($_GET['ticketId']);
$phone_number =  htmlspecialchars($_GET['phone_number']);
$from =  htmlspecialchars($_GET['from']);
$msg = htmlspecialchars($_GET['msg']);
$name = htmlspecialchars($_GET['name']);
$subtype = htmlspecialchars($_GET['subtype']);

file_put_contents("inicio.log","llego");

$cv = file_put_contents('chatGET.log',"{$deliveredTo}\n{$senderId}\n{$ticketId}\n{$chat_id}\n", FILE_APPEND);
$url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/availability?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();

if(file_exists("{$ticketId}.log")) 
{
   file_put_contents("log_chat_inicio.log",$msg,FILE_APPEND);
   $chatId = file_get_contents("{$ticketId}.log");
   chatEvents($chatId, $msg, $subtype, $first_name, $last_name);
   exit;
}
$nt = file_put_contents("{$ticketId}.log",'new');

$options = array(
        CURLOPT_URL            => $url,
        CURLOPT_HEADER         => true,   
        CURLOPT_RETURNTRANSFER => true,
		CURLOPT_SSL_VERIFYHOST => false,    // for https
        CURLOPT_SSL_VERIFYPEER => false,    // for https 
        CURLOPT_POST           => false,
		CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
); // Arreglo de la conexión para autenticación digest

$ch = curl_init();

curl_setopt_array( $ch, $options );

try {
	$raw_response  = curl_exec( $ch );
	file_put_contents('log_disponible.log',$raw_response,FILE_APPEND);
	// validar CURL status
	//1if(curl_errno($ch))
		//1throw new Exception(curl_error($ch), 500);
	// validar HTTP status code (respuestas de user/password)
	//1$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	//1if ($status_code != 200)
		//1throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);

} catch(Exception $ex) {
    //1if ($ch != null) curl_close($ch);
    //1throw new Exception($ex);
}
        $result = array( 'header' => '', 
                         'body' => '', 
                         'curl_error' => '', 
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            //echo $result;
        }
        
        $header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($raw_response, 0, $header_size);
        $result['body'] = substr( $raw_response, $header_size );
        $result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
        $json = json_decode($result['body'], true);
        if($json['chat'] == 'available')
		{
			if ($ch != null) curl_close($ch);
			
			/* REQUEST CHAT */
			$url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();

			$postData = array( 
				'phone_number'=> $phone_number, 
				'from'=> $from,
				'ticket' =>$ticketId,
				'parameters'=>array('first_name'=>$name)
			  );

			$jsonDataEncoded =  utf8_encode(json_encode($postData, JSON_UNESCAPED_SLASHES));

			$options = array(
					CURLOPT_URL            => $url,
					CURLOPT_HEADER         => true,   
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_SSL_VERIFYHOST => false,    // for https
					CURLOPT_SSL_VERIFYPEER => false,    // for https 
					CURLOPT_POST           => true,
					CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
					CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
			); // Arreglo de la conexión para autenticación digest

			$ch = curl_init();

			curl_setopt_array( $ch, $options );

			try {
				$raw_response  = curl_exec( $ch );
				file_put_contents("log_chat.log",$raw_response, FILE_APPEND);
				// validar CURL status
				//1if(curl_errno($ch))
					//1throw new Exception(curl_error($ch), 500);

				// validar HTTP status code (respuestas de user/password)
				//1$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				//1if ($status_code != 200)
				//throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);

			} catch(Exception $ex) {
				//1if ($ch != null) curl_close($ch);
				//1throw new Exception($ex);
			}
				$result = array( 'header' => '', 
								 'body' => '', 
								 'curl_error' => '', 
								 'http_code' => '',
								 'last_url' => '');
				if ( $error != "" )
				{
					$result['curl_error'] = $error;
					//echo $result;
				}
					
				$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
				$result['header'] = substr($raw_response, 0, $header_size);
				$result['body'] = substr( $raw_response, $header_size );
				$result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
				$result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
				$json = json_decode($result['body'], true);
				$chat_id = $json['chat_id'];
				file_put_contents("{$ticketId}.log", $chat_id);
				
				getEvents($chat_id, $senderId, $deliveredTo, $ticketId);
				if ($ch != null) curl_close($ch);
			/* END REQUEST CHAT */
			
			/* SEND INITIAL MESSAGE TO AGENT */
			$url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats/' .$chat_id .'/events?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();
			$postData["events"] = array(array("event"=>"chat_session_message", "msg"=>$msg, "msg_id"=>$chat_id.':1'));
			$jsonDataEncoded =  utf8_encode(json_encode($postData, JSON_UNESCAPED_SLASHES));
			$options = array(
				CURLOPT_URL            => $url,
				CURLOPT_HEADER         => true,   
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_SSL_VERIFYHOST => false,    // for https
				CURLOPT_SSL_VERIFYPEER => false,    // for https 
				CURLOPT_POST           => true,
				CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
				CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
			); // Arreglo de la conexión para autenticación digest

			$ci = curl_init();
			curl_setopt_array( $ci, $options );

			try {
				$raw_response  = curl_exec( $ci );
				file_put_contents('log_inicia.log',  $jsonDataEncoded . "-" . $raw_response, FILE_APPEND);
				// validar CURL status
				//1if(curl_errno($ci))
					//1throw new Exception(curl_error($ci), 200);

				// validar HTTP status code (respuestas de user/password)
				//1$status_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
				//1if ($status_code != 200)
					//1throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);

			} catch(Exception $ex) {

				//throw new Exception($ex);
			}
			//echo "raw response: " . $raw_response;
				if ($gc != null) curl_close($gc);
					$result = array( 'header' => '', 
									 'body' => '', 
									 'curl_error' => '', 
									 'http_code' => '',
									 'last_url' => '');
					if ( $error != "" )
					{
						$result['curl_error'] = $error;
						echo $result;
					}
					
					$header_size = curl_getinfo($ci,CURLINFO_HEADER_SIZE);
					$result['header'] = substr($raw_response, 0, $header_size);
					$result['body'] = substr( $raw_response, $header_size );
					$result['http_code'] = curl_getinfo($ci,CURLINFO_HTTP_CODE);
					$result['last_url'] = curl_getinfo($ci,CURLINFO_EFFECTIVE_URL);
					$json = json_decode($result['body'], true);
				if ($ci != null) curl_close($ci);
				if ($gc != null) curl_close($gc);
			/* END SEND INITIAL MESSAGE TO AGENT */
		
			//if ($ch != null) curl_close($ch);
		//pollEvents($chat_id, $senderId, $deliveredTo, $ticketId);
		}
		if ($ch != null) curl_close($ch);
		pollEvents($chat_id, $senderId, $deliveredTo, $ticketId);
		
function getEvents($chat_id, $senderId, $deliveredTo, $ticketId)
{
    file_put_contents("log_acceso.log","Llego a la funcion get events");
	/* GUSCHAT PARAMS */
    $username = "neufeld@a5111f7c-cde2-4bf4-9204-68ba0b7164eb";
    $password = "JlJzADXPOU88KcxmX17NCpKcFRLkXmisWtLHLu2NvlRUQHkbDqxST47gzBcUPa5PtfQKzTaEODvaAcuz8ZMovTwwkUk6Dpyzfb3buztqyGuAJ64kgKKIFFoh09T1MPPt";
    $gcurl = "https://glip.gus.chat/channels-api/v1/conversation";
    
    /* events array */
    $eventsArray = array();
    
    /* events array end */
    $url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats/' .$chat_id .'/events?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();
    $options = array(
            CURLOPT_URL            => $url,
            CURLOPT_HEADER         => true,   
            CURLOPT_RETURNTRANSFER => true,
    		CURLOPT_SSL_VERIFYHOST => false,    // for https
            CURLOPT_SSL_VERIFYPEER => false,    // for https 
            CURLOPT_POST           => false, 
    		CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
    ); // Arreglo de la conexión para autenticación digest
    
    $ch = curl_init();
    curl_setopt_array( $ch, $options );
    
    try {
    	$raw_response  = curl_exec( $ch );
		file_put_contents("logGetEvents.log",$raw_response,FILE_APPEND);
    	// validar CURL status
    	//1if(curl_errno($ch))
    		//1throw new Exception(curl_error($ch), 500);
    
    	// validar HTTP status code (respuestas de user/password)
    	//1$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    	//!if ($status_code != 200)
    		//1throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);
    
    } catch(Exception $ex) {
        //1throw new Exception($ex);
    }
    
            $result = array( 'header' => '', 
                             'body' => '', 
                             'curl_error' => '', 
                             'http_code' => '',
                             'last_url' => '');
            if ( $error != "" )
            {
                $result['curl_error'] = $error;
                echo $result;
            }
            
            $header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
            $result['header'] = substr($raw_response, 0, $header_size);
            $result['body'] = substr( $raw_response, $header_size );
            $result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
            $result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
            $json = json_decode($result['body'], true);
 
    $ef = file_put_contents('getEvents.log', $result['body'],FILE_APPEND);
    if ($ch != null) curl_close($ch);
    
    $eventsArray = json_decode($result['body'], true);
    
    foreach($eventsArray as $events){
        foreach($events as $event){
            $ev = file_put_contents('eventType.log',"[" . date('Y-m-d H:i:s') ."] " . $event['event'] . "\n", FILE_APPEND);
            /* GUSCHAT */
            if($event['event'] == 'chat_session_message'){
                $response = array("content"=>str_replace("</br>","\n",str_replace("&nbsp;"," ",$event['msg'])),
				"senderId"=>$senderId,
                "deliveredTo"=>$deliveredTo,
                "subtype"=>"TEXT"
                );
                $customRequest = 'PUT';

                $jsonDataEncoded = utf8_encode(json_encode($response, JSON_UNESCAPED_SLASHES));
                $pfp = file_put_contents( 'payload.log', $jsonDataEncoded,FILE_APPEND );
                
                $options = array(
                        CURLOPT_URL            => $gcurl,
                        CURLOPT_HEADER         => true,   
                        CURLOPT_RETURNTRANSFER => true,
                		CURLOPT_SSL_VERIFYHOST => false,    // for https
                        CURLOPT_SSL_VERIFYPEER => false,    // for https 
                        CURLOPT_USERPWD        => $username . ":" . $password,
                		CURLOPT_HTTPAUTH	   => CURLAUTH_BASIC,
                		CURLOPT_CUSTOMREQUEST  => 'PUT',
                        CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
                		CURLOPT_HTTPHEADER	   => array('Content-Type: application/json; charset=utf-8')
                ); // Arreglo de la conexión para autenticación digest
                
                $gc = curl_init();
                
                curl_setopt_array( $gc, $options );
                
                try {
                	$raw_response  = curl_exec( $gc );
                file_put_contents( 'gcivr.log', $raw_response,FILE_APPEND );
                
                	// validar CURL status
                	//1if(curl_errno($gc))
                		//1throw new Exception(curl_error($gc), 500);
                
                	// validar HTTP status code (respuestas de user/password)
                	//1$status_code = curl_getinfo($gc, CURLINFO_HTTP_CODE);
                	//1if ($status_code != 200) 
                		//1throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);
                
                } catch(Exception $ex) {
                    //1if ($gc != null) curl_close($gc);
                    //1throw new Exception($ex);
                }
                if ($gc != null) curl_close($gc);
            }
            
            if($event['msg'] == 'Sorry there are no representatives available to serve you at this time. Please try later. #ct' || $event['msg'] == 'Lo sentimos, por el momento todos nuestros agentes se encuentran ocupados, por favor intente nuevamente mas tarde.'){
                sleep(5);
                $customRequest = 'DELETE';
                $response = array("senderId"=>$deliveredTo, "ticketId"=>$ticketId);
                sendEventLib($response, $customRequest);
                unlink("{$ticketId}.log");
                unlink("{$chat_id}.csv");
            }
    
        }
}

 return null;
}

function sendEventLib($response, $customRequest)
{
    
    /* GUSCHAT PARAMS */
    $username = "neufeld@a5111f7c-cde2-4bf4-9204-68ba0b7164eb";
    $password = "JlJzADXPOU88KcxmX17NCpKcFRLkXmisWtLHLu2NvlRUQHkbDqxST47gzBcUPa5PtfQKzTaEODvaAcuz8ZMovTwwkUk6Dpyzfb3buztqyGuAJ64kgKKIFFoh09T1MPPt";
    
    $gcurl = "https://glip.gus.chat/channels-api/v1/conversation";
    
    $jsonDataEncoded = utf8_encode(json_encode($response, JSON_UNESCAPED_SLASHES));
    $options = array(
            CURLOPT_URL            => $gcurl,
            CURLOPT_HEADER         => true,   
            CURLOPT_RETURNTRANSFER => true,
    		CURLOPT_SSL_VERIFYHOST => false,    // for https
            CURLOPT_SSL_VERIFYPEER => false,    // for https 
            CURLOPT_USERPWD        => $username . ":" . $password,
    		CURLOPT_HTTPAUTH	   => CURLAUTH_BASIC,
    		CURLOPT_CUSTOMREQUEST  => $customRequest,
            CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
    		CURLOPT_HTTPHEADER	   => array('Content-Type: application/json; charset=utf-8')
    ); // Arreglo de la conexión para autenticación digest
    
    $gc = curl_init();
    
    curl_setopt_array( $gc, $options );
    
    try {
    	$raw_response  = curl_exec( $gc );
    //	echo "raw response: " . $raw_response;
    file_put_contents( 'gcivr.log', $raw_response );
    
    	// validar CURL status
    	//1if(curl_errno($gc))
    		//1throw new Exception(curl_error($gc), 500);
    
    	// validar HTTP status code (respuestas de user/password)
    	//1$status_code = curl_getinfo($gc, CURLINFO_HTTP_CODE);
    	//1if ($status_code != 200) 
    		//1throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);
    
    } catch(Exception $ex) {
        //1if ($gc != null) curl_close($gc);
        //1throw new Exception($ex);
    }
    if ($gc != null) curl_close($gc);
    
    return null;
}
function pollEvents($chat_id, $senderId, $deliveredTo, $ticketId)
{
file_put_contents("log_pollevents.log","Llego aqui");
$username = "neufeld@a5111f7c-cde2-4bf4-9204-68ba0b7164eb";
$password = "JlJzADXPOU88KcxmX17NCpKcFRLkXmisWtLHLu2NvlRUQHkbDqxST47gzBcUPa5PtfQKzTaEODvaAcuz8ZMovTwwkUk6Dpyzfb3buztqyGuAJ64kgKKIFFoh09T1MPPt";

$gcurl = "https://glip.gus.chat/channels-api/v1/conversation";
$eventsArray = array();
$url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats/' .$chat_id .'/events?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();


$options = array(
        CURLOPT_URL            => $url,
        CURLOPT_HEADER         => true,   
        CURLOPT_RETURNTRANSFER => true,
		CURLOPT_SSL_VERIFYHOST => false,    // for https
        CURLOPT_SSL_VERIFYPEER => false,    // for https 
        CURLOPT_POST           => false, 
		CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
); // Arreglo de la conexión para autenticación digest

$ch = curl_init();

curl_setopt_array( $ch, $options );

try {
	$raw_response  = curl_exec( $ch );
	file_put_contents('log4.log',$raw_response,FILE_APPEND);
	//1if(curl_errno($ch))
		//1throw new Exception(curl_error($ch), 500);
	//1$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	//1if ($status_code != 200)
		//throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);

} catch(Exception $ex) {
    //1throw new Exception($ex);
}

        $result = array( 'header' => '', 
                         'body' => '', 
                         'curl_error' => '', 
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            echo $result;
        }
        
        $header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($raw_response, 0, $header_size);
        $result['body'] = substr( $raw_response, $header_size );
        $result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
        $json = json_decode($result['body'], true);
//        $chat_id = $json['chat_id'];
        
    $ef = file_put_contents('pollEvents.log', $result['body'],FILE_APPEND);
            
    if ($ch != null) curl_close($ch);
    
    $eventsArray = json_decode($result['body'], true);
    
    foreach($eventsArray as $events){
        foreach($events as $event){
            $ev = file_put_contents('eventType.log',"[" . date('Y-m-d H:i:s') ."] " . $event['event'] . "\n", FILE_APPEND);
    

            switch($event['event']){ 
                case 'chat_session_message':
                    $response = array("content"=> str_replace("&nbsp;"," ",str_replace("<br>","\n",$event['msg'])),
                    "senderId"=>$senderId,
                    "deliveredTo"=>$deliveredTo,
                    "subtype"=>"TEXT"
                    );
                    $customRequest = 'PUT';
                    sendEventPoll($response, $customRequest);
                    break;
                case 'chat_session_timeout_warning':
                    $response = array("content"=>"La sesión está a punto de terminar por inactividad. Envíe un mensaje para mantenerla activa.",
                    "senderId"=>$senderId,
                    "deliveredTo"=>$deliveredTo,
                    "subtype"=>"TEXT"
                    );
                    $customRequest = 'PUT';
                    sendEventPoll($response, $customRequest);
                    break;
                case 'chat_session_file':
                    $url = "https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1/chats/" . $chat_id . "/files/" . $event['file_id'] . "";
					$narchivo = substr($url,112,66);
					$tarjet = $narchivo . ".jpg";
					file_put_contents("imagen.log", $tarjet, FILE_APPEND);
                    descargarImagen($url, $tarjet, 'img/');
					$url2= "http://wsdebcio.zw-callitonce.alestra.net.mx/img/" . $tarjet . "";
					file_put_contents("urlimagen.log",$url2 . "\n",FILE_APPEND);
					$response = array("content"=>$url2,
                    "senderId"=>$senderId,
                    "deliveredTo"=>$deliveredTo,
                    "subtype"=>"TEXT"
                    );  
                    $customRequest = 'PUT';
                    sendEventPollimg($response, $customRequest);
                    break;
                case 'chat_session_party_joined':
                    $response = array("content"=>"Está conectado con " . $event['display_name'],
                    "senderId"=>$senderId,
                    "deliveredTo"=>$deliveredTo,
                    "subtype"=>"TEXT"
                    );
                    $customRequest = 'PUT';
                    sendEventPoll($response, $customRequest);
                    break;
                case 'chat_session_inactivity_timeout':
                case 'chat_session_ended':
               // case 'chat_session_party_left':
                    $response = array("content"=>"Su sesión ha terminado. Para iniciar una nueva sesión, envíe un mensaje",
                    "senderId"=>$senderId,
                    "deliveredTo"=>$deliveredTo,
                    "subtype"=>"TEXT"
                    );
                    $customRequest = 'PUT'; 
                    sendEventPoll($response, $customRequest);
                    sleep(5);
                    $customRequest = 'DELETE';
                    $response = array("senderId"=>$deliveredTo, "ticketId"=>$ticketId);
                    sendEventPoll($response, $customRequest);
                    $ticketFile = dirname(__FILE__) . "/{$ticketId}.log";
                    $chatFile = dirname(__FILE__) . "/{$chat_id}.csv";
                    chmod($ticketFile, 777);
                    chmod($chatFile, 777);
                    @unlink($ticketFile);
                    @unlink($chatFile);
                    exit;
                    break;
            }
                
    
        }
    }
    sleep(5);
    pollEvents($chat_id, $senderId, $deliveredTo, $ticketId);

}	

function sendEventPollimg($response, $customRequest){
    
    /* GUSCHAT PARAMS */
    $username = "neufeld@a5111f7c-cde2-4bf4-9204-68ba0b7164eb";
    $password = "JlJzADXPOU88KcxmX17NCpKcFRLkXmisWtLHLu2NvlRUQHkbDqxST47gzBcUPa5PtfQKzTaEODvaAcuz8ZMovTwwkUk6Dpyzfb3buztqyGuAJ64kgKKIFFoh09T1MPPt";
    
    $gcurl = "https://glip.gus.chat/channels-api/v1/conversation";
    
    $jsonDataEncoded = utf8_encode(json_encode($response, JSON_UNESCAPED_SLASHES));
	file_put_contents( 'payloadimg.log', $jsonDataEncoded );
    
    $options = array(
            CURLOPT_URL            => $gcurl,
            CURLOPT_HEADER         => true,   
            CURLOPT_RETURNTRANSFER => true,
    		CURLOPT_SSL_VERIFYHOST => false,    // for https
            CURLOPT_SSL_VERIFYPEER => false,    // for https 
            CURLOPT_USERPWD        => $username . ":" . $password,
    		CURLOPT_HTTPAUTH	   => CURLAUTH_BASIC,
    		CURLOPT_CUSTOMREQUEST  => $customRequest,
            CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
    		CURLOPT_HTTPHEADER	   => array('Content-Type: application/json; charset=utf-8')
    ); // Arreglo de la conexión para autenticación digest
    
    $gc = curl_init();
    
    curl_setopt_array( $gc, $options );
    
    try {
    	$raw_response  = curl_exec( $gc );
		file_put_contents("postimagen.log",$raw_response,FILE_APPEND);
    	// validar CURL status
    	//1if(curl_errno($gc))
    		//1throw new Exception(curl_error($gc), 500);
    
    	// validar HTTP status code (respuestas de user/password)
    	//!$status_code = curl_getinfo($gc, CURLINFO_HTTP_CODE);
    	//1if ($status_code != 200) 
    		//!throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);
    
    } catch(Exception $ex) {
        if ($gc != null) curl_close($gc);
        //1throw new Exception($ex);
    }
    if ($gc != null) curl_close($gc);
    
    return null;
}

function sendEventPoll($response, $customRequest){
    
    /* GUSCHAT PARAMS */
    $username = "neufeld@a5111f7c-cde2-4bf4-9204-68ba0b7164eb";
    $password = "JlJzADXPOU88KcxmX17NCpKcFRLkXmisWtLHLu2NvlRUQHkbDqxST47gzBcUPa5PtfQKzTaEODvaAcuz8ZMovTwwkUk6Dpyzfb3buztqyGuAJ64kgKKIFFoh09T1MPPt";
    
    $gcurl = "https://glip.gus.chat/channels-api/v1/conversation";
    
    $jsonDataEncoded = utf8_encode(json_encode($response, JSON_UNESCAPED_SLASHES));
//    $pfp = file_put_contents( 'payload.log', $jsonDataEncoded );
    
    $options = array(
            CURLOPT_URL            => $gcurl,
            CURLOPT_HEADER         => true,   
            CURLOPT_RETURNTRANSFER => true,
    		CURLOPT_SSL_VERIFYHOST => false,    // for https
            CURLOPT_SSL_VERIFYPEER => false,    // for https 
            CURLOPT_USERPWD        => $username . ":" . $password,
    		CURLOPT_HTTPAUTH	   => CURLAUTH_BASIC,
    		CURLOPT_CUSTOMREQUEST  => $customRequest,
            CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
    		CURLOPT_HTTPHEADER	   => array('Content-Type: application/json; charset=utf-8')
    ); // Arreglo de la conexión para autenticación digest
    
    $gc = curl_init();
    
    curl_setopt_array( $gc, $options );
    
    try {
    	$raw_response  = curl_exec( $gc );
		file_put_contents("postENVIO.log",$raw_response,FILE_APPEND);
    	// validar CURL status
    	//1if(curl_errno($gc))
    		//1throw new Exception(curl_error($gc), 500);
    
    	// validar HTTP status code (respuestas de user/password)
    	//!$status_code = curl_getinfo($gc, CURLINFO_HTTP_CODE);
    	//1if ($status_code != 200) 
    		//!throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);
    
    } catch(Exception $ex) {
        if ($gc != null) curl_close($gc);
        //1throw new Exception($ex);
    }
    if ($gc != null) curl_close($gc);
    
    return null;
}


function chatEvents($chat_id, $msg, $subtype, $first_name, $last_name){
    
//$url = 'https://brightpattern.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats/' .$chat_id .'/events?tenantUrl=' . 'brightpattern.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();
$url = 'https://neufeld.zw-callitonce.alestra.net.mx/clientweb/api/v1' . '/chats/' .$chat_id .'/events?tenantUrl=' . 'neufeld.zw-callitonce.alestra.net.mx' . '&timestamp=' . time();
//$uf = file_put_contents('events.log', $url);
//$uf = file_put_contents('subtype.log', $subtype);
//echo "{$subtype}<br />";
switch($subtype){
    case "LOCATION":
        $coordinates = explode(',', $msg);
        $latitude = $coordinates[0];
        $longitude = $coordinates[1];
        $postData["events"] = array(array("event"=>"chat_session_message", "msg"=>"https://google.com.mx/maps/search/{$latitude},{$longitude}", "msg_id"=>$chat_id.':1'));
        break;
    default:
        $postData["events"] = array(array("event"=>"chat_session_message", "msg_id"=>$chat_id.':1', "msg"=>$msg));
        break;
}

$jsonDataEncoded =  utf8_encode(json_encode($postData, JSON_UNESCAPED_SLASHES));
//echo "{$jsonDataEncoded}<br />";
echo "{$url}<br />";
$uf = file_put_contents('events.log', $jsonDataEncoded,FILE_APPEND);
$options = array(
        CURLOPT_URL            => $url,
        CURLOPT_HEADER         => true,   
        CURLOPT_RETURNTRANSFER => true,
		CURLOPT_SSL_VERIFYHOST => false,    // for https
        CURLOPT_SSL_VERIFYPEER => false,    // for https 

        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $jsonDataEncoded, 
		CURLOPT_HTTPHEADER	   => array('Authorization: MOBILE-API-140-327-PLAIN appId="' . 'e06163c91f17464ca6f14ce629055455' . '", clientId="' . 'WebChat' . '"') //27ea392ff567493796cb7e1e629fc7aa
); // Arreglo de la conexión para autenticación digest

$ci = curl_init();

curl_setopt_array( $ci, $options );

try {
	$raw_response  = curl_exec( $ci );
	file_put_contents("logChatEvent.log",$raw_response,FILE_APPEND);
	echo "raw response: " . $raw_response;

	// validar CURL status
	//1if(curl_errno($ci))
		//1throw new Exception(curl_error($ci), 500);

	// validar HTTP status code (respuestas de user/password)
	//1$status_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
	//!if ($status_code != 200)
		//!throw new Exception("Respuesta con Status Code [" . $status_code . "].", 200);

} catch(Exception $ex) {

    //throw new Exception($ex);
}

/*    if ($gc != null) curl_close($gc);
        $result = array( 'header' => '', 
                         'body' => '', 
                         'curl_error' => '', 
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            echo $result;
        }
        
        $header_size = curl_getinfo($ci,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($raw_response, 0, $header_size);
        $result['body'] = substr( $raw_response, $header_size );
        $result['http_code'] = curl_getinfo($ci,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($ci,CURLINFO_EFFECTIVE_URL);
        $json = json_decode($result['body'], true);*/

    if ($ci != null) curl_close($ci);
    $tf = file_put_contents('mensaje_enviado.log', "{$msg} ". time() . "\n", FILE_APPEND);
    return null;
}
function descargarImagen($urlImagen, $target, $directorioBase)
{
    file_put_contents('datos_url.log',$urlImagen);
	$curl = curl_init();
$headers = array(
    'Content-Type: application/x-www-form-urlencoded',
    'Authorization:  MOBILE-API-140-327-PLAIN appId="b157e128a1f84e0d873dcb0a27b06737", clientId="WebChat"'
);

curl_setopt_array($curl, array(
CURLOPT_URL => $urlImagen,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => $headers,
  CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5'
));
$imagen = curl_exec($curl);

    curl_close($curl);
    file_put_contents('imagenes1.log',$imagen);
	$archivo = @fopen($directorioBase.$target, 'w');
    if($archivo)
    {
        file_put_contents('validaciones.log','La imagen '.$urlImagen.' ha sido descargada a '.'http://52.20.38.249/img/'.$target . "\n", FILE_APPEND);
        @fwrite($archivo, $imagen);
        @fclose($archivo);
    }else{
        file_put_contents('validaciones.log','La imagen '.$urlImagen.' no se ha sido podido descargar'.'http://52.20.38.249/img/'.$target . "\n", FILE_APPEND);
    }
}

