<?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__) . '/Login.php';

class CTMobile_WS_LoginAndFetchModules extends CTMobile_WS_Login {

    function postProcess(CTMobile_API_Response $response) {
        global $current_user, $adb, $site_URL;
        $current_user = $this->getActiveUser();
        if ($current_user) {
            $result = $response->getResult();
            $user_type = $_REQUEST['user_type'];
            if ($current_user) {
                $results = $response->getResult();
                $result['modules'] = $this->getListing($current_user, $user_type);
                $query = "SELECT vtiger_tab.name, vtiger_tab.tabid FROM vtiger_links INNER JOIN vtiger_tab ON vtiger_links.tabid = vtiger_tab.tabid where vtiger_links.linklabel = ?";
                $params = array("DetailViewBlockCommentWidget");
                $results = $adb->pquery($query, $params);
                $numrows = $adb->num_rows($results);
                $CommentsModule = array();
                for ($i = 0;$i < $numrows;$i++) {
                    $CommentsModule[] = $adb->query_result($results, $i, 'name');
                }
                $query2 = "SELECT vtiger_tab.name, vtiger_tab.tabid FROM vtiger_relatedlists INNER JOIN vtiger_tab ON vtiger_relatedlists.tabid = vtiger_tab.tabid where vtiger_relatedlists.presence = 0 AND vtiger_relatedlists.label=?";
                $params2 = array("Activities");
                $result2 = $adb->pquery($query2, $params2);
                $numrows = $adb->num_rows($result2);
                $ActivitiesModule = array();
                for ($i = 0;$i < $numrows;$i++) {
                    $ActivitiesModule[] = $adb->query_result($result2, $i, 'name');
                }
                $query3 = "SELECT * FROM  `vtiger_tab` WHERE  `isentitytype` =1 AND  `presence` =0";
                $result3 = $adb->pquery($query3, array());
                $numrows = $adb->num_rows($result3);
                $SummaryModule = array();
                for ($i = 0;$i < $numrows;$i++) {
                    $Module = $adb->query_result($result3, $i, 'name');
                    $moduleModel = Vtiger_Module_Model::getInstance($Module);
                    if ($moduleModel->isSummaryViewSupported()) {
                        $SummaryModule[] = $Module;
                    } else {
                        continue;
                    }
                }
                $userPrivModel = Users_Privileges_Model::getInstanceById($current_user->id);
                $moduleModel = Vtiger_Module_Model::getInstance('MailManager');
                $isMailManager = false;
                $menuModelsList = Vtiger_Menu_Model::getAll(true);
                $presence = array('0', '2');
                if (array_key_exists("MailManager", $menuModelsList) && ($userPrivModel->isAdminUser() || $userPrivModel->hasGlobalReadPermission() || $userPrivModel->hasModulePermission($moduleModel->get('id'))) && in_array($moduleModel->get('presence'), $presence)) {
                    $isMailManager = true;
                }

                $moduleModel = Vtiger_Module_Model::getInstance('CTUserFilterView');
                $isCTUserFilterView = false;
                if (($userPrivModel->isAdminUser() || $userPrivModel->hasGlobalReadPermission() || $userPrivModel->hasModulePermission($moduleModel->get('id'))) && in_array($moduleModel->get('presence'), $presence)) {
                    $isCTUserFilterView = true;
                }

                $moduleModel = Vtiger_Module_Model::getInstance('CTWhatsApp');
                $isWhatsApp = false;
                $menuModelsList = Vtiger_Menu_Model::getAll(true);
                $presence = array('0', '2');
                if(array_key_exists("CTWhatsApp",$menuModelsList) && ($userPrivModel->isAdminUser() ||
                                    $userPrivModel->hasGlobalReadPermission() ||
                                    $userPrivModel->hasModulePermission($moduleModel->get('id'))) && in_array($moduleModel->get('presence'), $presence) ){
                    $isWhatsApp = true;
                }

                if($isWhatsApp){
                    if(!$this->isWhatsAppEnabled()){
                        $isWhatsApp = false;
                    }
                }
                $result['isMailManager'] = $isMailManager;
                $result['isCTUserFilterView'] = $isCTUserFilterView;
                $result['isWhatsApp'] = $isWhatsApp;
                $response->setResult($result);
            }
            $response->setResult($result);
        }
    }

