<?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.
  ***************************************************************************** */

class CTMobile_WS_ReadWhatsAppMessage extends CTMobile_WS_Controller {
	
	function process(CTMobile_API_Request $request) {
		$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
		global $current_user, $adb; // Few core API assumes this variable availability
		$current_user = $this->getActiveUser();
		$ChatId = $request->get('ChatId');
		$rctwhatsappid = $request->get('ctwhatsappid');
		if($ChatId){
			if (strpos($ChatId, '@g.us') !== false) {
			    $customQuery = 	" SELECT * FROM vtiger_ctwhatsapp 
		        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
		        WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.whatsapp_unreadread = 'Unread' AND vtiger_ctwhatsapp.message_type = 'Recieved' AND vtiger_ctwhatsapp.msgid = '".$ChatId."'";
			}else{
				$customQuery = 	" SELECT * FROM vtiger_ctwhatsapp 
          		INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctwhatsapp.ctwhatsappid 
          		WHERE vtiger_crmentity.deleted = 0 AND vtiger_ctwhatsapp.whatsapp_unreadread = 'Unread' AND vtiger_ctwhatsapp.message_type = 'Recieved' AND vtiger_ctwhatsapp.whatsapp_withccode = '".$ChatId."'";
			}
			$results = $adb->pquery($customQuery,array());
			$rows = $adb->num_rows($results);
			for ($i=0; $i < $rows; $i++) { 
				 $CTWhatsappId = $adb->query_result($results, $i, 'ctwhatsappid');
				 if($CTWhatsappId){
		            $recordModel = Vtiger_Record_Model::getInstanceById($CTWhatsappId, 'CTWhatsApp');
		            if($recordModel){
		                $recordModel->set('mode', 'edit');
		                $recordModel->set('id', $CTWhatsappId); 
		                $recordModel->set('whatsapp_unreadread', 'Read');
		                $recordModel->save();
		            }
		        }
			}

		}

		if($rctwhatsappid){
            $recordModel = Vtiger_Record_Model::getInstanceById($rctwhatsappid, 'CTWhatsApp');
            if($recordModel){
                $recordModel->set('mode', 'edit');
                $recordModel->set('id', $rctwhatsappid); 
                $recordModel->set('whatsapp_unreadread', 'Read');
                $recordModel->save();
            }
        }
		
		
		$response = new CTMobile_API_Response();
		$response->setResult(array("message"=>"Message Read successfully"));
		return $response;
	}

}
