<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */

include_once dirname(__FILE__) . '/models/SearchFilter.php';

class CTMobile_WS_WhatsAppList extends CTMobile_WS_Controller {
	
	function process(CTMobile_API_Request $request) {
		$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
		global $current_user, $adb, $site_URL; // Few core API assumes this variable availability
		$current_user = $this->getActiveUser();
		$currentUserID = $current_user->id;
		$licenseData = CTWhatsApp_Record_Model::getWhatsAppLicenseDetail();
        $configurationData = Settings_CTWhatsApp_Record_Model::getUserConfigurationAllDataWithId($currentUserID);
        $expirydate = Settings_CTWhatsApp_ConfigurationDetail_View::encrypt_decrypt($licenseData['expiryDate'], $action='d');
        $connectedNumberDetails = array();
        $connectedNumberDetails['authtoken'] = $configurationData['authtoken'];
        $connectedNumberDetails['whatsappstatus'] = $configurationData['whatsappstatus'];
        $connectedNumberDetails['whatsappno'] = $configurationData['whatsappno'];
        $connectedNumberDetails['api_url'] = $configurationData['api_url'];
        $connectedNumberDetails['expirydate'] = $expirydate;
        if(strtotime($expirydate) < strtotime(date('Y-m-d'))){
        	$connectedNumberDetails['license_expired'] = 1;
        }else{
        	$connectedNumberDetails['license_expired'] = 0;
        }
		$activeNumbers = $this->getActiveNumber($current_user);
		$roleid = $current_user->roleid;
		$time_zone = $current_user->time_zone;
		$module = trim($request->get('module'));
		$index = trim($request->get('index'));
		$size = trim($request->get('size'));
		$search = trim($request->get('search'));
		//$importantMessages = $request->get('importantMessages');
		$searchmodule = $request->get('searchmodule');

		$searchBy = "All";
		if($searchmodule == 'Important'){
			$searchBy = "Important";
			$importantMessages = 'Yes';
			$searchmodule = "";
		}else if($searchmodule == 'All'){
			$searchBy = "All";
			$searchmodule = "";
		}else if($search != ""){
			$searchBy = "search";
		}else if($searchmodule != ""){
			$searchBy = $searchmodule;
		}

		$customView = new CustomView();
		$filterid = $customView->getViewId($module);
		$filterOrAlertInstance = CTMobile_WS_FilterModel::modelWithId($module, $filterid);

		$generator = new QueryGenerator($module, $current_user);
		$generator->setFields($morefields);
		$query = $generator->getQuery();
		$explodeWhereQuery = explode('WHERE', $query);
		$explodeQuery = explode('FROM', $explodeWhereQuery[0]);

		$whatsAppAllNumber = CTWhatsApp_Record_Model::getAllConnectedWhatsappNumber($currentUserID);
        $inNumber = '';
        foreach ($whatsAppAllNumber as $key => $value) {
            $inNumber .= "'".$value['whatsappno']."',";
        }
        $allnumber = rtrim($inNumber, ',');
        $inNumberQuery = ' AND vc.whatsapplog_your_number IN ('.$allnumber.') ';
        $inNumber_Query = ' AND vc_inner.whatsapplog_your_number IN ('.$allnumber.') ';
        $important = "";
        if($importantMessages == 'Yes'){
            $important = " AND vc.whatsapplog_important = 1 ";
        }

        if($whatsappmodule == "NewMessages"){
            $customUnreadQuery = " AND vc.whatsapplog_unreadread = 'Unread' AND vc.messagelog_type = 'Recieved'";
        }else{
            $temporaryQuery = "INNER JOIN ct_whatsapp_temp_table_timeline ON vc.whatsapplogid = ct_whatsapp_temp_table_timeline.whatsapplogid ";
        }


        if($search){
            if(is_numeric($search)){
            	if($searchmodule){
            		$searchInnerQuery = "INNER JOIN vtiger_crmentity cw on cw.crmid = vc.whatsapplog_contactid";
            	}
                $searchQuery = " AND vc.whatsapplog_withccode LIKE '%".$search."%'";
            }else{
                $searchQuery = " AND cw.label like '%".$search."%'";
                $searchInnerQuery = " INNER JOIN vtiger_crmentity cw on cw.crmid = vc.whatsapplog_contactid ";
            }
        }

        if($searchmodule){
        	if($searchInnerQuery == ""){
        		$searchInnerQuery = " INNER JOIN vtiger_crmentity cw on cw.crmid = vc.whatsapplog_contactid ";
        		$searchQuery = " AND cw.setype = '".$searchmodule."'";
        	}
        }

		/*if($search){
            $searchQuery = " AND (vtiger_whatsapplog.whatsapplog_displayname LIKE '%".$search."%' OR vtiger_whatsapplog.whatsapplog_chatid LIKE '%".$search."%' OR vtiger_whatsapplog.whatsapplog_withccode LIKE '%".$search."%' OR c1.label LIKE '%".$search."%')";
        }*/

		if($index != '' && $size != ''){
			if($index == 0){
				$index = 1;
			}
			$limit = ($index*$size) - $size;
			$totalQuery = "SELECT vc.whatsapplog_withccode, vc.messagelog_body, vc.whatsapplogid, vc.whatsapplog_datetime, vc.whatsapplog_contactid
                FROM vtiger_whatsapplog vc INNER JOIN vtiger_crmentity cr ON cr.crmid = vc.whatsapplogid
                ".$searchInnerQuery."
                AND vc.whatsapplog_withccode != ''   
                ".$inNumberQuery."
                ".$important."
                ".$searchQuery."
                ".$customUnreadQuery."
                AND vc.whatsapplog_withccode != 'Groups' 
                AND cr.deleted = 0 
                ORDER BY vc.whatsapplog_datetime DESC";
			$limitQuery = $totalQuery." LIMIT ".$limit.", ".$size;
			
			//$limitQuery = "SELECT * FROM ".$explodeQuery[1]." LEFT JOIN vtiger_crmentity c1 ON c1.crmid = vtiger_whatsapplog.whatsapplog_contactid   WHERE ".$explodeWhereQuery[1]." ".$searchQuery." AND vtiger_whatsapplog.whatsapplog_withccode != 'Groups' AND vtiger_whatsapplog.whatsapplog_your_number = '".$configurationData['whatsappno']."'  ORDER BY vtiger_whatsapplog.whatsapplog_datetime DESC LIMIT ".$limit.", ".$size;
			//$totalQuery = "SELECT * FROM ".$explodeQuery[1]."LEFT JOIN vtiger_crmentity c1 ON c1.crmid = vtiger_whatsapplog.whatsapplog_contactid   WHERE ".$explodeWhereQuery[1]." ".$searchQuery. " AND vtiger_whatsapplog.whatsapplog_withccode != 'Groups' AND AND vtiger_whatsapplog.whatsapplog_your_number = '".$configurationData['whatsappno']."'";
		}else{
			$limitQuery = "SELECT * FROM ".$explodeQuery[1]."LEFT JOIN vtiger_crmentity c1 ON c1.crmid = vtiger_whatsapplog.whatsapplog_contactid   WHERE ".$explodeWhereQuery[1]." ".$searchQuery." AND vtiger_whatsapplog.whatsapplog_withccode != 'Groups' ORDER BY vtiger_whatsapplog.whatsapplog_datetime DESC";
			$totalQuery = '';
		}
		
		$isLast = true;
		$totalLabel = "";
		if($totalQuery != ""){
			$totalResults = $adb->pquery($totalQuery);
			$totalRecords = $adb->num_rows($totalResults);
			if($index && $size){
				if($totalRecords > $index*$size){
					$isLast = false;	
					$pagesize = $index-1;
					$startRange = $pagesize*$size+1;
					$lastRange = $index*$size;	
				}else{
					$isLast = true;
					$pagesize = $index-1;
					$startRange = $pagesize*$size+1;
					$lastRange = $totalRecords;
				}
			}else{
				$isLast = true;
				$startRange = 1;
				$lastRange = $totalRecords;
			}

			$totalLabel = $startRange.' '.vtranslate('LBL_to', $module).' '.$lastRange.' '.vtranslate('LBL_OF', $module).' '.$totalRecords;
		}
		//echo $limitQuery;
		$queryResult = $adb->pquery($limitQuery, array());
		$rows = $adb->num_rows($queryResult);

		$whatsAppList = array();
		for ($i=0; $i < $rows; $i++) { 
			$lastStatus = '';
			$whatsapplogid = $adb->query_result($queryResult, $i, 'whatsapplogid');
			$whatsapplog_chatid = $adb->query_result($queryResult, $i, 'whatsapplog_chatid');
			$messagelog_body = decode_html(decode_html($adb->query_result($queryResult, $i, 'messagelog_body')));
			$whatsapplog_withccode = $adb->query_result($queryResult, $i, 'whatsapplog_withccode');
			if($whatsapplog_withccode == 'Groups'){
				$label = $whatsapplog_chatid;
				$imagePath = $adb->query_result($queryResult, $i, 'whatsapplog_quotemessage');
				$isGroup = 1;
				$ChatId = $adb->query_result($queryResult, $i, 'whatsapplog_msgid');
				if(!$label){
					$whatsappGroupQuery = $adb->pquery("SELECT * FROM vtiger_whatsapplog 
			            INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_whatsapplog.whatsapplogid 
			            WHERE vtiger_crmentity.deleted = 0 AND vtiger_whatsapplog.whatsapplog_msgid = ? AND vtiger_whatsapplog.whatsapplog_msgid != '' ORDER BY vtiger_whatsapplog.whatsapplog_chatid DESC", array($ChatId));
			        $rows1 = $adb->num_rows($whatsappGroupQuery);
			        $allGroupsData = array();
			        if($rows1){
				       $label = $adb->query_result($whatsappGroupQuery,0, 'whatsapplog_chatid');
					}
				}

				$getlastMessageQuery = $adb->pquery("SELECT * FROM vtiger_ctwhatsapp 
					INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
					WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.msgid = ? ORDER BY vtiger_ctwhatsapp.whatsapp_datetime DESC LIMIT 0,1", array($ChatId));
				
				$getlastMessageRow = $adb->num_rows($getlastMessageQuery);
				if($getlastMessageRow){
					$lastStatus = $adb->query_result($getlastMessageQuery, 0, 'whatsapp_unreadread');
				}

				$getlastMessageQuery = $adb->pquery("SELECT count(*) as totalunread FROM vtiger_ctwhatsapp 
					INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
					WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.msgid = ? AND vtiger_ctwhatsapp.whatsapp_unreadread = 'Unread' AND vtiger_ctwhatsapp.message_type = 'Recieved'", array($ChatId));
				$totalunread = $adb->query_result($getlastMessageQuery, 0, 'totalunread');

			}else{
				$whatsapplog_contactid = $adb->query_result($queryResult, $i, 'whatsapplog_contactid');
				$ChatId = $adb->query_result($queryResult, $i, 'whatsapplog_withccode');
				if($whatsapplog_contactid == ""){
					$getRecord = $adb->pquery("SELECT * FROM vtiger_whatsapplog 
						INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_whatsapplog.whatsapplogid 
						WHERE vtiger_whatsapplog.whatsapplog_withccode = '".$ChatId."' AND vtiger_crmentity.deleted = 0".$inNumberQuery, array());
					$RecordRow = $adb->num_rows($getRecord);
					if($RecordRow){
						$whatsapplog_contactid = $adb->query_result($getRecord, 0, 'whatsapplog_contactid');
					}
				}
	
				if(!$this->isDeleted($whatsapplog_contactid)){
					$setype = VtigerCRMObject::getSEType($whatsapplog_contactid);
					if($setype != ""){
						if(!Users_Privileges_Model::isPermitted($setype, 'DetailView', $whatsapplog_contactid)){
							$whatsapplog_contactid = "";
						}else{
							/*$whatsaappModuleData = CTWhatsApp_Record_Model::getWhatsappAllowModuleFields($setype);
							$whatsappPhoneField = $whatsaappModuleData['phoneField'];
							if($whatsappPhoneField != ''){
								$whatsappphonemodel = Vtiger_Record_Model::getInstanceById($whatsapplog_contactid,$setype);
								$phonefieldvalue = $whatsappphonemodel->get($whatsappPhoneField);
								if($phonefieldvalue != $whatsapplog_chatid){
									$whatsapplog_contactid = "";
								}
							}*/
						}
					}
				}else{
					$whatsapplog_contactid = "";
				}

				if ($whatsapplog_contactid && !$this->isDeleted($whatsapplog_contactid)) {
		            $sql = "SELECT vtiger_attachments.*, vtiger_crmentity.setype FROM vtiger_attachments
		                INNER JOIN vtiger_seattachmentsrel ON vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid
		                INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_attachments.attachmentsid
		                WHERE vtiger_seattachmentsrel.crmid = ?";

		            $result = $adb->pquery($sql, array($whatsapplog_contactid));

		            $imageId = $adb->query_result($result, 0, 'attachmentsid');
		            $imagePath = $adb->query_result($result, 0, 'path');
		            $imageName = $adb->query_result($result, 0, 'name');

		            //decode_html - added to handle UTF-8 characters in file names
		            $imageOriginalName = urlencode(decode_html($imageName));

		            if(!empty($imageName)){
		                $imageDetails[] = array(
		                    'id' => $imageId,
		                    'orgname' => $imageOriginalName,
		                    'path' => $imagePath.$imageId,
		                    'name' => $imageName
		                );
		                $imagePath = $site_URL.'/'.$imagePath.$imageId.'_'.$imageName;
		            }
		            
		            $setype = VtigerCRMObject::getSEType($whatsapplog_contactid);
		            $moduleRecordModel = Vtiger_Record_Model::getInstanceById($whatsapplog_contactid);
		            $entityQuery = $adb->pquery("SELECT * FROM vtiger_entityname WHERE modulename = ?",array($setype));
					$entityField = $adb->query_result($entityQuery,0,'fieldname');
					$entityField_array = explode(',',$entityField);
					$entityField = $entityField_array[0];
					if(count($entityField_array) == 2){
						$label = $moduleRecordModel->get($entityField_array[0])." ".$moduleRecordModel->get($entityField_array[1]);
					}else{
		            	$label = $moduleRecordModel->get($entityField);
					}
		        }else{
		        	$imagePath = '';
		        	$label = $whatsapplog_withccode;
		        }
		        $isGroup = 0;

				if($ChatId == ""){
					continue;
				}

				$getlastMessageQuery = $adb->pquery("SELECT * FROM vtiger_ctwhatsapp 
					INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
					WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.whatsapp_withccode = ? ORDER BY vtiger_ctwhatsapp.whatsapp_datetime DESC LIMIT 0,1", array($ChatId));
				
				$getlastMessageRow = $adb->num_rows($getlastMessageQuery);
				if($getlastMessageRow){
					$lastStatus = $adb->query_result($getlastMessageQuery, 0, 'whatsapp_unreadread');
				}

				$getlastMessageQuery = $adb->pquery("SELECT count(*) as totalunread FROM vtiger_ctwhatsapp 
					INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
					WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.whatsapp_withccode = ? AND vtiger_ctwhatsapp.whatsapp_unreadread = 'Unread' AND vtiger_ctwhatsapp.message_type = 'Recieved'", array($ChatId));
				$totalunread = $adb->query_result($getlastMessageQuery, 0, 'totalunread');
			}

			$whatsapplog_unreadread = $adb->query_result($queryResult, $i, 'whatsapplog_unreadread');
			$whatsapplog_your_number = $adb->query_result($queryResult, $i, 'whatsapplog_your_number');
			$whatsapplog_datetime = $adb->query_result($queryResult, $i, 'whatsapplog_datetime');
			$setype = $adb->query_result($queryResult, $i, 'setype');
			$lastMessageConvertDateTime = Vtiger_Util_Helper::formatDateDiffInStrings($whatsapplog_datetime);
			if(date('Y-m-d',strtotime($whatsapplog_datetime)) == date('Y-m-d')){
				$dateArray = explode(' ',Vtiger_Util_Helper::convertDateTimeIntoUsersDisplayFormat($whatsapplog_datetime));
				if(count($dateArray) > 2){
					$whatsapplog_datetime = $dateArray[1].' '.$dateArray[2];
				}else{
					$whatsapplog_datetime = $dateArray[1];
				}
			}else{
				$dateArray = explode(' ',Vtiger_Util_Helper::convertDateTimeIntoUsersDisplayFormat($whatsapplog_datetime));
				$whatsapplog_datetime = $dateArray[0];
			}
			$whatsAppList[$label] = array('id' => CTMobile_WS_Utils::getEntityModuleWSId($module).'x'.$whatsapplogid,'recordid'=>$whatsapplog_contactid, 'label' => $label, 'ImageUrl' => $imagePath, 'phone' => $whatsapplog_withccode, 'ChatId' => $ChatId, 'isGroup' => $isGroup, 'lastMessage' => $messagelog_body, 'lastMessageDateTime' => $whatsapplog_datetime, 'lastMessageConvertDateTime' => $lastMessageConvertDateTime, 'isGroup' => $isGroup, 'email' => '', 'editAction' => true, 'deleteAction' => true, 'lastStatus' => $lastStatus, 'unReadCount' => $totalunread);
		}

		$relatedModules = CTWhatsApp_Record_Model::getWhatsappAllowModules();
		$allowedModules = array_column($relatedModules, 'module');
		//print_r($allowedModules);
		$presence = array('0', '2');
		$searchableModules = array();
		$searchableModules[] = array('module'=>"All",'moduleLabel'=>$this->CTTranslate("all"),'ismoduleEnabled'=>true);
		$searchableModules[] = array('module'=>"Important",'moduleLabel'=>$this->CTTranslate("important"),'ismoduleEnabled'=>true);
		$userPrivModel = Users_Privileges_Model::getInstanceById($current_user->id);
		foreach ($allowedModules as $key => $amodule) {
			$ismoduleEnabled = false;
			$contactModuleModel = Vtiger_Module_Model::getInstance($amodule);
			if(($userPrivModel->isAdminUser() ||
								$userPrivModel->hasGlobalReadPermission() ||
								$userPrivModel->hasModulePermission($contactModuleModel->get('id'))) && in_array($contactModuleModel->get('presence'), $presence) && in_array($amodule,$allowedModules)){
				$ismoduleEnabled = true;
			}
			$searchableModules[] = array('module'=>$amodule,'moduleLabel'=>vtranslate($amodule,$amodule),'ismoduleEnabled'=>$ismoduleEnabled);
		}
		
		$response = new CTMobile_API_Response();
		$results['records'] = array_values($whatsAppList);
		$results['module'] = $module;
		$results['moduleLabel'] = vtranslate($module,$module);
		$results['isLast'] = $isLast;
		$results['totalLabel'] = $totalLabel;
		$results['activeNumbers'] = $activeNumbers;
		$results['connectedDetails'] = $connectedNumberDetails;
		$results['disconnectedMessage'] = "WhatsApp number is disconnected";
		$results['searchBy'] = $searchBy;
		$results['searchableModules'] = $searchableModules;
		$response->setResult($results);
		return $response;
	}

	public function isDeleted($crmid) {
		global $adb;
		$query = "SELECT deleted FROM vtiger_crmentity WHERE crmid = ?";
		$result = $adb->pquery($query,array($crmid));
		if($adb->num_rows($result)){
			return $adb->query_result($result,0,'deleted') == 0 ? false : true;
		}else{
			return true;
		}
	}

	function getActiveNumber($current_user){
		$currenUserID = $current_user->id;
        $configurationData = Settings_CTWhatsApp_Record_Model::getUserConfigurationAllDataWithId($currenUserID);
        $allUserNumber = CTWhatsApp_Record_Model::getAllUserWhatsappNumber($currenUserID);
        $connectedNumbers = array();
        foreach ($allUserNumber as $key => $value) {
        	$configurationData = Settings_CTWhatsApp_Record_Model::getUserConfigurationAllDataWithId($value['userid']);
	        $value['authtoken'] = $configurationData['authtoken'];
	        $value['api_url'] = $configurationData['api_url'];
        	$connectedNumbers[] = $value;
        }
        return $connectedNumbers;
	}

}