    function isWhatsAppEnabled(){
        global $adb,$current_user;
        $current_user = $this->getActiveUser();
        $currenUserID = $current_user->id;
        $query_main = "SELECT iconactive FROM vtiger_ctwhatsappusers WHERE customfield5 = ?";
        $query_result = $adb->pquery($query_main,array($currenUserID));
        if($adb->num_rows($query_result)){
            $iconactive = $adb->query_result($query_result,0,'iconactive');
            if(!$iconactive){
                return false;
            }
        }
        $getUserGrous = $adb->pquery("SELECT * FROM vtiger_ctwhatsappconfiguration");
        $multipleWahtsapp = $adb->query_result($getUserGrous, 0, 'customfield4');

        if($multipleWahtsapp == 'multipleWhatsapp'){
            $getUserGroups = $adb->pquery("SELECT * FROM vtiger_ctwhatsappusers INNER JOIN vtiger_ctwhatsapp_user_groups ON vtiger_ctwhatsapp_user_groups.userid = vtiger_ctwhatsappusers.customfield5 WHERE vtiger_ctwhatsapp_user_groups.active = 1");
            $userrows = $adb->num_rows($getUserGroups);
            $allUsers = '';
            for ($i=0; $i < $userrows; $i++) { 
                $allUsers .= $adb->query_result($getUserGroups, $i, 'userid').',';
                $allUsers .= $adb->query_result($getUserGroups, $i, 'multiple_userid').',';
            }

            $usersGroups = explode(',', $allUsers);
        }else{
            $usersGroups = explode(',', $adb->query_result($getUserGrous, 0, 'users_groups'));
        }

        $userid = in_array($currenUserID, $usersGroups);
        if($userid){
            $num_rows = 1;
        }else{
            $queryGetGroupId = $adb->pquery("SELECT * FROM vtiger_users2group WHERE userid = ?", array($currenUserID));
            $numRows = $adb->num_rows($queryGetGroupId);
            for ($i=0; $i < $numRows; $i++) { 
                $groupid[] = $adb->query_result($queryGetGroupId, $i, 'groupid');
            }

            foreach ($groupid as $key => $value) {
                $existGroup = in_array($value, $usersGroups);
                if($existGroup){
                    $num_rows = 1;
                    break;
                }else{
                    $num_rows = 0;
                }
            }
        }

        if($num_rows == 1){
            return true;
        }else{
            return false;
        }
    }

