<?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/Alert.php';
include_once dirname(__FILE__) . '/models/SearchFilter.php';
include_once dirname(__FILE__) . '/models/Paging.php';

class CTMobile_WS_GetMessageTemplate extends CTMobile_WS_Controller {
	
	
	function getSearchFilterModel($module, $search) {
		return CTMobile_WS_SearchFilterModel::modelWithCriterias($module, Zend_JSON::decode($search));
	}
	
	function getPagingModel(CTMobile_API_Request $request) {
		$page = $request->get('page', 0);
		return CTMobile_WS_PagingModel::modelWithPageStart($page);
	}
	
	function process(CTMobile_API_Request $request) {
		global $adb, $current_user,$root_directory,$site_URL;
		$whatsappFolderPath = "/modules/CTWhatsApp/CTWhatsAppStorage/";
		$current_user = $this->getActiveUser();
		$message_type = trim($request->get('message_type'));
		if($message_type == ''){
			$message = $this->CTTranslate('Required fields not found');
			throw new WebServiceException(404,$message);
		}
		if($message_type == 'WhatsAppTemplates'){
			$searchkeyword = $request->get('search');
			$index = trim($request->get('index'));
			$size = trim($request->get('size'));
	        $wpTemplateViewQuery = $adb->pquery("SELECT * FROM vtiger_customview WHERE entitytype = 'CTWhatsAppTemplates' AND viewname = 'All'");
	        $viewid = $adb->query_result($wpTemplateViewQuery, 0, 'cvid');
	        $listViewModel = Vtiger_ListView_Model::getInstance('CTWhatsAppTemplates', $viewid);
	        $queryGenerator = $listViewModel->get('query_generator');
	        $listQuery = $queryGenerator->getQuery();
	        if($searchkeyword != ""){
	        	$listQuery.= " AND ( vtiger_ctwhatsapptemplates.wptemplate_title LIKE '%".$searchkeyword."%' OR vtiger_ctwhatsapptemplates.wptemplate_text LIKE '%".$searchkeyword."%' )";
	        }
	        /*if($more != 'no'){
	            $listQuery .= " AND vtiger_ctwhatsapptemplates.wptemplate_quickaccess = '1' ORDER BY vtiger_crmentity.modifiedtime DESC LIMIT 0,5";
	        }*/
	        $listq = explode('FROM',$listQuery);
	        $listQuery = "SELECT vtiger_ctwhatsapptemplates.wptemplate_title, vtiger_ctwhatsapptemplates.wptemplate_modules, vtiger_ctwhatsapptemplates.wptemplate_msg, vtiger_ctwhatsapptemplates.whatsapptemplates_no, vtiger_ctwhatsapptemplates.wptemplate_image, vtiger_ctwhatsapptemplates.ctwhatsapptemplatesid,vtiger_ctwhatsapptemplates.wptemplate_text FROM ".$listq[1];
	        $totalQuery = $listQuery;
	        $listQuery.=" ORDER BY vtiger_crmentity.modifiedtime DESC ";
			$totalParams = array();
			$totalResults = $adb->pquery($totalQuery,$totalParams);
			$totalRecords = $adb->num_rows($totalResults);
			if($index && $size){
				$limit = ($index*$size) - $size;
				$listQuery .= sprintf(" LIMIT %s, %s", $limit, $size);
				if($totalRecords > ($index*$size)){
						$isLast = false;
				}else{
					$isLast = true;
				}	
			}else{
				$isLast = true;
			}
	        $getWhatsappTemplateQuery = $adb->pquery($listQuery, array());

	        $whatsappTemplateRows = $adb->num_rows($getWhatsappTemplateQuery);
	        $templatesArray = array();
	        for ($j=0; $j < $whatsappTemplateRows; $j++) { 
	            $templatesID = $adb->query_result($getWhatsappTemplateQuery, $j, 'ctwhatsapptemplatesid');
	            $wptemplate_title = $adb->query_result($getWhatsappTemplateQuery, $j, 'wptemplate_title');
	            $wptemplate_text = $adb->query_result($getWhatsappTemplateQuery, $j, 'wptemplate_text');
	            $wptemplate_image = $adb->query_result($getWhatsappTemplateQuery, $j, 'wptemplate_image');
	            if($wptemplate_text == "" && $wptemplate_image != ""){
	            	$getAttachmentQuery = $adb->pquery("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 = ? AND vtiger_crmentity.deleted = 0", array($templatesID));
	
					$imageId = $adb->query_result($getAttachmentQuery, 0, 'attachmentsid');
					$imagePath = $adb->query_result($getAttachmentQuery, 0, 'path');
					$imageName = $adb->query_result($getAttachmentQuery, 0, 'name');
					$filetype = $adb->query_result($getAttachmentQuery, 0, 'type');
					$attachmentPath = $root_directory.$imagePath.$imageId.'_'.$imageName;

					$newfileURL = $site_URL.$imagePath.$imageId.'_'.urlencode($imageName);
					$wptemplate_text = $newfileURL;
					//copy($attachmentPath, $newfile);
					//$newfileURL = $site_URL.$whatsappFolderPath . "$year/$month/$week/".urlencode($imageName);
		        }
	            $templatesArray[] = array('msgTemplateId'=>$templatesID,'templates_name'=>$wptemplate_title,'description'=>$wptemplate_text);
	        }
	        $response = new CTMobile_API_Response();
			$response->setResult(array('records'=>$templatesArray,'code'=>'','message'=>'','WhatsAppTemplates'=>true,'isLast'=>$isLast));
			if (count($templatesArray) == 0) {
				$message = $this->CTTranslate('No Templates found - create it from Message Templates module');
				$response->setResult(array('records'=>array(),'code'=>404,'message'=>$message,'WhatsAppTemplates'=>true,'isLast'=>$isLast));
			}
		}else{
			$getTemplateQuery = $adb->pquery("SELECT * FROM vtiger_ctmessagetemplate INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctmessagetemplate.ctmessagetemplateid where vtiger_ctmessagetemplate.message_status = ? AND vtiger_ctmessagetemplate.message_type = ? AND vtiger_crmentity.deleted = 0", array('Active', $message_type));
			$countTemplate = $adb->num_rows($getTemplateQuery);
			
			for($i=0;$i<$countTemplate;$i++){
				$msgTemplateId = $adb->query_result($getTemplateQuery, $i, 'ctmessagetemplateid');
				$templates_name = decode_html(decode_html($adb->query_result($getTemplateQuery, $i, 'templates_name')));
				$description = decode_html(decode_html($adb->query_result($getTemplateQuery, $i, 'description')));
				$message_status = $adb->query_result($getTemplateQuery, $i, 'message_status');
				$message_type = $adb->query_result($getTemplateQuery, $i, 'message_type');
				
				$messageTemplateData[] = array('msgTemplateId' => trim($msgTemplateId), 'templates_name' => $templates_name, 'description' => $description, 'message_status' => $message_status, 'message_type' => $message_type); 
			}
			
			$response = new CTMobile_API_Response();
			$response->setResult(array('records'=>$messageTemplateData,'code'=>'','message'=>''));
			
			if ($countTemplate == 0) {
				$message = $this->CTTranslate('No Templates found - create it from Message Templates module');
				$response->setResult(array('records'=>array(),'code'=>404,'message'=>$message));
			}
		}
		
		return $response;
	}
}

?>
