<?php
// Set proper content type
header('Content-Type: text/html');
// Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');
define( 'SHORTINIT', false );
$path = preg_replace( '/wp-content.*$/' , '', __DIR__ );
require $path.'wp-load.php';
$guppySetting = get_option('wpguppy_settings');
$secretKey = $appId = $publicKey = $appCluster = '';
if(!empty($guppySetting) && !empty($guppySetting['option']['app_secret'])){
	$secretKey 		= !empty($guppySetting['option']['app_secret']) 	? $guppySetting['option']['app_secret'] : '';
	$appId 			= !empty($guppySetting['option']['app_id'])			? $guppySetting['option']['app_id'] : '';
	$publicKey 		= !empty($guppySetting['option']['app_key'])		? $guppySetting['option']['app_key']	: '';
	$appCluster 	= !empty($guppySetting['option']['app_cluster'])	? $guppySetting['option']['app_cluster'] : '';
}
require_once('libraries/pusher/vendor/autoload.php');
require_once('includes/class-wp-guppy-model.php');
$guppyModel = WPGuppy_Model::instance();

$app_key = $_SERVER['HTTP_X_PUSHER_KEY'];
$webhook_signature = $_SERVER ['HTTP_X_PUSHER_SIGNATURE'];

$body = file_get_contents('php://input');

$expected_signature = hash_hmac( 'sha256', $body, $secretKey, false );

if($webhook_signature == $expected_signature) {

	$options = array(
		'useTLS'    => false,
		'cluster'   => $appCluster
	);
	$pusher = new Pusher\Pusher($publicKey, $secretKey, $appId, $options);
	
	$logged_in_users = get_transient('wpguppy_online_status'); 
	$logged_in_users = !empty($logged_in_users) ? $logged_in_users : array();
	$batchRequests = array();
	// decode as associative array
	$payload = json_decode( $body, true );
	foreach($payload['events'] as &$event) {
		$onlineFriendslist = array();
		$userId = $event['user_id'];
		$where = "(send_by=".$userId." OR send_to=".$userId.") AND friend_status=1";
		$friendDetails		= $guppyModel->getdata('send_by,send_to', 'wpguppy_friend_list', $where);
		if(!empty($friendDetails)){
			if($event['name'] == 'member_added'){
				$userAvatar 	= $guppyModel->getUserInfoData('avatar', $userId, array('width' => 150, 'height' => 150));
				$userName 		= $guppyModel->getUserInfoData('username', $userId, array());
				$where 		 	= "user_id=". $userId; 
				$userinfo 		= $guppyModel->getData('user_name,user_image','wpguppy_users',$where );
				if(!empty($userinfo)){
					$info 					= $userinfo[0];
					$userName 			= $info['user_name'];
					if(!empty($info['user_image'])){
						$userImage 			= unserialize($info['user_image']);
						$userAvatar 		= $userImage['attachments'][0]['thumbnail'];
					}
				}
				if($userName != ''){
					$lastname = '';
					$name =	explode(' ' , $userName);
					if(!empty($name[1])){
						$lastname = ' '. ucfirst(substr($name[1], 0, 1));
					}
					$userName = ucfirst($name[0]) . $lastname; 
				}
			}
			foreach($friendDetails as $single){
				if($single['send_by'] == $userId){
					$friendId = intval( $single['send_to'] );
				}else{
					$friendId = intval( $single['send_by'] );
				}
				
				if(isset($logged_in_users[$friendId]['last']) 
					&& $logged_in_users[$friendId]['last'] > time() - 900){
					if($event['name'] == 'member_added'){
						$where 					= "action_by=".$friendId." AND corresponding_id=".$userId." AND chat_type=1 AND action_type=2";
						$muteNotification		= $guppyModel->getdata('id', 'wpguppy_chat_action', $where);

						if(!empty($muteNotification)){
							$muteNotification = true;
						}else{
							$muteNotification = false;
						}
						$chatkey = $friendId . '_1';
						$userFriendList = array(
							'muteNotification' 	=> $muteNotification,
							'chatType'			=> 1,
							'isOnline'			=> true,
							'isBlocked'			=> false,
							'blockedId'			=> false,
							'chatId' 			=> $userId . '_1',
							'userName' 			=> $userName,
							'userAvatar' 		=> $userAvatar,
						);
						$batchRequests[] = array(
							'channel' 	=> 'presence-user-' . $friendId,
							'name' 		=> 'updateOnlineStatus',
							'data'		=> (Object)$userFriendList,
						);
					}elseif($event['name'] == 'member_removed'){
						$batchRequests[] = array(
							'channel' 	=> 'presence-user-' . $friendId,
							'name' 		=> 'userOffline',
							'data'		=> $userId,
						);
					}	
					
				}
			}

			if(!empty($onlineFriendslist)){
				$batchRequests[] = array(
					'channel' 	=> 'presence-user-' . $userId,
					'name' 		=> 'updateUserOnlineFriends',
					'data'		=> (Object)$onlineFriendslist,
				);
			}
			
		}
	}
	if(!empty($batchRequests)){
		$pusher->triggerBatch($batchRequests);
	}
	header("Status: 200 OK");
}else {
	header("Status: 401 Not authenticated");
}