    function getListing($user, $user_type) {
        global $adb;
        $modulewsids = CTMobile_WS_Utils::getEntityModuleWSIds();
        // Disallow modules
        unset($modulewsids['Users']);
        // Calendar & Events module will be merged
        unset($modulewsids['Events']);
        $listresult = vtws_listtypes(null, $user);
        include_once 'modules/Vtiger/models/Menu.php';
        $menuModelsList = Vtiger_Menu_Model::getAll(true);
        unset($modulewsids['ModuleIcon']);
        unset($modulewsids['EmailTracker']);
        unset($modulewsids['CTAddressFinder']);
        unset($modulewsids['Rss']);
        unset($modulewsids['Portal']);
        unset($modulewsids['PBXManager']);
        unset($modulewsids['RecycleBin']);
        unset($modulewsids['Reports']);
        unset($modulewsids['forecast']);
        unset($modulewsids['EmailCampaigns']);
        unset($modulewsids['EmailTemplates']);
        unset($modulewsids['SubscribersList']);
        unset($modulewsids['EmailTrackingReport']);
        unset($modulewsids['Billing']);
        unset($modulewsids['ModComments']);
        unset($modulewsids['Emails']);
        unset($modulewsids['ModuleIcon']);
        unset($modulewsids['CTPushNotification']);
        unset($modulewsids['CTMobile']);
        unset($modulewsids['CTAttendance']);
        unset($modulewsids['CTRouteAttendance']);
        unset($modulewsids['CTRoutePlanning']);
        unset($modulewsids['CTTimeTracker']);
        unset($modulewsids['CTTimeControl']);
        unset($modulewsids['CTUserFilterView']);
        unset($menuModelsList['CTAttendance']);
        unset($menuModelsList['CTMobile']);
        unset($menuModelsList['CTPushNotification']);
        unset($menuModelsList['ModuleIcon']);
        unset($menuModelsList['EmailTracker']);
        unset($menuModelsList['CTAddressFinder']);
        unset($menuModelsList['Rss']);
        unset($menuModelsList['Portal']);
        unset($menuModelsList['PBXManager']);
        unset($menuModelsList['RecycleBin']);
        unset($menuModelsList['Reports']);
        unset($menuModelsList['forecast']);
        unset($menuModelsList['EmailCampaigns']);
        unset($menuModelsList['EmailTemplates']);
        unset($menuModelsList['SubscribersList']);
        unset($menuModelsList['EmailTrackingReport']);
        unset($menuModelsList['Billing']);
        unset($menuModelsList['ModComments']);
        unset($menuModelsList['Emails']);
        unset($menuModelsList['CTRouteAttendance']);
        unset($menuModelsList['CTRoutePlanning']);
        unset($menuModelsList['CTTimeTracker']);
        unset($menuModelsList['CTTimeControl']);
        unset($menuModelsList['CTUserFilterView']);
        $AllowedModules = array();
        $MResults = $adb->pquery("SELECT module FROM ctmobile_modules_management", array());
        for ($i = 0;$i < $adb->num_rows($MResults);$i++) {
            $AllowedModules[] = $adb->query_result($MResults, $i, 'module');
        }
        $appname = array('Sales', 'Marketing', 'Inventory', 'Tools', 'Support', 'Other Modules');
        $listing = array();
        $other_module = 'Other Modules';
        $count = 0;
        $inventoryModules = getInventoryModules();
        foreach ($appname as $key => $value) {
            foreach ($listresult['types'] as $index => $modulename) {
                if (checkModulePermission($modulename, $AllowedModules)) {
                    unset($menuModelsList[$modulename]);
                    $view = 'List';
                    if ($modulename == 'Calendar') {
                        $view = 'Calendar';
                    }
                    if (!isset($modulewsids[$modulename])) continue;
                    $getModuleParent = $adb->pquery("SELECT * FROM vtiger_tab where name = ? and isentitytype = ?", array($modulename, 1));
                    $countModuleParent = $adb->num_rows($getModuleParent);
                    $userPrivModel = Users_Privileges_Model::getInstanceById($user->id);
                    $moduleModel = Vtiger_Module_Model::getInstance($modulename);
                    if (($userPrivModel->isAdminUser() || $userPrivModel->hasGlobalReadPermission() || $userPrivModel->hasModulePermission($moduleModel->getId()))) {
                        $restrictedModule = array('CTMobile', 'Rss', 'Portal', 'RecycleBin', 'ExtensionStore', 'CTPushNotification', 'EmailTemplates', 'CTAttendance');
                        if (in_array($modulename, $restrictedModules) && $user_type == 'free') {
                            $module_access = false;
                        } else {
                            $module_access = true;
                        }
                        $ModulesArray = array('SMSNotifier', 'PBXManager', 'CTPushNotification', 'CTCalllog', 'CTAttendance');
                        if (in_array($modulename, $ModulesArray)) {
                            $QuickCreateAction = false;
                            $editAction = false;
                            $createAction = false;
                        } else {
                            $QuickCreateAction = $moduleModel->isQuickCreateSupported();
                            $editAction = $userPrivModel->hasModuleActionPermission($moduleModel->getId(), 'EditView');
                            $createAction = $userPrivModel->hasModuleActionPermission($moduleModel->getId(), 'EditView');
                        }
                        if ($countModuleParent > 0) {
                            if ($value == $other_module) {
                                $value = '';
                            }
                            $moduleParent = $adb->query_result($getModuleParent, 0, 'parent');
                            if ($moduleParent == $value) {
                                if ($moduleParent == 'Sales' || $moduleParent == 'Marketing') {
                                    $count = 0;
                                    $moduleParent = 'LBL_MARKETING_AND_SALES';
                                } else if ($moduleParent == '') {
                                    $moduleParent = $other_module;
                                } else {
                                    $moduleParent = 'LBL_' . strtoupper($moduleParent);
                                }
                                $moduleParent = vtranslate($moduleParent, 'Vtiger', $user->language);
                                if ($moduleParent != '') {
                                    if (in_array($modulename, $CommentsModule)) {
                                        $isCommentModule = true;
                                    } else {
                                        $isCommentModule = false;
                                    }
                                    if (in_array($modulename, $ActivitiesModule)) {
                                        $isActivityModule = true;
                                    } else {
                                        $isActivityModule = false;
                                    }
                                    if (in_array($modulename, $SummaryModule)) {
                                        $isSummerymodule = true;
                                    } else {
                                        $isSummerymodule = false;
                                    }
                                    if (in_array($modulename, $inventoryModules)) {
                                        $isInventoryModule = true;
                                    } else {
                                        $isInventoryModule = false;
                                    }
                                    $listing[$count]['tab_key'] = $count;
                                    $listing[$count]['tab_name'] = $moduleParent;
                                    $listing[$count]['modules_list'][] = array('id' => $modulewsids[$modulename], 'name' => $modulename, 'isEntity' => $listresult['information'][$modulename]['isEntity'], 'label' => $listresult['information'][$modulename]['label'], 'singular' => $listresult['information'][$modulename]['singular'], 'parent' => $moduleParent, 'view' => $view, 'img_url' => CTMobile_WS_Utils::getModuleURL($modulename), 'module_access' => $module_access, 'createAction' => $createAction, 'editAction' => $editAction, 'QuickCreateAction' => $QuickCreateAction, 'isCommentModule' => $isCommentModule, 'isActivityModule' => $isActivityModule, 'isSummerymodule' => $isSummerymodule, 'isInventoryModule' => $isInventoryModule);
                                }
                            }
                        } else {
                            if (in_array($modulename, $CommentsModule)) {
                                $isCommentModule = true;
                            } else {
                                $isCommentModule = false;
                            }
                            if (in_array($modulename, $ActivitiesModule)) {
                                $isActivityModule = true;
                            } else {
                                $isActivityModule = false;
                            }
                            if (in_array($modulename, $SummaryModule)) {
                                $isSummerymodule = true;
                            } else {
                                $isSummerymodule = false;
                            }
                            if (in_array($modulename, $inventoryModules)) {
                                $isInventoryModule = true;
                            } else {
                                $isInventoryModule = false;
                            }
                            $listing[4]['modules_list'][] = array('id' => $modulewsids[$modulename], 'name' => $modulename, 'isEntity' => $listresult['information'][$modulename]['isEntity'], 'label' => $listresult['information'][$modulename]['label'], 'singular' => $listresult['information'][$modulename]['singular'], 'parent' => '', 'view' => $view, 'img_url' => CTMobile_WS_Utils::getModuleURL($modulename), 'module_access' => $module_access, 'createAction' => $createAction, 'editAction' => $editAction, 'QuickCreateAction' => $QuickCreateAction, 'isCommentModule' => $isCommentModule, 'isActivityModule' => $isActivityModule, 'isSummerymodule' => $isSummerymodule, 'isInventoryModule' => $isInventoryModule);
                        }
                    }
                }
            }
            $count++;
        }
        $newModulesList = array();
        foreach ($listing as $key => $value) {
            if (count($value) > 0) {
                $newModulesList[] = $value;
            } else {
                unset($listing[$key]);
            }
        }
        return $newModulesList;
    }
}
function checkModulePermission($module, $AllowedModules) {
    if (!in_array('selectAll', $AllowedModules)) {
        if (in_array($module, $AllowedModules)) {
            return true;
        } else {
            return false;
        }
    } else {
        return true;
    }
}
