<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

date_default_timezone_set('UTC');

include("../data/config/config.php");
$PDO = PDO_CONNECT();

if (isset($_POST['request_id']) && $_POST['request_id'] != '' && $_POST['status'] != '') {
    $command = "UPDATE chat_requests SET u_status = :typing_status WHERE request_id = :request_id";
    $result = $PDO->prepare($command);
    $result->bindParam(':request_id', $_POST['request_id']);
    $result->bindParam(':typing_status', $_POST['status']);
    $result->execute();
}

if (isset($_POST['username']) && $_POST['username'] != '') {
	
    $encoded_data = json_decode(base64_decode($_POST['encodedGetVars']));
	$request_id = stripslashes(htmlspecialchars($_POST['request_id'], ENT_QUOTES, "utf-8"));
    $uri = stripslashes(htmlspecialchars($encoded_data->current_url, ENT_QUOTES, "utf-8"));
		
	if ($_POST['emojiFamily'] == 'twitter'){		
		$_POST['message'] = htmlspecialchars_decode($_POST['message']);
		$_POST['message'] = strip_tags($_POST['message'], '<img>');	
	    $text = stripslashes(htmlspecialchars($_POST['message'], ENT_QUOTES, "utf-8"));

	}
	else{
		$_POST['message'] = strip_tags($_POST['message'], '<img>');	
	    $text = stripslashes(htmlspecialchars($_POST['message'], ENT_QUOTES, "utf-8"));
		// Native Emoji processing
	 	$encoded_emoji = encode($text);
		$text = decode($encoded_emoji);
	}
	

    $command = "INSERT IGNORE INTO chats VALUES('', '0', '', '', '$request_id', '$text', '$uri', UTC_TIMESTAMP() )";
    $result = $PDO->prepare($command);
    $result->execute();
    echo 'posted';
}


	
function encode($text) {
	return convertEmoji($text,"ENCODE");
}
		
function decode($text) {
	return convertEmoji($text,"DECODE");
}
	
	
function convertEmoji($text,$op) {
	if($op=="ENCODE"){
		return preg_replace_callback('/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u',"encodeEmoji", $text);
	}else{
		return preg_replace_callback('/(\\\u[0-9a-f]{4})+/',"decodeEmoji" ,$text);
	}
}
	
function encodeEmoji($match) {		
	return str_replace(array('[',']','"'),'',json_encode($match));
}

function decodeEmoji($text) {
	if(!$text) return '';
		
	$text = $text[0];
	$decode = json_decode($text,true);
			
	if($decode) return $decode;

	$text = '["' . $text . '"]';
	$decode = json_decode($text);
		
	if(count($decode) == 1){
		return '<span class="emoji_span">'.$decode[0].'</span';
	}
				
	return $text;
}