<?php
require_once(WPGuppy_GlobalSettings::get_plugin_path().'libraries/jwt/vendor/autoload.php');
/** Requiere the JWT library. */
use Firebase\JWT\JWT;
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wp-guppy.com
 * @since      1.0.0
 *
 * @package    wp-guppy
 * @subpackage wp-guppy/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    wp-guppy
 * @subpackage wp-guppy/admin
 * @author     wp-guppy <wpguppy@gmail.com>
 */
class WPGuppy_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * The rest api url
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $restapiurl   admin rest api url
	 */

	private $restapiurl = 'admin-guppy';


	/**
	 * The restapiversion
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $restapiversion    rest api version
	*/
	private $restapiversion = 'v2';


	/**
	 * private key for jwt.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $secretKey   secret key for jwt.
	 */
	private $secretKey;

	/**
	 * database object
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of the plugin.
	 */
	private $guppyModel;

	/**
	 * Show Record By Default
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of the plugin.
	 */

	private $showRec;
	
	/**
	 * Guppy Setting
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of the plugin.
	 */

	private $guppySetting;

	/**
	 * Initialize Singleton
	 *
	 * @var [void]
	 */

	private static $_instance = null;

	/**
	 * Call this method to get singleton
	 *
	 * @return wp-guppy Instance
	 */
	public static function instance($plugin_name, $version){
		if (self::$_instance === null) {
			self::$_instance = new WPGuppy_Admin($plugin_name, $version);
		}
		return self::$_instance;
	}

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name  = $plugin_name;
		$this->version 		= $version;
		$this->secretKey 		= '&EH-n;xy)LjN%]tx4DH*_vv^9J~?6*Zi/_YXKxTU4qwN_SkQ8F[q|du@/J}';

		$guppyModel = WPGuppy_Model::instance();
		$this->guppyModel = $guppyModel;
		global $guppySetting;
		$this->guppySetting = $guppySetting;
		$this->showRec 		= !empty($this->guppySetting['showRec']) ? $this->guppySetting['showRec'] : 20;

		add_action('rest_api_init', function() {

			register_rest_route($this->restapiurl.'/'.$this->restapiversion , 'load-guppy-messages-list' , array(
				'methods'    			=>  WP_REST_Server::READABLE,
				'callback'   			=> array(&$this, 'getUserMessageslist'),
				'args' 					=> array(),
				'permission_callback' 	=> '__return_true', 
			));

			register_rest_route($this->restapiurl.'/'.$this->restapiversion , 'load-guppy-chat' , array(
				'methods'    			=>  WP_REST_Server::READABLE,
				'callback'   			=> array(&$this, 'getGuppyChat'),
				'args' 					=> array(),
				'permission_callback' 	=> '__return_true', 
			));

			register_rest_route($this->restapiurl.'/'.$this->restapiversion , 'delete-guppy-conversation-messages' , array(
				'methods'    			=>  WP_REST_Server::EDITABLE,
				'callback'   			=> array(&$this, 'deleteGuppyConversationMessages'),
				'args' 					=> array(),
				'permission_callback' 	=> '__return_true', 
			));

			register_rest_route($this->restapiurl.'/'.$this->restapiversion , 'delete-guppy-conversation' , array(
				'methods'    			=>  WP_REST_Server::EDITABLE,
				'callback'   			=> array(&$this, 'deleteGuppyConversation'),
				'args' 					=> array(),
				'permission_callback' 	=> '__return_true', 
			));
		});
		
	}
	
	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in WPGuppy_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The WPGuppy_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_enqueue_style('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css',array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name.'-guppy-icons', WPGuppy_GlobalSettings::get_plugin_url(). 'public/css/guppy-icons.css', array(), $this->version, 'all' );
		wp_enqueue_style('wpguppy-app', WPGuppy_GlobalSettings::get_plugin_url().'chatapp/dist/css/app.css',array(), $this->version, 'all');
		wp_enqueue_style('wpguppy-vendors', WPGuppy_GlobalSettings::get_plugin_url().'chatapp/dist/css/vendors.css',array(), $this->version, 'all');
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_style( 'wpguppy-settings', plugin_dir_url( __FILE__ ) . 'css/wpguppy-admin.css',array(), $this->version, 'all');
		wp_enqueue_style( 'jquery-confirm', plugin_dir_url( __FILE__ ) . 'css/jquery-confirm.min.css',array(), $this->version, 'all');
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in WPGuppy_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The WPGuppy_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		
		
		wp_enqueue_script('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), $this->version, true);
		wp_enqueue_script('sortable', 'https://raw.githack.com/SortableJS/Sortable/master/Sortable.min.js', array('jquery'), $this->version, true);

		wp_enqueue_script('wpguppy-settings', plugin_dir_url( __FILE__ ) . 'settings/js/settings.js',array( 'wp-color-picker' ), $this->version, true);
		wp_enqueue_script('jquery-confirm', plugin_dir_url( __FILE__ ) . 'settings/js/jquery-confirm.min.js',array( 'wp-color-picker' ), $this->version, true);

		wp_enqueue_script('wpguppy-app', WPGuppy_GlobalSettings::get_plugin_url().'chatapp/dist/js/app.js', array(), $this->version, true);
		wp_enqueue_script('wpguppy-vendors', WPGuppy_GlobalSettings::get_plugin_url().'chatapp/dist/js/vendors.js', array(), $this->version, true);

		global $current_user;
		$loginedUser 			= !empty($current_user->ID) ?$current_user->ID : 0;
		$token  				= $this->getGuppyAuthToken($loginedUser);
		$authToken				= $token['authToken'];
		$primaryColor 			= !empty($this->guppySetting['primary_color']) 		? $this->guppySetting['primary_color'] 		: '#FF7300';
		$secondaryColor 		= !empty($this->guppySetting['secondary_color']) 	? $this->guppySetting['secondary_color'] 	: '#0A0F26';
		$textColor 				= !empty($this->guppySetting['text_color']) 		? $this->guppySetting['text_color'] 		: '#000000';
		$translations 			= !empty($this->guppySetting['translations']) 		? $this->guppySetting['translations'] 		: array();
		$floatingIcon 			= !empty($this->guppySetting['dock_layout_image']) 	? $this->guppySetting['dock_layout_image'] 	: '';
		$timeFormat 			= !empty($this->guppySetting['time_format']) 		&& $this->guppySetting['time_format'] == '24hrs' 	? '24hrs' 	: '12hrs';

		$default_translations 	= wp_list_pluck(apply_filters( 'wpguppy_default_text','' ), 'default');
		
		$adminTranslations = array(
			'gallery_close_btn',
			'gallery_previous_btn',
			'gallery_next_btn',
			'error_title',
			'input_params_err',
			'no_results',
			'start_conversation',
			'search_results',
			'group_users_txt',
			'detail_txt',
			'owner_txt',
			'admin_txt',
			'load_more',
			'media',
			'no_attachments',
			'voice_note',
			'deleted_message',
			'group_chat_header_txt',
			'search',
			'private_chat_header_txt',
			'you_txt',
			'grp_sent_attachment',
			'you_sent_attachment',
			'you_sent_location',
			'grp_sent_location',
			'you_sent_voice_note',
			'sent_you_location',
			'sent_you_attachment',
			'sent_you_voice_note',
			'you',
			'post_chat_header_txt',
			'private_tooltip_txt',
			'group_tooltip_txt',
			'post_tooltip_txt',
			'admin_start_conversation',
			'msg_sent_time_txt',
			'add_grp_member_txt',
			'group_created_notify',
			'group_updated_notify',
			'updt_grp_role',
			'join_grp_member_txt',
			'remove_grp_member_txt',
			'grp_other_membert_txt',
			'leave_grp_member_txt',
			'auto_inv_sender_msg',
			'auto_inv_receiver_msg',
			'more_text',
			'select_all_chats_txt',
			'cancel_txt',
			'delete_select_txt',
			'select_all_conv_txt',
			'are_you_sure',
			'delet_grp_member_btn',
			'not_right_now',
			'am_time_txt',
			'pm_time_txt',
			'today_time_txt',
			'yesterday_time_txt',
			'sunday',
			'monday',
			'tuesday',
			'wednesday',
			'thursday',
			'friday',
			'saturday',
			'january',
			'february',
			'march',
			'april',
			'may',
			'june',
			'july',
			'august',
			'september',
			'october',
			'november',
			'december',
			'private_tab_txt',
			'group_tab_txt',
			'post_tab_txt',
			'customer_tab_txt',
		);
		$activeTranslations = array();
		foreach($adminTranslations as $key) {
			if( ! empty($translations[$key]) ) {
				$activeTranslations[$key] = $translations[$key];
			} elseif( ! empty($default_translations[$key]) ) {
				$activeTranslations[$key] = $default_translations[$key];
			}
		}

		$chatSetting = array(
			'timeFormat'		=> $timeFormat,
			'primaryColor' 		=> $primaryColor,	
			'secondaryColor' 	=> $secondaryColor,	
			'textColor' 		=> $textColor,
			'isRtl'				=> is_rtl(),
			'videoThumbnail'	=> WPGuppy_GlobalSettings::get_plugin_url().'public/images/video-thumbnail.jpg',
			'floatingIcon'		=> !empty($floatingIcon) ? $floatingIcon : WPGuppy_GlobalSettings::get_plugin_url().'public/images/floating-logo.gif',
			'translations'		=> $activeTranslations,
			'enabledTabs'		=> array('private', 'group', 'posts'),
			'defaultActiveTab'  => 'private',
		);
		
		wp_localize_script('wpguppy-settings', 'wpguppy_scripts_vars', array(
			'rest_db_message'	=> esc_html__('Are you sure you want to reset databse?','wp-guppy'),
			'is_admin'			=> 'no',
			'ajaxurl' 			=> admin_url('admin-ajax.php'),
			'ajax_nonce'		=> wp_create_nonce('ajax_nonce'),
			'restapiurl'    	=> get_rest_url( null, $this->restapiurl.'/'.$this->restapiversion.'/'),
			'userId'			=> $loginedUser,
			'authToken' 		=> $authToken,
			'showRec'			=> $this->showRec, 
			'chatSetting'		=> $chatSetting,
		));
	}

	/**
	 * Get guppy auth token
	 *
	 * @since    1.0.0
	*/
	public function getGuppyAuthToken($loginedUser){
		$jwt 		= array();
		$issuedAt 	= time();
		$notBefore 	= $issuedAt + 10;
		$expire 	= $issuedAt + (DAY_IN_SECONDS * 1);
		
		$token = array(
			'iss' => get_bloginfo('url'),
			'iat' => $issuedAt,
			'nbf' => $notBefore,
			'exp' => $expire,
			'data' => array(
				'user' => array(
					'id' => $loginedUser,
				),
			),
		);
		$authToken = JWT::encode($token, $this->secretKey , 'HS256');
		$jwt['authToken'] 		= $authToken;
		return $jwt;
	}

	/**
	 * Guppy admin Authentication
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_Error|WP_REST_Request
	*/

	public function guppyAuthentication($params , $authtoken){
		
		$json 		= array();
		$type 		= 'success';
		$message 	= '';
		if(empty($params['userId']) 
			|| empty(get_userdata($params['userId'])) ){
			$message   	= esc_html__('You are not allowed to perform this action!', 'wp-guppy');
			$type 		= 'error';	
		}else{
			list($token) = sscanf($authtoken, 'Bearer %s');
			if(!$token){
				$message   	= esc_html__('Authorization Token does not found!', 'wp-guppy');
				$type 		= 'error';
			}else{
				try {
					JWT::$leeway = 60;
					$token 	= JWT::decode($token, $this->secretKey, array('HS256'));
					$now 	= time();
					if ($token->iss != get_bloginfo('url') 
						|| !isset($token->data->user->id)
						|| $token->data->user->id != $params['userId']
						|| $token->exp < $now) {
						$message   	= esc_html__('You are not allowed to perform this action!', 'wp-guppy');
						$type 		= 'error';
					}else{
						$userMeta  	= get_userdata($params['userId']);	
						$userRoles 	= !empty($userMeta->roles) ? $userMeta->roles : array();
						$allowedRoles 	= array('administrator');
						if (!array_intersect( $allowedRoles, $userRoles ) ) {
							$message   	= esc_html__('You are not allowed to perform this action!', 'wp-guppy');
							$type 		= 'error';
						}
					}
					
				}catch(Exception $e){
					$message   	= $e->getMessage();
					$type 		= 'error';
				}
			}
		}
		$json['type'] 			= $type;
		$json['message_desc']   = $message; 
		return $json;
	}

	/**
	 * Get timeFormat
	 *
	 * @since    1.0.0
	*/
	public function getTimeFormat($time){
		$timeOffset 	= (float) get_option( 'gmt_offset' );
		$seconds 		= intval( $timeOffset * HOUR_IN_SECONDS );
		$timestamp 		= strtotime( $time ) + $seconds;
		$timeFormat 	= !empty($time) ?  human_time_diff( $timestamp,current_time( 'timestamp' ) ).' '.esc_html__('ago','wp-guppy') : '';
		return $timeFormat;
	}

	/**
	 * Load all user messages 
	 *
	 * @since    1.0.0
	*/
	public function getUserMessageslist($data){
		$headers    = $data->get_headers();
		$params     = ! empty($data->get_params()) 		? $data->get_params() 		: '';
		$authToken  = ! empty($headers['authorization'][0]) ? $headers['authorization'][0] : '';
		$guppyMessageList  = $json  = $postImages 	= array();
		$response = $this->guppyAuthentication($params, $authToken);
		if(!empty($response) && $response['type']=='error'){
			return new WP_REST_Response($response , 203);
		}
		$offset 		= !empty($params['offset']) ? intval($params['offset']) : 0; 
		$searchQuery 	= !empty($params['search']) ? wp_strip_all_tags($params['search']) : '';
		$loginedUser 	= !empty($params['userId']) ? intval($params['userId']) : 0;
		$chatType 		= $params['chatType'];
		$fetchResults   = $this->guppyModel->getAdminUserMessageslist($this->showRec, $offset, $searchQuery, $chatType);
		
		if(!empty($fetchResults)){
			foreach($fetchResults as $result){

				$messageData 					= array();
				$senderId 						= $result['chat_type'] == 3 	? $result['sp_sender_id']  	: $result['sender_id'];
				$receiverId 					= $result['chat_type'] == 3 	? $result['sp_rec_id']  	: $result['receiver_id']; 
				$message 						= $result['message'];
				$messageType 					= $result['message_type'];
				$timestamp 						= $result['timestamp'];
				
				if(!empty($result['post_id'])){
					if(empty($postImages) || !isset($postImages[$result['post_id']])){
						$postImage = $this->guppyModel->getPostImage($result['post_id']);
						$postImages[$result['post_id']] = $postImage;	
					}else{
						$postImage = $postImages[$result['post_id']];
					}

					$messageData['postId']			= $result['post_id'];
					$postTitle 						= has_filter('wpguppy_get_post_title') ? apply_filters('wpguppy_get_post_title',$result['post_id']) : '';
					$postTitle 						= empty( $postTitle ) ? get_the_title($result['post_id']) : $postTitle;
					$messageData['postImage']		= $postImage;
					$messageData['postTitle']		= !empty($postTitle) ? html_entity_decode( stripcslashes($postTitle), ENT_QUOTES) : '';
				}elseif(!empty($result['group_id'])){
					
					$groupDetail 	= $this->guppyModel->getGroupDetail($result['group_id']);
					$userData 		= $this->guppyModel->getUserInfo('1', $result['sender_id']);
					$messageData['senderName'] 		= $userData['userName'];
					$messageData['senderAvatar'] 	= $userData['userAvatar'];
					$messageData['groupTitle'] 		= !empty($groupDetail['groupTitle']) ? $groupDetail['groupTitle'] : '' ;
					$messageData['groupDetail']		= !empty($groupDetail) ? $groupDetail : '';	
					$memberInfo 					= !empty($groupDetail['memberAvatars']) ? $groupDetail['memberAvatars'] : '';
					$groupImage 					= !empty($groupDetail['groupImage']) 	? $groupDetail['groupImage'] 	: '';

					if(function_exists('buddypress') && bp_is_active( 'groups' ) && $groupDetail['isbpgroup']){
						$groupImage =  bp_core_fetch_avatar(
							array(
								'item_id' => $groupDetail['bpgroupId'],
								'object'  => 'group',
								'type'    => 'full',
								'width'   => bp_core_avatar_full_width(),
								'height'  => bp_core_avatar_full_height(),
								'html'    => false,
							)
						);
						
						if(empty($groupImage)){
							$groupImage = !empty($groupDetail['groupImage']) ? $groupDetail['groupImage'] : '';	
						}
					}

					$messageData['groupImage'] 		= $groupImage;

					if($messageType == '4'){
						$message = is_serialized($message) ? unserialize($message) : $message;
						$membersUpdate = array();
						if(in_array($message['type'], array('2','3','4','5','7'))){
							foreach($message['memberIds'] as $single){
								$memberName = !empty($memberInfo[$single]['userName']) ? $memberInfo[$single]['userName'] : '';
								$membersUpdate[$single] = $memberName;
							}
							$messageData['membersUpdate'] = $membersUpdate;
						}
					}
				}

				if($chatType == '0' 
					|| $chatType == '1' 
					|| $chatType == '3'
				){

					$sisRegistered 	= get_userdata($senderId);
					$risRegistered 	= get_userdata($receiverId);

					$userData 	= $this->guppyModel->getUserInfo(!empty($sisRegistered) ? 1 : 0 , $senderId);
					$messageData['senderAvatar']		= $userData['userAvatar'];	
					$messageData['senderName'] 			= $userData['userName'];

					$userData 	= $this->guppyModel->getUserInfo(!empty($risRegistered) ? 1 : 0, $receiverId);
					$messageData['receiverAvatar']		= $userData['userAvatar'];	
					$messageData['receiverName'] 		= $userData['userName'];
					
				}
				
				
				if($result['message_status'] == 2 ){
					$message = '';
				}

				$chatId = $senderId.'_'.$receiverId;
				
				if(!empty($result['group_id'])){
					$chatId = $result['group_id'];
				}
				if($message!=''){
					if($messageType == '0'){
						$message = html_entity_decode( stripslashes($message), ENT_QUOTES );
					}elseif($messageType == '2' || $messageType == '4'){
						$message = is_serialized($message) ? unserialize($message) : $message;
					}
				}

				if(!empty($result['post_id'])){
					$key = $this->guppyModel->getChatKey($result['chat_type'], $result['post_id'], $chatId);
				}else{
					$key = $this->guppyModel->getChatKey($result['chat_type'], $chatId);
				}
				
				$messageData['chatId']				= $key;
				$messageData['message'] 	   		= $message;
				$messageData['sentTime'] 			= $this->getTimeFormat($result['message_sent_time']);
				$messageData['messageType'] 		= $messageType;
				$messageData['messageStatus'] 		= $result['message_status'];
				$messageData['chatType'] 			= intval($result['chat_type']);
				$messageData['timeStamp'] 			= $timestamp;
				$messageData['messageId']			= Intval($result['id']);
				$guppyMessageList[$key] 			= $messageData;
			}
		}
		
		$json['type'] 				= 'success';
		$json['guppyMessageList']   = (Object)$guppyMessageList;
		return new WP_REST_Response($json , 200);		 
	}

	
	/**
	 * get user chat
	 *
	 * @since    1.0.0
	*/
	public  function getGuppyChat($data){
		
		$headers    	= $data->get_headers();
		$params     	= ! empty($data->get_params()) 	? $data->get_params() 		: '';
		$authToken  	= ! empty($headers['authorization'][0]) ? $headers['authorization'][0] : '';
		$chatMessages  	= $json  = $memberInfo = $filterData = array();
		
		$response = $this->guppyAuthentication($params, $authToken);
		if(!empty($response) && $response['type']=='error'){
			return new WP_REST_Response($response , 203);
		}

		$offset 		= !empty($params['offset']) 	? intval($params['offset']) 	: 0; 
		$receiverId 	= !empty($params['receiverId']) ? $params['receiverId'] : 0;
		$chatType 		= !empty($params['chatType']) 	? intval($params['chatType']) 	: 0;
		$groupId 		= !empty($params['groupId']) 	? intval($params['groupId']) 	: 0;
		$postId 		= !empty($params['postId']) 	? intval($params['postId']) 	: 0;
		$loginedUser 	= !empty($params['userId']) 	? intval($params['userId']) 	: 0;
		
		$id 	= explode('_', $receiverId);
		$filterData = array();
		$filterData['actionBy'] 	= !empty($id[0]) ? $id[0] : 0;
		$filterData['chatType'] 	= $chatType;
		$filterData['groupId'] 		= $groupId;
		$filterData['userId'] 		= !empty($id[1]) ? $id[1] : 0;
		$filterData['postId'] 		= $postId;

		if($chatType == '2' && !empty($groupId)){
			
			// get group members
			$where 			= '';
			$where 		 	= " group_id =". $groupId; 
			$groupMembers 	= $this->guppyModel->getData('member_id', 'wpguppy_group_member', $where );

			// group members info
			if(!empty($groupMembers)){
				$userName = $userAvatar = '';
				foreach($groupMembers as $member){
					$userData 	= $this->guppyModel->getUserInfo('1', $member['member_id']);
					$userAvatar = $userData['userAvatar'];
					$userName 	= $userData['userName'];
					$memberInfo[$member['member_id']] = array(
						'userName' 		=> $userName,
						'userAvatar' 	=> $userAvatar,
					);
				}
			}
		}

		// add filter for  pagination
		$filterData['limit'] 		= $this->showRec;
		$filterData['offset'] 		= $offset;
		$fetchResults = $this->guppyModel->getAdminGuppyChat($filterData);
		
		if(!empty($fetchResults)){

			$senderId 						= $fetchResults[0]['chat_type'] == 3 	? $fetchResults[0]['sp_sender_id']  : $fetchResults[0]['sender_id'];
			$receiverId 					= $fetchResults[0]['chat_type'] == 3 	? $fetchResults[0]['sp_rec_id']  	: $fetchResults[0]['receiver_id'];
			
			$sisRegistered 	= get_userdata($senderId);
			$risRegistered 	= get_userdata($receiverId);
			
			$senderUserData 	= $this->guppyModel->getUserInfo(!empty($sisRegistered) ? 1 : 0, $senderId);
			if(!empty($senderUserData)){
				$senderUserName 	= $senderUserData['userName'];
				$senderUserAvatar = $senderUserData['userAvatar'];
			}

			$recUserData 	= $this->guppyModel->getUserInfo(!empty($risRegistered) ? 1 : 0, $receiverId);
			if(!empty($recUserData)){
				$recUserName 	= $recUserData['userName'];
				$recUserAvatar = $recUserData['userAvatar'];
			}
			foreach($fetchResults as $result){

				$message =  '';
				$messageData = $attachmentsData = array();

				if($result['sender_id'] == $senderId){
					$messageData['userName']  	= $senderUserData['userName'];
					$messageData['userAvatar'] 	= $senderUserData['userAvatar'];
				}else{
					$messageData['userName']  	= $recUserName;
					$messageData['userAvatar'] 	= $recUserAvatar;
				}

				if(!empty($result['group_id']) && $result['chat_type'] == '2'){

					if(!empty($memberInfo[$result['sender_id']])){
						$messageData['userAvatar'] 	= $memberInfo[$result['sender_id']]['userAvatar'];
						$messageData['userName'] 	= $memberInfo[$result['sender_id']]['userName'];
					} else {
						$messageData['userName']  	= $memberInfo[$result['receiver_id']]['userAvatar'];
						$messageData['userAvatar'] 	= $memberInfo[$result['receiver_id']]['userName'];
						
					}
				}

				if($result['message_type'] == '0'){
					$message = html_entity_decode( stripslashes($result['message']),ENT_QUOTES );
				}elseif($result['message_type'] == '1' || $result['message_type'] == '3'){
					$attachmentsData 	= unserialize($result['attachments']);
				}elseif($result['message_type'] == '2'){
					$message = unserialize($result['message']);
				}elseif($result['message_type'] == '4'){
					$message = unserialize($result['message']);
					if($result['chat_type'] == '2' && !empty($result['group_id'])){
						$membersUpdate = array();
						if(in_array($message['type'], array('2','3','4','5','7'))){
							foreach($message['memberIds'] as $single){
								$memberName = !empty($memberInfo[$single]['userName']) ? $memberInfo[$single]['userName'] : '';
								$membersUpdate[$single] = $memberName;
							}
							$messageData['membersUpdate'] = $membersUpdate;
						}
					}	
				}

				$messageData['messageId'] 			= $result['id'];
				$messageData['senderId'] 			= $result['chat_type'] == 3 ? $result['sp_sender_id'] : $result['sender_id'];
				$messageData['message'] 			= ($result['message_status'] !='2' ? $message : false);
				$messageData['attachmentsData'] 	= $attachmentsData;
				$messageData['replyMessage'] 		= !empty($result['reply_message']) ? unserialize($result['reply_message']) : NULL;
				$messageData['chatType'] 			= $result['chat_type'];
				$messageData['messageType'] 		= $result['message_type'];
				$messageData['messageStatus'] 		= $result['message_status'];
				$messageData['timeStamp'] 			= $result['timestamp'];

				$chatMessages[] = $messageData;
			}
		}

		$mediaAttachments = array();
		
		if($offset=='0'){

			$id1 = !empty($id[0]) ? $id[0] : 0;
			$id2 = !empty($id[1]) ? $id[1] : 0;
			
			$filterData['isAdmin'] = true;
			unset($filterData['limit']);
			unset($filterData['offset']);
			$chatMedia = $this->guppyModel->getChatMedia($id1, $filterData);

			if(!empty($chatMedia)){
				foreach($chatMedia as $single){
					$counter = 1;
					$media_data = unserialize($single['attachments']);
					foreach($media_data['attachments'] as $attach){
						$mediaAttachments[] = array(
							'messageId' => $single['id'].'_'.$counter++,
							'type' 		=> $media_data['attachmentType'],
							'fileName' 	=> $attach['fileName'],
							'file' 		=> $attach['file'],
							'thumbnail' => $attach['thumbnail'],
						);
					}
				}
			}

			$where = '';
			$key = 'sender_id';
			if($chatType == '0'){
				$where = "(sender_id=$id1 AND receiver_id= $id2) OR (sender_id=$id2 AND receiver_id= $id1) AND message_type <> 4 AND user_type =1 AND post_id=$postId AND chat_type=$chatType ORDER BY id ASC LIMIT 1";
			}elseif($chatType == '1'){
				$where = " (sender_id=$id1 AND receiver_id= $id2) OR (sender_id=$id2 AND receiver_id= $id1) AND message_type <> 4 AND user_type =1 AND chat_type=$chatType ORDER BY id ASC LIMIT 1";
			}elseif($chatType == '2'){
				$where = "message_type <> 4 and user_type =1 AND chat_type=$chatType AND group_id=$groupId ORDER BY id ASC LIMIT 1";
			}elseif($chatType == '3'){
				$key = 'sp_sender_id';
				$where = " (sp_sender_id='$id1' AND sp_rec_id= '$id2') OR (sp_sender_id='$id2' AND sp_rec_id= '$id1') AND message_type <> 4 and user_type =1 AND chat_type=$chatType  ORDER BY id ASC LIMIT 1";	
			}
			$fetchResults = $this->guppyModel->getData($key, 'wpguppy_message', $where );
			if(!empty($fetchResults)){
				$json['senderId'] = $fetchResults[0][$key];
			}
		}

		if($chatType== '0'){
			$chatId = $this->guppyModel->getChatKey('0', $postId, $receiverId);
		}elseif($chatType== '1' || $chatType== '3'){
			$chatId = $this->guppyModel->getChatKey('1', $receiverId);
		}elseif($chatType== '2' && !empty($groupId)){
			$chatId = $this->guppyModel->getChatKey('2', $groupId);
		}

		$json['type'] 				= 'success';
		$json['chatId']   			= $chatId;
		$json['chatType']   		= $chatType;
		$json['chatMessages']   	= $chatMessages;
		$json['mediaAttachments']   = $mediaAttachments;
		return new WP_REST_Response($json , 200);
	}

	/**
	 * delete conversation messages by admin
	 *
	 * @since    1.0.0
	*/
	public function deleteGuppyConversationMessages($data){
		$headers    = $data->get_headers();
		$params     = ! empty($data->get_params()) 		? $data->get_params() 		: '';
		$authToken  = ! empty($headers['authorization'][0]) ? $headers['authorization'][0] : '';
		$json  = array();
		$response = $this->guppyAuthentication($params, $authToken);
		if(!empty($response) && $response['type']=='error'){
			return new WP_REST_Response($response , 203);
		}
		$loginedUser 		= !empty($params['userId']) 		? intval($params['userId']) : 0;
		$messageIds 		= !empty($params['messageIds']) 	? $params['messageIds'] 	: array();
		$userMeta  	= get_userdata($loginedUser);
		$userRoles 	= $userMeta->roles;
		$allowedRoles = array( 'administrator');
		if (array_intersect( $allowedRoles, $userRoles ) && !empty($messageIds)) {
			foreach($messageIds as $single){
				$this->guppyModel->deleteData( 'wpguppy_message', array('id' => $single));
			}
		}else{
			$json['type'] = 'error';
			$json['message_desc']   = esc_html__('You are not allowed to perform this action!', 'wp-guppy');
			return new WP_REST_Response($json , 203);
		}

		$json['type'] 		= 'success';
		return new WP_REST_Response($json , 200);
	}

	/**
	 * delete conversations by admin
	 *
	 * @since    1.0.0
	*/
	public function deleteGuppyConversation($data){
		$headers    = $data->get_headers();
		$params     = ! empty($data->get_params()) 		? $data->get_params() 		: '';
		$authToken  = ! empty($headers['authorization'][0]) ? $headers['authorization'][0] : '';
		$json  = array();
		$response = $this->guppyAuthentication($params, $authToken);
		if(!empty($response) && $response['type']=='error'){
			return new WP_REST_Response($response , 203);
		}
		$loginedUser 	= !empty($params['userId']) 	? intval($params['userId']) : 0;
		$chatIds 		= !empty($params['chatIds']) 	? $params['chatIds'] 	: array();
		
		$userMeta  	= get_userdata($loginedUser);
		$userRoles 	= $userMeta->roles;
		$allowedRoles = array( 'administrator');
		if (array_intersect( $allowedRoles, $userRoles ) && !empty($chatIds)) {
			foreach($chatIds as $single){
				$chatId = explode('_', $single);
				$chatType = end($chatId);
				if($chatType == '0'){

					$postId 	= $chatId[0];
					$senderId 	= $chatId[1];
					$receiverId = $chatId[2];

					$this->guppyModel->deleteData( 'wpguppy_message',  			array('sender_id' => $senderId, 	'receiver_id'		=> $receiverId, 'post_id'=> $postId, 'chat_type' => '0'));
					$this->guppyModel->deleteData( 'wpguppy_message',  			array('sender_id' => $receiverId, 	'receiver_id'		=> $senderId, 	'post_id'=> $postId, 'chat_type' => '0'));
					$this->guppyModel->deleteData( 'wpguppy_postchat_action',  	array('action_by' => $senderId, 	'action_to' 		=> $receiverId, 'post_id'=> $postId));
					$this->guppyModel->deleteData( 'wpguppy_postchat_action',  	array('action_by' => $receiverId, 	'action_to' 		=> $senderId, 	'post_id'=> $postId));

				}elseif($chatType == '1'){

					$senderId 	= $chatId[0];
					$receiverId = $chatId[1];

					$this->guppyModel->deleteData( 'wpguppy_message',  		array('sender_id' => $senderId, 	'receiver_id'		=> $receiverId, 'chat_type' => '1'));
					$this->guppyModel->deleteData( 'wpguppy_message',  		array('sender_id' => $receiverId, 	'receiver_id'		=> $senderId, 	'chat_type' => '1'));
					$this->guppyModel->deleteData( 'wpguppy_chat_action',  	array('action_by' => $senderId,		'corresponding_id' 	=> $receiverId, 'chat_type'=> '1'));
					$this->guppyModel->deleteData( 'wpguppy_chat_action',  	array('action_by' => $receiverId,	'corresponding_id' 	=> $senderId, 	'chat_type'=> '1'));

				}elseif($chatType == '2'){

					$groupId 	= $chatId[0];

					$this->guppyModel->deleteData( 'wpguppy_message',  		array('group_id' => $groupId, 'chat_type'=> '2'));
					$this->guppyModel->deleteData( 'wpguppy_group',  		array('id' 		=> $groupId));
					$this->guppyModel->deleteData( 'wpguppy_group_member',  array('group_id' => $groupId));
					$this->guppyModel->deleteData( 'wpguppy_chat_action',  	array('corresponding_id' => $groupId, 'chat_type'=> '2'));
				
				}elseif($chatType == '3'){

					$senderId 	= "$chatId[0]";
					$receiverId = "$chatId[1]";

					$this->guppyModel->deleteData( 'wpguppy_message',  array('sp_sender_id' => $senderId, 	'sp_rec_id'		=> $receiverId, 'chat_type' => '3'));
					$this->guppyModel->deleteData( 'wpguppy_message',  	array('sp_sender_id' => $receiverId, 'sp_rec_id'	=> $senderId, 	'chat_type' => '3'));
					
				}
			}
		}else{
			$json['type'] = 'error';
			$json['message_desc']   = esc_html__('You are not allowed to perform this action!', 'wp-guppy');
			return new WP_REST_Response($json , 203);
		}

		$json['type'] 		= 'success';
		return new WP_REST_Response($json , 200);
	}

	
}
