<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       wpguppy-buddpress
 * @since      1.0.0
 *
 * @package    WPGuppy_BuddyPress
 * @subpackage Wpguppy_Buddpress/includes
 */
if(!function_exists('buddypress')){
	return;
}

/**
 * The core plugin class.
 *
 * This is used to integrate WPGuppy plugin with buddypress.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    WPGuppy_BuddyPress
 * @subpackage Wpguppy_Buddpress/includes
 * @author     wp-guppy <wpguppy@gmail.com>
 */

if(!class_exists('WPGuppy_BuddyPress')){

	class WPGuppy_BuddyPress{

		/**
		 * database object
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private $guppyModel;

		/**
		 * rest api object
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private $restApiObj;
		
		public function __construct() {
			add_action( 'groups_created_group', 			array($this, 'updateGuppyGroup'), 10, 2);
			add_action( 'groups_details_updated', 			array($this, 'updateGuppyGroup'), 10, 3);
			add_action( 'groups_avatar_uploaded', 			array($this, 'updateGuppyGroup'), 10,3);
			add_action( 'groups_accept_invite', 			array($this, 'BPInviteAccepted'), 10, 3 );
			add_action( 'groups_membership_accepted', 		array($this, 'BPMembershipAccepted'), 10, 3 );
			add_action( 'groups_join_group', 				array($this, 'BPJoinedGroup'), 10, 2 );
			add_action( 'groups_leave_group', 				array($this, 'BPleaveGuppyGroup'), 10, 3 );
			add_action( 'groups_member_after_save', 		array($this, 'BPafterMemberSave'));
			add_action( 'groups_member_after_remove', 		array($this, 'BPafterMemberdelete'));
			add_action( 'groups_delete_group', 				array($this, 'BPGroupDelete'), 10, 1);
			$guppyModel 	= WPGuppy_Model::instance();
			$restApiObj 	= WPGuppy_RESTAPI::instance('wp-guppy', WPGUPPY_VERSION);
			$this->restApiObj = $restApiObj;
			$this->guppyModel = $guppyModel;
		}

		/**
		 * Create/Update Group in WPGuppy
		 *
		 * @since 1.0.0
		 *
		 * @param int $groupId ID of the group to delete.
		 * @return bool True on success, false on failure.
		 */
		public function updateGuppyGroup( $bpgroupId = 0, $group = false, $members = array()){
			
			if (!empty( $bpgroupId)) {
				$where 				= "bp_group_status = 1 AND bp_group_id =".$bpgroupId; 
				$fetchResults 		= $this->guppyModel->getData('id','wpguppy_group', $where );
				$messages 			= array();
				global $current_user;
				$loginedUser 	= !empty($current_user->ID) ? $current_user->ID : 0;
				if(empty($fetchResults)){
					// create guppy group
					$groupdata = array(
						'group_title' 			=> !empty($group->name) ? $group->name : '',
						'group_description' 	=> !empty($group->description) ? $group->description : '',
						'disable_reply' 		=> 0,
						'bp_group_id' 			=> $bpgroupId,
						'bp_group_status' 		=> 1,
						'group_created_date'	=> date('Y-m-d H:i:s'),
					);
					$guppyGroupId = $this->guppyModel->insertData('wpguppy_group', $groupdata);
					
					// add member in guppy group
					$memberData = array();
					$memberData['group_id']			= $guppyGroupId;		
					$memberData['member_id']		= !empty($group->creator_id) ? $group->creator_id : 0;		
					$memberData['group_role']		= 1;	// for creator of group
					$memberData['member_status']	= 1;		
					$memberData['group_status']		= 1;
					$memberData['member_added_date'] = date('Y-m-d H:i:s');
					$this->guppyModel->insertData('wpguppy_group_member',$memberData);
					
					// add message to guppy message table
					$messageData 			= array();
					$messageSentTime 		= date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s")));
					$timestamp 				= strtotime($messageSentTime);
					$message 				= array('type' => 1);
					$senderId 				= $group->creator_id;
					$messageData['sender_id'] 			= !empty($group->creator_id) ? $group->creator_id : 0; 
					$messageData['user_type'] 			= 1; 
					$messageData['group_id'] 			= $guppyGroupId; 
					$messageData['chat_type'] 			= 2; 
					$messageData['message_type'] 		= 4;
					$messageData['timestamp'] 			= $timestamp; 
					$messageData['message_sent_time'] 	= $messageSentTime; 
					$messageData['message'] 			= serialize($message); 
					$this->guppyModel->insertData('wpguppy_message', $messageData);
				}else{
					
					$group 			= groups_get_group( $bpgroupId );
					$guppyGroupId 	= $fetchResults[0]['id'];
					$groupdata = array(
						'group_title' 			=> !empty($group->name) ? $group->name : '',
						'group_description' 	=> !empty($group->description) ? $group->description : '',
						'group_updated_date'	=> date('Y-m-d H:i:s'),
					);
					$this->guppyModel->updateData( 'wpguppy_group', $groupdata, array('id' => $guppyGroupId));

					// add message to guppy message table
					$messageData 			= array();
					$messageSentTime 		= date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s")));
					$timestamp 				= strtotime($messageSentTime);
					$senderId 				= $loginedUser;
					$message 				= array('type' => 6);
					$messageData['sender_id'] 			= $loginedUser; 
					$messageData['user_type'] 			= 1; 
					$messageData['group_id'] 			= $guppyGroupId; 
					$messageData['chat_type'] 			= 2; 
					$messageData['message_type'] 		= 4;
					$messageData['timestamp'] 			= $timestamp; 
					$messageData['message_sent_time'] 	= $messageSentTime; 
					$messageData['message'] 			= serialize($message); 
					$this->guppyModel->insertData('wpguppy_message', $messageData);
				}
				
				$messages[] = $message;
				$params = array(
					'guppyGroupId' 	=> $guppyGroupId,
					'bpgroupId' 	=> $bpgroupId,
					'timestamp' 	=> $timestamp,
					'senderId' 		=> $senderId,
					'messages' 		=> $messages,
				);
				
				$this->restApiObj->sendPusherGroupData($params);	
			}
		}

		/**
		 * Fires after a accept invite of a buddypress group
		 *
		 * @since 1.0.0
		 * @param int             $groupId ID of the group.
		 * @param int             $userId  ID of the user joining the group.
		 * @param int             $inviterId  ID of the inviter.
		*/
		public function BPInviteAccepted($userId = 0, $bpGroupId = 0, $inviterId = 0){
			$this->updateGuppyGroupMember($userId, $bpGroupId, $inviterId);
		}

		/**
		 * Fires after a user membership accepted buddypress group.
		 *
		 * @since 1.0.0
		 * @param int             $groupId ID of the group.
		 * @param int             $userId  ID of the user joining the group.
		 * @param boolean          $accept.
		 */
		public function BPMembershipAccepted($userId = 0, $bpGroupId = 0, $accept = false){
			if($accept){
				global $current_user;
				$loginedUser 	= !empty($current_user->ID) ? $current_user->ID : 0;
				$this->updateGuppyGroupMember($userId, $bpGroupId, $loginedUser);
			}
		}

		/**
		 * Fires after a user joins a buddypress group.
		 *
		 * @since 1.0.0
		 * @param int             $groupId ID of the group.
		 * @param int             $userId  ID of the user joining the group.
		 */
		public function BPJoinedGroup($bpGroupId = 0, $userId = 0 ){
			$this->updateGuppyGroupMember($userId, $bpGroupId, $userId, true);
		}

		/**
		 * update wpguppy group member
		 *
		 * @since 1.0.0
		 * @param int             $groupId ID of the group.
		 * @param int             $userId  ID of the user joining the group.
		 * @param int             $inviterId  ID of the inviter.
		 * @param boolean          $joinGroup.
		 * @param boolean          $removeGroup.
		 * @param boolean          $leaveGroup.
		 */
		public function updateGuppyGroupMember( $userId = 0, $bpgroupId = 0, $inviterId = 0, $joinGroup = false, $removeGroup = false, $leaveGroup = false ){
			if ( empty( $bpgroupId ) || empty( $userId ) ) {
				return false;
			}
			$where 				= "bp_group_status = 1 AND bp_group_id =".$bpgroupId; 
			$fetchResults 		= $this->guppyModel->getData('id','wpguppy_group', $where );
			if(!empty($fetchResults)){
				$message 		= false;
				$where 		 	= "group_id=". $fetchResults[0]['id']."  AND member_id=".$userId; 
				$userinfo 		= $this->guppyModel->getData('*','wpguppy_group_member',$where );
				if(empty($userinfo)){
					// add member in guppy group
					$memberData = array();
					$memberData['group_id']			= $fetchResults[0]['id'];		
					$memberData['member_id']		= $userId;		
					$memberData['group_role']		= 0;
					$memberData['member_status']	= 1;		
					$memberData['group_status']		= 1;
					$memberData['member_added_date'] = date('Y-m-d H:i:s');
					$this->guppyModel->insertData('wpguppy_group_member', $memberData);
					$message = true;
				}elseif($removeGroup){
					$where 		 	= "group_id=".$fetchResults[0]['id']." AND member_status='1'  AND member_id=".$userId; 
					$verifyInfo 	= $this->guppyModel->getData('id','wpguppy_group_member',$where );
					if(!empty($verifyInfo)){
						$this->guppyModel->updateData( 'wpguppy_group_member', array('member_status'=> 2), array('id' => $verifyInfo[0]['id']));
						// insert chat action
						$actionTime = date('Y-m-d H:i:s');
						$data = array();
						$data['corresponding_id']		= $fetchResults[0]['id'];		
						$data['chat_type']				= 2;		
						$data['action_by']				= $inviterId;
						$data['action_type']			= 4;
						$data['action_time']			= $actionTime;
						$data['action_updated_time']	= $actionTime;
						$this->guppyModel->insertData('wpguppy_chat_action', $data);
						$message = true;
					}	
				}elseif($leaveGroup){
					$where 		 	= "group_id=".$fetchResults[0]['id']." AND member_status='1' AND group_status = '1' AND member_id=".$userId; 
					$verifyInfo 	= $this->guppyModel->getData('id','wpguppy_group_member',$where );
					if(!empty($verifyInfo)){
						$this->guppyModel->updateData( 'wpguppy_group_member', array('member_status'=> 0, 'group_role'=> 0), array('id' => $verifyInfo[0]['id']));
						// insert chat action
						$actionTime = date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s")));
						$data['corresponding_id']		= $fetchResults[0]['id'];		
						$data['chat_type']				= 2;		
						$data['action_by']				= $userId;
						$data['action_type']			= 3;
						$data['action_time']			= $actionTime;
						$data['action_updated_time']	= $actionTime;
						$this->guppyModel->insertData('wpguppy_chat_action', $data);
						$message = true;
					}	
				}else{
					$actionType = '0';
					if($userinfo[0]['group_status'] == '0'){
						$actionType = '5';
						$update_col = 'action_updated_time';
					}elseif($userinfo[0]['member_status'] == '0'){
						$actionType = '3';
						$update_col = 'action_updated_time';
					}elseif($userinfo[0]['member_status'] == '2'){
						$actionType = '4';
						$update_col = 'action_updated_time';
					}
					$where 		 	= "corresponding_id=". $fetchResults[0]['id']." AND chat_type = '2' AND action_type= '".$actionType."' AND action_by='".$userId."' ORDER BY id desc limit 1"; 
					$chatAction 	= $this->guppyModel->getData('id','wpguppy_chat_action',$where );
					if(!empty($chatAction)){ 
						$this->guppyModel->updateData( 'wpguppy_chat_action', array($update_col => date('Y-m-d H:i:s')), array('id' => $chatAction[0]['id']));	
					}
					$this->guppyModel->updateData( 'wpguppy_group_member', array('group_role' => 0, 'member_status'=> 1 , 'group_status' => 1), array('id' => $userinfo[0]['id']));
					$message = true;
				}
				// add message to guppy message table
				if($message){
					$removedIds = $membersUpdate = array();
					$messageData 			= array();
					$messageSentTime 		= date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s")));
					$timestamp 				= strtotime($messageSentTime);
					
					$message = array('type' => 2, 'memberIds' => array($userId));
					if($joinGroup){
						$message 	= array('type' => 7, 'memberIds' => array($userId));
					}elseif($removeGroup){
						$message 	= array('type' => 3, 'memberIds' => array($userId));
						$removedIds[] = $userId;
					}elseif($leaveGroup){
						$message 	= array('type' => 4, 'memberIds' => array($userId));
					}
					$messageData['sender_id'] 			= $inviterId; 
					$messageData['user_type'] 			= 1; 
					$messageData['group_id'] 			= $fetchResults[0]['id']; 
					$messageData['chat_type'] 			= 2; 
					$messageData['message_type'] 		= 4;
					$messageData['timestamp'] 			= $timestamp; 
					$messageData['message_sent_time'] 	= $messageSentTime; 
					$messageData['message'] 			= serialize($message); 
					$this->guppyModel->insertData('wpguppy_message', $messageData);

					$memberData 				= $this->guppyModel->getUserInfo('1', $userId);
					$memberName 				= $memberData['userName'];
					$membersUpdate[$userId] 	= $memberName;
					$message['membersUpdate']	= $membersUpdate;
					$params = array(
						'guppyGroupId' 	=> $fetchResults[0]['id'],
						'bpgroupId' 	=> $bpgroupId,
						'removedIds' 	=> $removedIds,
						'leaveGroup' 	=> $leaveGroup,
						'timestamp' 	=> $timestamp,
						'senderId' 		=> $inviterId,
						'messages' 		=> array($message),
					);
					$this->restApiObj->sendPusherGroupData($params);
				}
			}
		}

		/**
		 * Fires after a user leave buddypress group.
		 *
		 * @since 1.0.0
		 * @param int             $groupId ID of the group.
		 * @param int             $userId  ID of the user joining the group.
		 */
		public function BPleaveGuppyGroup( $groupId = 0, $userId = 0,  $group = false ){
			if ( empty( $groupId ) || empty( $userId ) ) {
				return false;
			}
			$this->updateGuppyGroupMember($userId, $groupId, $userId, false, false, true);
		}

		/**
		 * Fires after status update of a buddypress group user.
		 *
		 * @since 1.0.0
		 * @param array    $memberData of the member.
		 */
		public function BPafterMemberSave( $memberData = false, $id = 0){
			if ( empty( $memberData ) ) {
				return false;
			}
			global $current_user;
			$loginedUser 			= !empty($current_user->ID) ? $current_user->ID : 0;
			$where 					= "bp_group_status = 1 AND bp_group_id =".$memberData->group_id; 
			$fetchResults 			= $this->guppyModel->getData('id','wpguppy_group', $where );
			if(!empty($fetchResults)){
				if(!empty($memberData->is_banned) && $memberData->is_banned === 1){
					$this->updateGuppyGroupMember($memberData->user_id, $memberData->group_id, $loginedUser, false, true);
				}elseif(isset($memberData->is_banned) && $memberData->is_banned === 0){
					$where 		 	= "group_id=".$fetchResults[0]['id']." AND (member_status='0' OR member_status='2') AND member_id=".$memberData->user_id; 
					$verifyInfo 	= $this->guppyModel->getData('id','wpguppy_group_member',$where );
					if(!empty($verifyInfo)){
						$this->updateGuppyGroupMember($memberData->user_id, $memberData->group_id, $loginedUser);
					}
				}
			}
		}

		/**
		 * Fires after delete a buddypress group member.
		 *
		 * @since 1.0.0
		 *
		 * @param array   $memberData of the member.
		 */
		public function BPafterMemberdelete( $memberData){
			if ( empty( $memberData ) ) {
				return false;
			}
			global $current_user;
			$loginedUser 	= !empty($current_user->ID) ? $current_user->ID : 0;
			$this->updateGuppyGroupMember($memberData->user_id, $memberData->group_id, $loginedUser, false, true);	
		}

		/**
		 * Delete a group and all of its associated metadata.
		 *
		 * @since 1.0.0
		 *
		 * @param int $groupId ID of the group to delete.
		 * @return bool True on success, false on failure.
		 */
		public function BPGroupDelete( $bpgroupId = 0){
			if ( empty( $bpgroupId ) ) {
				return false;
			}
			$where 					= "bp_group_status = 1 AND bp_group_id =".$bpgroupId; 
			$fetchResults 			= $this->guppyModel->getData('id','wpguppy_group', $where );
			if(!empty($fetchResults)){
				$this->guppyModel->updateData( 'wpguppy_group', array('bp_group_status'=> 0), array('id' => $fetchResults[0]['id']));
				global $current_user;
				$loginedUser 	= !empty($current_user->ID) ? $current_user->ID : 0;
				$messageData 	= $messages = array();
				$messageSentTime 		= date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s")));
				$timestamp 				= strtotime($messageSentTime);
				$message = array('type' => 6);
				$messageData['sender_id'] 			= $loginedUser; 
				$messageData['user_type'] 			= 1; 
				$messageData['group_id'] 			= $fetchResults[0]['id']; 
				$messageData['chat_type'] 			= 2; 
				$messageData['message_type'] 		= 4;
				$messageData['timestamp'] 			= $timestamp; 
				$messageData['message_sent_time'] 	= $messageSentTime; 
				$messageData['message'] 			= serialize($message); 
				$this->guppyModel->insertData('wpguppy_message', $messageData);
				$messages[] = $message;
				$params = array(
					'guppyGroupId' 	=> $fetchResults[0]['id'],
					'bpgroupId' 	=> $bpgroupId,
					'timestamp' 	=> $timestamp,
					'senderId' 		=> $loginedUser,
					'messages' 		=> $messages,
				);
				$this->restApiObj->sendPusherGroupData($params);
			}
		}
	}
	new WPGuppy_BuddyPress();
}

