<?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_EmailSearch extends CTMobile_WS_Controller {

	function process(CTMobile_API_Request $request) {
		$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
		global $current_user,$adb, $site_URL;
		$current_user = $this->getActiveUser();
		$db = PearDatabase::getInstance();
		$searchValue = $request->get('searchValue');

		$EmailsModuleModel = Vtiger_Module_Model::getInstance('Emails');
        $currentUserModel = Users_Record_Model::getCurrentUserModel();
		$emailSupportedModulesList = $EmailsModuleModel->getEmailRelatedModules();

        foreach ($emailSupportedModulesList as $moduleName) {
            $searchFields = array();
            $moduleModel = Vtiger_Module_Model::getInstance($moduleName);
            $emailFieldModels = $moduleModel->getFieldsByType('email');

            foreach ($emailFieldModels as $fieldName => $fieldModel) {
                if ($fieldModel->isViewable()) {
                    $searchFields[] = $fieldName;
                }
            }
            $emailFields = $searchFields;

            $nameFields = $moduleModel->getNameFields();
            foreach ($nameFields as $fieldName) {
                $fieldModel = Vtiger_Field_Model::getInstance($fieldName, $moduleModel);
                if ($fieldModel->isViewable()) {
                    $searchFields[] = $fieldName;
                }
            }

            if ($emailFields) {
                $moduleInstance = CRMEntity::getInstance($moduleName);
                $queryGenerator = new QueryGenerator($moduleName, $currentUserModel);
                $listFields = $searchFields;
                $listFields[] = 'id';
                $queryGenerator->setFields($listFields);
                                
                                //Opensource fix for showing up deleted records on email search
                $queryGenerator->startGroup(""); 
                foreach ($searchFields as $key => $emailField) {
                    $queryGenerator->addCondition($emailField, trim($searchValue), 'c', 'OR');
                }

                $queryGenerator->endGroup(); 
                $result = $db->pquery($queryGenerator->getQuery(), array());
                $numOfRows = $db->num_rows($result);

                for($i=0; $i<$numOfRows; $i++) {
                    $row = $db->query_result_rowdata($result, $i);
                    foreach ($emailFields as $emailField) {
                        $emailFieldValue = $row[$emailField];
                        $id = $row[$moduleModel->get('basetableid')];
                        if ($emailFieldValue) {
                            $recordLabel = getEntityFieldNameDisplay($moduleName, $nameFields, $row);
                            if (strpos($emailFieldValue, $searchValue) !== false || strpos($recordLabel, $searchValue) !== false) {
                                $emailsResult[] = array('module'=>$moduleName,'moduleLabel'=>vtranslate($moduleName, $moduleName),'id'=>CTMobile_WS_Utils::getEntityModuleWSId($moduleName).'x'.$id,'value' => $emailFieldValue,'label' => decode_html($recordLabel).' <b>('.$emailFieldValue.')</b>','name' => decode_html($recordLabel));

                            }
                        }
                    }
                }
            }
        }

        $response = new CTMobile_API_Response();
        if(!empty($emailsResult)){
        	$response->setResult(array("emailsResult"=>$emailsResult,"message"=>""));
        }else{
        	$message = $this->CTTranslate('No records found');
        	$response->setResult(array("emailsResult"=>array(),"message"=>$message));
        }
        return $response;

    }

}