<?php
if(!isset($_SESSION)) session_start();

if ($_REQUEST["Action"] == "login")
{   
	require_once 'loginEng.php';
        $stratTime = date("h:i:sa");
        write_to_log("INFO", "Login: username:$userdetails[Username]"); //in error to track the login of users
	return;
}

require_once 'loginCheckPoint.php';
require_once 'write_log.php';
require_once 'mainEng_funcs.php';
require_once 'v2'.DIRECTORY_SEPARATOR.'mainEng_funcs_v2.php';
require_once 'tags.php';

require_once '..'.DIRECTORY_SEPARATOR.'iventitymatcherhtm'.DIRECTORY_SEPARATOR.'WLUtils.php';
require_once '..'.DIRECTORY_SEPARATOR.'iventitymatcherhtm'.DIRECTORY_SEPARATOR.'analyseWLClass.php';
require_once '..'.DIRECTORY_SEPARATOR.'iventitymatcherhtm'.DIRECTORY_SEPARATOR.'compareWLClass.php';


//initiliaze MainEng variables
$mainEng_arr = init_mainEng();
$username = $mainEng_arr['username'];
$isAdmin = $mainEng_arr['isAdmin'];
$action = $mainEng_arr['action'];
$mysqli = $mainEng_arr['mysqli'];
$allConceptsData = $mainEng_arr['concept_class'];

$start = microtime(true);
$stratTime = date("h:i:sa");

$response = array(); // init empty array for last response

$v2 = $_REQUEST['v2'] ?? null; //v2 condition

switch($action){
    case "cleanDB":
        require_once 'parseUtils.php';
        $response = cleanDB($mysqli, $userdetails);
        break;
        
    case "listFoldersTree":
        $response = listFoldersTree($mysqli, $_REQUEST["folderId"]);
        break;
   
    case "getFolderParentsList":
        $response = getFolderParentsList($mysqli, $_REQUEST["fid"]);
        break;
        
    case "listFilesPerDir":
        $response = listFilesPerDir($mysqli, $_REQUEST["folderId"],$username, $isAdmin);
        break;
     
    case "getSavedSearch":
        $response = getSavedSearch($mysqli, true, $_REQUEST["savedSearch"] ?? null);
        break;
 
    case "getFolders":
        $response = getFolders($mysqli, $username, $isAdmin);
        break;
        
    case "searchValues": 
        $response = getSearchFieldValues($mysqli, $username, $isAdmin, $_REQUEST, $v2 ?? null);
        break;
        
    case "getPie":
        if(empty($_REQUEST["name"])){
            require_once 'StatisticPageEng.php';
            $response = getPie($mysqli, $v2, null, $_REQUEST["savedsearch"] ?? null);
        }
        else{
            $response = getPieData($mysqli, $v2 ?? null);
        }
        break;
        
    case "addToFilterView":
        $response = addToFilterView($mysqli, $username);
        break;
        
    case "getFilteredItems":
        $response = getFilteredItems($mysqli, $username);
        break;
        
    case 'resetPanlesFilters':
        $response = resetFilterView($mysqli, $username, $isAdmin);
        break;
        
    case "getRelations":
        $response = getRelationsData($mysqli);
        break;

    case "caseStatistics":
        $response = caseStatistics($mysqli, $_REQUEST["from_background"] ?? null, $_REQUEST["savedSearch"] ?? null);
        break;
               
    case "saveSearchToFiles":
        $response = saveSearchToFiles($mysqli);
        break;
    
    case "isLocked":
        $response = isLocked($mysqli, $_REQUEST["docId"] ?? $_REQUEST["dcid"]);
        break;
        
    case "nextDoc":
        $response = nextDoc($mysqli, $_REQUEST["docId"] ?? $_REQUEST["dcid"],$_REQUEST["folder"] ?? null);
        break;
      
    case "export":        
        if (getUserPermission(CAN_EXPORT))
        {
            require_once 'parseUtils.php';         
            export($mysqli, $_REQUEST);
            $response = "ok";
        }
        else{
            $response = array("error" => "You are not authorized to perform this operation");
        }
        break;
          
    case "exportSearchedDocs":
        if (getUserPermission(CAN_EXPORT))
        {
            require_once 'parseUtils.php';
            $lsid = getLastSavedSearchId($mysqli, $username);
            
            $response = exportSearchFilesToFolder($mysqli,$lsid,$_REQUEST["dest_folder"] ?? null);
        }
        else{
            $response = array("error" => "You are not authorized to perform this operation");
        }
        break;
   
    case "getExtraColumns":
        $response = getExtraColumns($mysqli,$_REQUEST['label_view'] ?? false);
        break;  
  
   //Manage Entities//
    case "getManageEntitiesNames":
        $response = getManageEntitiesNames($mysqli);
        break; 

    case "getManageEntitiesPerInstance":
        require_once 'v2'.DIRECTORY_SEPARATOR .'ManageEntitiesEng_v2.php';
        $name = $_REQUEST['name'];
        $searchConcept = $_REQUEST['searchConcept'];
        $response = getMangeEntities($mysqli, $searchConcept,$name,true);  
        break;
        
    case "getManageEntities":
        require_once 'v2'.DIRECTORY_SEPARATOR .'ManageEntitiesEng_v2.php';
        $response =  getManageEntities($mysqli, $username, $isAdmin);
        break; 
        
        
    case "insertManageEntities":
        require_once 'v2'.DIRECTORY_SEPARATOR .'ManageEntitiesEng_v2.php';
        $input = file_get_contents( 'php://input');
        $data = json_decode($input,1) ;
        $response = insertData_v2($mysqli, $username, $data);
        break;
               
    //not in the new UI yet
    case "deleteManageEntities":
        require_once 'v2'.DIRECTORY_SEPARATOR .'ManageEntitiesEng_v2.php';
        $entity = $_REQUEST['entity'];
        $name = $_REQUEST['name'];
        $response = deleteEntity_v2($mysqli, $name);
        break;
        
    case 'removeTagFromEntityAgg':
        require_once 'v2'.DIRECTORY_SEPARATOR .'ManageEntitiesEng_v2.php';
        $entityAgg = $_REQUEST['entityAgg'];
        $tagname = $_REQUEST['tagname'];
        $response = deleteEntity_v2($mysqli, $entityAgg, $tagname);
        break;
        
   //end - manage Entities
    case "listRelationsTree":
        $response = getRelationHirarchy($mysqli);
        break;
        
    case "listRelations":
        if ($_REQUEST["type"] == "relation")
        {
            require_once 'parseUtils.php';
            $response = listRelations($mysqli, $_REQUEST["type"] ?? null, $_REQUEST["subjectType"]?? null,  $_REQUEST["objectType"]?? null, $_REQUEST["groupBy"]?? null, $_REQUEST["savedsearch"]?? null,  $_REQUEST["subjectName"]?? null,
                                                $_REQUEST["objectName"] ?? null, $_REQUEST["relationList"]?? null, $_REQUEST["relationType"]?? null, $_REQUEST["ignoreSubject"]?? null, $_REQUEST["lastSearch"]?? null,
                                                $_REQUEST["pastPeriod"] ?? null, $isAdmin,$username); 
        }
        else {
            $response = getPieData($mysqli, $v2 ?? null);
        }
        break;    
        
        
    case "getSlotByTable":
    	$response = getSlotByTable($mysqli, $_REQUEST);
        break; 
                
    case "autoComplete":
        $response = autoComplete($mysqli, $_REQUEST["name"] ?? null , $_REQUEST["table"] ?? null );
        break;
        
    case "generateKeywords":
        require 'analyticsUtils.php';
        session_write_close();    
        $filters = getConceptsFromIds($mysqli, $_REQUEST['filters']);
        $analytics_obj = new AnalyticsClass($mysqli, "concept", $filters ?? null, $username,  $_REQUEST["limit"] ?? 1000);
        if($_REQUEST['option'] == 'Solr'){
            $response = $analytics_obj->genereateSolrWordCloudResponse();    
        }
        else{
            $response = $analytics_obj->generateKeywords($mysqli, $_REQUEST["option"] ?? null,
                $_REQUEST["orderBy"] ?? null, $_REQUEST["prominence"] ?? null,
                $_REQUEST["savedSearch"] ?? null, $_REQUEST["limit"] ?? null, $filters ?? null, $isAdmin);
        }
        break;  

    case "setPastPeriod":
        require_once 'parseUtils.php';   
        $response = setPastPeriod($mysqli, $username, $_REQUEST["pastPeriod"]);
        break;
   
    case "setFlavor":
        $flavor = $_REQUEST["flavor"];
        $response = $allConceptsData::setFlavor($mysqli, $flavor);
        break;
        
    case "getAllFlavorData":
        $response = $allConceptsData::getAllFlavorData($mysqli);
        break;
    
    case "getAllConceptArr":
        require_once 'allConceptArr.php';
        $response = $allConceptArr;
        break;
        
    case "getDefaultConcepts":
        //get the default concepts for the allConcept Editor (new UI)
        require_once 'allConceptArr.php';
        $response = $allConceptArrDefault;
        break;
        
    case "getSystemStatus":
        session_write_close();
        
        require_once 'systemCheckup.php';   
        $request_id = $_REQUEST['id'] ?? null;
        $response = systemCheckup::system_status( $username);
        break;
  
    case "getSolrFields":
        $response = getSolrFields($mysqli, $username, $isAdmin);
        break;
        
    case "getFieldValueFromSolr":
        $response = getFieldValueFromSolr($mysqli, $username, $isAdmin, $_REQUEST['docid'], $_REQUEST["field"]);
        break;
        
            
   //Actions with RETURN
   //first get the responses (could be NULL)  
    case "getLogs":
        getLogs($_REQUEST['log_action']);
        $result = null;
        break;
        
    case "exportAllFilesIdName":
        $lsid = getLastSavedSearchId($mysqli, $username);
        $response = exportLimitAllSearch($mysqli, $lsid);
        $result = null;
        break;
    /**
     * end -  results return
     */
 
     //New UI Get Settings 
    case "getSettings":   
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getSettings($_REQUEST["settings"] ?? null, $_REQUEST['section'] ?? null, $_REQUEST["sub_section"] ??  $_REQUEST["subSection"] ?? null);
        break;
 
    case "getDashboardLanguages":
    case "getLanguages":
    case "getDateFormats":
    case "getFonts":
    case "getFontSizes":
    case "getThemes":
    case "getTableFields":
    case "getFlavors":
    case "getKeyStats":
    case "getPermissions":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getSettings($_REQUEST["settings"] ?? null, $_REQUEST['section'] ?? $_REQUEST['Action'] ?? null, $_REQUEST['Action'] ?? null);
        break;
        
    case "getSystemSettings":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getSystemSettings();
        break;
        
    case "getCrawlerSettingsAndStatus":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getCrawlerSettingsAndStatus();
        break;

    case "setCrawlerSettings":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setCrawlerSettings($data);
        break;
        
    case 'analyseLinkedinProfile':
        session_write_close();
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $response = analyseLinkedinProfile($mysqli, $username, $data);
        break;
        
    case "startTwitterCrawler":
        $input = file_get_contents('php://input');
        $response = asyncRequst::getInstance()->crawlerAsync($_REQUEST['twitterBK']);
        break;
        
    case "stopTwitterCrawler":
        $input = file_get_contents('php://input');     
        $response = stopTwitterCrawler($mysqli);
        break;

    case "saveTwitterRule":
        require_once 'tools'.DIRECTORY_SEPARATOR.'cowitter'.DIRECTORY_SEPARATOR.'twitter_v2.php';
        $input = file_get_contents('php://input');
        $response = Felix\TwitterStream\saveTwitterRule($input, $_REQUEST['twitterBK']); 
        break;
      
    case "deleteTwitterRule":
        require_once 'tools'.DIRECTORY_SEPARATOR.'cowitter'.DIRECTORY_SEPARATOR.'twitter_v2.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $response = Felix\TwitterStream\deleteTwitterRule($data,$_REQUEST['twitterBK']);
        break;
        
        
    case "getTwitterRules":
        require_once 'tools'.DIRECTORY_SEPARATOR.'cowitter'.DIRECTORY_SEPARATOR.'twitter_v2.php';
        $response = Felix\TwitterStream\getTwitterRules($_REQUEST['twitterBK']);
        break;
        
        
    case "startFilter":
        $response = asyncRequst::getInstance()->filterAsync();
        break;
        
    case "stopFilter":
        $response = stopFilter($mysqli);
        break;
        
    case "setAlertsSettings":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1); 
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setAlertSettings($data);
        break;
        
    case "setReportSettings":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setReportSettings($data);
        break;
        
    case "setFileReportSettings":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setFileReportSettings($data);
        break;
        
    case "setSettingsConceptInstaces":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setSettingsConceptInstaces($data);
        break;
        
    case "getAlertsSettings":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getAlertSettings();
        break;
        
    case "getReportSettings":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getReportSettings();
        break;
        
    case "getFileReportSettings":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getFileReportSettings();
        break;
        
        
    case "setSystemSettings":
        require_once 'settings.php';
        $input = file_get_contents('php://input');
        $data = json_decode($input,1);
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setSystemSettings($data);
        break;

    case "getActiveFlavor":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->getActiveFlavor();
        break;
        
    case "setActiveFlavor":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setActiveFlavor();
        break;
        
    case "setKeyStats":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setSettings("ui", $_REQUEST['Action'] ?? null, $_REQUEST['Action'] ?? null);
        break;
        
    case "setTableFields":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setSettings("ui", $_REQUEST['Action'] ?? null, $_REQUEST['Action'] ?? null);
        break;
        
    case "setSettings":
        require_once 'settings.php';
        $settings_class =  new Settings($mysqli, $username);
        $response =  $settings_class->setSettings($_REQUEST["settings"],  $_REQUEST["section"], $_REQUEST["sub_section"] ??  $_REQUEST["subSection"] ?? null);
        break;
        
    case "saveGraph":
        $response = saveGraph($mysqli, $username);
        break;
     
    case "getMetadataFromDB":
        $response = getMetadataFromDB($mysqli, $_REQUEST['docid']);
        break; 
        
    case "getIntuviewInfoFromDB":
        $response = getMetadataFromDB($mysqli, $_REQUEST['docid'], true);
        break; 
        
    case "getFolderMetaData":
        $response = getFolderMetaData($mysqli, $username, $_REQUEST["fid"], $_REQUEST['intuviewinfo'] ?? null);
        break;
        
    case "searchSmartSearch_v2":
        $response = applySmartSearch_v2($mysqli, $username, $_REQUEST["searchSmart"] ?? null);
        break; 
        
    case "getRelationsEntityTypes":
        $response = getRelationsType($mysqli, $username, $_REQUEST["merged"] ?? null);
        break;
    
    case "getRelationsTypesMatch":
        $response = getRelationsTypesMatch($mysqli, $username, $_REQUEST["type"], $_REQUEST["name"]);
        break;
        
    case "getKeywordTables_v2":
        $response = getKeywordTables_v2($mysqli, $allConceptsData::getFlavorDataArr($mysqli));
        break;
        
    case "getConceptsIds":
        $response = getConceptsIds($mysqli);
        break;
        
    case "proSentPageEng":
        $_REQUEST['avoidDupTrend'] = true;
        require_once 'proSentPageEng.php';
        
        $response = getTrend($mysqli, true, null, null);
        
        break;
        
//     case "getGroupTrend": 
//         require_once 'proSentPageEng.php';
//         $response = getTrendGroup($mysqli, $username, $isAdmin);
//         break;
        
    case "crossEntity":
        require_once 'ManageEntitiesEng.php';   
        $input = file_get_contents('php://input');       
        $entity = json_decode($input,1); 
        $response = crossEntity($mysqli, $username, $isAdmin, $entity, $_REQUEST["source_table"], $_REQUEST["dest_table"]);
        break;
        
    case 'resetAllCrossEntity':
        require_once 'ManageEntitiesEng.php';
        $response = reset_all_cross_entity($mysqli, $username, $isAdmin);
        break;
        
    case 'hideEntities':
        require_once 'ManageEntitiesEng.php'; 
        $response = hide_entities($mysqli, $username, $isAdmin);
        break;
           
    case "removePanel":
        $response = removePanel($mysqli, $username, $_REQUEST["id"]);
        break;
        
    //restore the user config details in the site (search, saved search dashboard, foldertree, lockedfile, userstatus)
    case "restoreUser":
        require_once 'v2'.DIRECTORY_SEPARATOR.'users.php';
        $user_class = new Users($mysqli);
        $response = $user_class->restore_user($_REQUEST['username']); 
        break;
        
    case 'deleteUser':
        require_once 'v2'.DIRECTORY_SEPARATOR.'users.php';
        $user_class = new Users($mysqli);
        $response =  $user_class->remove_user($_REQUEST['username'], true);
        break;  
        
    case "addUser":
        require_once 'v2'.DIRECTORY_SEPARATOR.'users.php';
        $user_class = new Users($mysqli);
        $response = $user_class->addUser();
        break;
        
    case "getUsers":
        require_once 'v2'.DIRECTORY_SEPARATOR.'users.php';
        $user_class = new Users($mysqli);
        $response = $user_class->getAllUsers();
        break;
        
    //informationEng_v2
    case "information_v2":
        require_once 'parseUtils.php';
        require_once 'v2'.DIRECTORY_SEPARATOR .'informationEng_v2.php';
        $response = informationPage_v2($mysqli, $allConceptsData->getMergedData(), $_REQUEST["name"] ?? null,  $_REQUEST["type"] ?? null);     
        break;
        
    //senddocEngAjx_v2
    case "senddocEngAjx":
        require_once 'v2'.DIRECTORY_SEPARATOR.'senddocEngAjx_v2.php';
        $response = uploadFilesProcess($mysqli, $isAdmin);
        break;
        
    //sendFolder_v2
    case "sendFolder":
        require_once 'v2'.DIRECTORY_SEPARATOR.'sendFolder_v2.php';
        $response = sendFolderProcess($mysqli, $username, $isAdmin);
        break;
        
    case "getFoldersStatus":
        require_once 'v2'.DIRECTORY_SEPARATOR.'sendFolder_v2.php';
        $response = getFoldersStatus($mysqli, $username, $isAdmin);
        break;
     
    case "checkAlerts":
        $response = checkAlerts($mysqli, $username, $isAdmin);
        break;
        
    case "getAlerts":
        $response = getAlerts($mysqli, $username, $isAdmin);
        break;
        
    case "getAlertsStatus":
        $response = getAlertsStatus($mysqli, $username, $isAdmin);
        break;
  
    case 'addToAlert':
        $response = addToAlert($mysqli, $username);
        break;
        
    case 'getUserAlertHistory':
        require_once 'tools'.DIRECTORY_SEPARATOR.'cowitter'.DIRECTORY_SEPARATOR.'cli_filter_application.php';
        $response = fetchUserHistory($_REQUEST["user_id"]);
        break;
         
    case "getDocUrls":
        $response = getDocUrls($mysqli, $_REQUEST["docid"],$_REQUEST["regex"]);
        break;
        
    case "getCustomReport":
        require_once 'report.php';
        $report = new ReportGenerator($mysqli,$username);
        $response = $report->generateReport();
        break;

    /**
     * WL ACTIONS
     */
    case "uploadWL":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1); 
        $WLclass = new WLUtils($mysqli,$sent_data);
        $response =  $WLclass->uploadWL($sent_data, $_REQUEST["override"] ?? null);
        break;
        
    case "deleteWL":
        $WLclass = new WLUtils($mysqli);
        $response =   $WLclass->deleteWL($_REQUEST["name"]);
        break;
        
    case "getWL":
        $WLclass = new WLUtils($mysqli);
        $response =   $WLclass->getWLs();
        break;
        
    case "getNAColumns":
        $columns_json = json_decode(file_get_contents('../iventitymatcherhtm/jsons/columns.json',true));
        $columns_arr = json_decode(json_encode($columns_json), TRUE);
        $response = $columns_arr['resultsCols'];
        break;
        
    case "analyseName":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1);
        $WLclass = new AnalyseWLClass($mysqli, "name", $sent_data);
        $response = $WLclass->analyseNameFunc($_REQUEST["searchPerson"]);
        break;
        
    case "analyseWL":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1);
        $WLclass = new AnalyseWLClass($mysqli, "list", $sent_data);
        $response = $WLclass->analyseWL();
        break;
        
    case "searchPersonInWL":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1);
        $WLclass = new CompareWLClass($mysqli,"name", $sent_data);
        $response = $WLclass->searchPersonInList($_REQUEST["searchPerson"], $_REQUEST["wlSelected"]);
        break;

    case "compareWLs":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1);
        $WLclass = new CompareWLClass($mysqli, "list", $sent_data);
        $response = $WLclass->compareWLs();
        break;
    
    case "compareDBWLs":
        $input = file_get_contents('php://input');
        $sent_data = json_decode($input,1);
        $WLclass = new CompareWLClass($mysqli, "db", $sent_data);
        $response = $WLclass->compareDBWLs();
        break;
        
    case "getLatestWLResult":
        $WLclass = new WLUtils($mysqli);
        $response = $WLclass->getLatestWLResult($_REQUEST["wl"], $_REQUEST["wl_ref"] ?? null);
        break;
        
    case "getLatestReportResult":
        $WLclass = new WLUtils($mysqli);
        $response = $WLclass->getLatestWLResult($_REQUEST["wl"], $_REQUEST["wl_ref"] ?? null);
        break;
      
    case "refreshNMTable":
        $WLclass = new WLUtils($mysqli, null);
        $response = $WLclass->refreshTable($_REQUEST["name"], $_REQUEST["wl_ref"] ?? null);
        break;
      
    case "fetchSavedTables":       
        $WLclass = new WLUtils($mysqli);
        $response = $WLclass->fetchSavedTables($username, $isAdmin);
        break;
        
    case "fetchWLReport":
        $WLclass = new WLUtils($mysqli);
        $response = $WLclass->fetchReport($_REQUEST["name"]);
        break;
        
    case "clearNMHistory":
        $WLclass = new WLUtils($mysqli);
        $response = $WLclass->clearNMHistory($username, $isAdmin);
        break;

    /**
     * END - watchlist
     */

    case "getPanelsConfiguration":
        $tab = $_REQUEST["tab"];
        $visibility = $_REQUEST["visibility"];
        $response = getPanelsConfiguration($mysqli,$username, $tab, $visibility);
        break;
        
    case "showSearchPanels":
        $response = showSearchPanels($mysqli,$username);
        break;
        
    case "getOverviewConfiguration":
        $response = getOverViewConfiguration($mysqli,$username);
        break;
        
    case "savePanelConfiguration":
        $response = savePanelConfiguration($mysqli,$username);
        break;
        
    case "restorePanels":
        $response = restorePanels($mysqli,$username);
        break;
        
    case "sortPanels":
        $response = sortPanels($mysqli,$username);
        break;
        
    case "saveRedactionMarks":
        $response = SaveRedactionMarks($mysqli);   
        break;
        
    case "getRedactionMarks":
        $response = getRedactionMarks($mysqli, $_REQUEST['docid']);
        break;
        
    case "deleteSavedSearch":
        $name = $_REQUEST['savedSearch'];
        $response = deleteSavedSearch($mysqli, $username, $isAdmin, $name);
        break;
  
    case "getSmartSearch_v2":
        $response = getSmartSearch_v2($mysqli, $_REQUEST["table"] ?? null, $_REQUEST["value"] ?? null, $_REQUEST["limit_tables"] ?? null);
        break;

    //*********TAGS ************
    case "getTagsTree":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->getTagsTree();
        break;
        
    case "addToTagTree":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->addToTagTree($_REQUEST['tagGroup'], $_REQUEST['tagname'] ?? $_REQUEST['tag'] ?? null, $_REQUEST['exclusive']);
        break;

    case "removeFromTagTree":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->removeFromTree($_REQUEST['tagGroup'], $_REQUEST['tagname'] ?? $_REQUEST['tag'] ?? null);
        break;
        
    case "getTagsPerDoc":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->getTagsPerDoc($_REQUEST['docid']);
        break;
        
    case "addTagToDoc":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->insertTag($_REQUEST['docid'], $_REQUEST['tagname'] ?? $_REQUEST['tag'] ?? null, $_REQUEST['tagGroup']);
        break;
        
    case "removeTagFromDoc":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->deleteTags($_REQUEST['tagGroup'], $_REQUEST['docid'], $_REQUEST['tagname'] ?? $_REQUEST['tag'] ?? null);
        break;
        
    case "setTagsForSearch":
        $tag_class = new Tags($mysqli, $username);
        $response = $tag_class->setTagsForSearch($_REQUEST["tags"] ?? null);
        break;
        
   

    //***********************************************************
    //***********************************************************
    //***********************OBS ACTIONS: ***********************
    //***********************************************************
    //***********************************************************
     
    case "listDirectory": //not in V2!
        $response = listDirectory($mysqli, $_REQUEST["folderId"]);
        break;
        
    case "deleteDirectory":  //not in V2!
        $response =  deleteDirectory($mysqli,  $_REQUEST["folderId"]);
        break;
        
    case "tagDocument": //not in V2!
        require_once 'parseUtils.php';
        $tagGroup = filter_input(INPUT_GET, "tagGroup");
        $tag = filter_input(INPUT_GET, "tag");
        $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
        $enable = filter_input(INPUT_GET, "enable", FILTER_VALIDATE_BOOLEAN);
        $response = tagDocument($mysqli, $id, $tag, $enable, $tagGroup, $username);
        break;
        
    case "tagModel":    //not in V2!
        $response = getTagModel($mysqli);
        break;
        
    case "saveTagModel":  //not in V2!
        $response = saveTagModel($mysqli, $_REQUEST["tagModel"]);
        break;
        
    case "getBubbles": //not in V2!
    case "getNetwork": //not in V2!
        $response = getPieData($mysqli, $v2 ?? null);
        break;
        
    case "getCacheDate": //not in V2!
        $response = getDateLastModified($mysqli);
        break;
        
    case "updateStatisticsList": //not in V2!
        $response = updateStatisticsList($mysqli);
        break;
        
    case 'refreshManageEntities':
        require_once 'ManageEntitiesEng.php';
        $response = refreshManageEntities($mysqli, $username, true);
        break; 
        
    case 'refreshOverview':
        $response = refreshOverview($mysqli, $isAdmin, $username);
        break;
        
    case "allGraphsList":  //not in V2!
        $response = allGraphsList($mysqli);
        break;
        
    case "getTrendData":  //not in V2!
        $response = getTrendData($mysqli);
        break;
               
    case "saveTrend": //not implemented in V2!
        $response = saveTrendData($mysqli);
        break;
        
    case "statisticsList": //not in V2!
        $response = statisticsList($mysqli);
        break;
        
    case "searchInstanceData": //not in V2!
        $response = searchInstanceData($mysqli, $_REQUEST);
        break;
        
        
    case "saveRedactedDoc": //not in V2!
        $response = saveRedactedDoc($mysqli, $_REQUEST);
        break;
        
    case "deleteRedactedDoc":  //not in V2!
        $response = deleteRedactedDoc($mysqli, $_REQUEST);
        break;
        
        
    case "removeDocFromRedaction": //not in V2!
        $response = removeDocFromRedaction($mysqli, $_REQUEST["dcid"]);
        break;
        
    case "getDocRedactedId": //not in V2!
        require_once 'parseUtils.php';
        $response = docToRedactedId($mysqli, intval($_REQUEST["dcid"]), $_REQUEST["pageNum"] ?? null, false);
        break;
        
    case "getRedactedDocOriginalId": //not in V2!
        require_once 'parseUtils.php';
        $response = getRedactedDocOriginalId($mysqli, intval($_REQUEST["redactedId"]));
        break;
        
    case "getImageCount": //not in V2!
        require_once 'parseUtils.php';
        $response = getImageCount($_REQUEST["dcid"]);
        break;
        
    case "getSlotData": //not in V2!
        $response = getSlotData($mysqli, $_REQUEST);
        break;
        
    case "getSlotsHirarchy":
        $response = getSlotsHirarchy($mysqli);    
        break;
        
    case "getSlotInfoPerTag":
        $response = getSlotInfoPerTag($mysqli, $username, $_REQUEST['docId'] ?? $_REQUEST['docid'], $_REQUEST['table'],$_REQUEST['tag']);
        break;
        
    case "downloadGraph": //not in V2!
        $response = downloadGraph();
        break;
        
    case "releaseLocked": //not in V2!
        $response = releaseLocked($mysqli);
        break;
        
    case "priorDoc":  //not in V2!
        $response = priorDoc($mysqli, $_REQUEST["docId"]  ?? $_REQUEST["dcid"]);
        break;
        
    case "exportRedactedDocs": //not in V2!
        if (getUserPermission(CAN_EXPORT))
        {
            require_once 'parseUtils.php';
            createRedactionLoadFiles($mysqli);
            $response = "ok";
        }
        else{
            $response = array("error" => "You are not authorized to perform this operation");
        }
        break;
        
    case "getKeywordTables": //not in V2!
        $response = getKeywordTables($mysqli);
        break;
        
    case "getExtraEntityTypesArray": //not in V2!
        $response = getExtraEntityTypesArray();
        break;
        
        
    case "getPastPeriod":  //not in V2!
        require_once 'parseUtils.php';
        $response = getPastPeriod($mysqli, $username);
        break;
        
    case "information": //not in V2!
        require_once 'parseUtils.php';
        require_once 'informationEng.php';
        //Write session data and end session
        session_write_close();
        $gArr = getGeneralInfo($mysqli, $username);
        $iArr = informationPage($mysqli);
        $response = $gArr + $iArr;
        
        break;
        
    case "getGeneralInfo": //not in V2!
        require_once 'parseUtils.php';
        $response = getGeneralInfo($mysqli, $username);
        break;
        
    case "getMangeEntities":  //not in V2!
        require_once 'parseUtils.php';
        $response = getMangeEntities($mysqli, $_REQUEST["searchConcept"],$_REQUEST["name"]);
        break;
        
    case "getTables": //not in V2!
        require_once 'parseUtils.php';
        $response = getTables($mysqli);
        break;
        
    case "getSmartSearch":    //not in V2!
        $response = getSmartSearch($mysqli, $_REQUEST["table"] ?? null, $_REQUEST["value"] ?? null);
        break;
        
    case "searchSmartSearch":  //not in V2!
        $response = applySmartSearch($mysqli, $username, $_REQUEST["searchSmart"] ?? null);
        break;
        
    case "getSearchResults": //not in V2!
        $_REQUEST['skip_include'] = true;
        $id= filter_input(INPUT_GET, "searchid", FILTER_VALIDATE_INT);
        $threshold= filter_input(INPUT_GET, "threshold", FILTER_VALIDATE_INT)?? 0;
        $numberToFetch= filter_input(INPUT_GET, "numberToFetch", FILTER_VALIDATE_INT)?? 100;
        $offset= filter_input(INPUT_GET, "offset", FILTER_VALIDATE_INT)?? 0;
        require_once 'searchEng.php';
        $response = getSearchResults($mysqli, $id, $threshold, $numberToFetch, $offset);
        break;
        
    case "getUserName":  //not in V2!
        $response = $_SESSION['username'] ?? "";
        break;
   
    case "getUserPerms":
        $response = getUserAuth($_REQUEST["username"]);
        break;
    
    case "StatisticPagePie": //not implemented in v2
        require_once 'StatisticPageEng.php';
        $response = getPie($mysqli, true);
        return;
        
    case "getRangeFromNumericTable":
        
        $response = TablesInformation::getRangeFromNumericTable($mysqli, $_REQUEST["table"]);
        break;
        
    case "getSlotDataColumns":
        $response =  TablesInformation::getSlotDataColumns($mysqli, $_REQUEST['concept']);
        break;
        
    case "getTableColumns":
        $response = TablesInformation::getElementsColumns($mysqli, $_REQUEST["table"], $_REQUEST["as_array"] ?? null, $_REQUEST["extra_only"] ?? null);
        break;
        
    case "getDistinctValFromCol":
        $response = TablesInformation::getDistinctValuesFromCol($mysqli, $_REQUEST["table"], $_REQUEST["col"], $_REQUEST["concept"] ?? null);
        break;
        
    case "getDistinctGroupValsFromSlotData":
        $response = getDistinctGroupValsFromSlotData($mysqli, $_REQUEST["concept"] ?? null, $_REQUEST['prefix'] ?? null);
        break;
        
    case "getCaptionsPerSlot":
        $response = getCaptionsPerSlot($mysqli, $_REQUEST['prefix'] ?? null);
        break;
        
    case "getSlotsDetails":
        $response = getSlotsDetails($mysqli, $_REQUEST['section'] ?? null);
        break;
        
    case "isOrgText": //not implemented in v2
        $isOrgText = getSystemSettingsProp($mysqli, "isOrgText");
        $response = $isOrgText;
        break;
        
        
    case "getNlpConfig":
        $response = getNlpConfig($_REQUEST['path']);
        break;

    case "saveFileList":  //not in V2!
        //no response on this action
        $params = get_params($mysqli, $username);
        $time = applySmartSearch($mysqli, $username, $params, true);
        $result = null;
        
    case "fetchMoreSearchResults":   //not in V2!
        $result = fetchMoreSearchResults($mysqli, $username, $v2);
        break;
        
    case "fetchMoreDocuments": //not in V2!
        $result = fetchMoreDocuments($mysqli);
        break;
        
    case "asyncPhpAction": //not in V2!
        $func_name = $_REQUEST['function_name'];
        $func_params = $_REQUEST['func_params'];
        write_to_log("TRACE", "$func_name - asyncPhpAction Action in process");
        $result = $func_name($func_params);
        break;
        
    case "clickThru": //not in V2!
        $result = clickThruFunc($mysqli, $username, $_REQUEST["searchSmart"]);
        break;
        
    case "fetchMoreSearchResults_v2":  //not in V2  - yet!
        $result = fetchMoreSearchResults_v2($mysqli, $username);
        break;
        
    case "clickThru_v2": //not in V2  - yet!
        $result = clickThruFunc_v2($mysqli, $username, $_REQUEST["searchSmart"]);
        break;

        
    case "saveFileList";
    case "fetchMoreSearchResults":
    case "fetchMoreSearchResults_v2":
    case "fetchMoreDocuments":
    case "asyncPhpAction":
    case "clickThru":
    case "clickThru_v2":    
        sqlClose($mysqli, 'mainEng - return functions');
        return $result;
        
     
        //***********************************************************
        //***********************************************************
        //***********************************************************
        //***********************OBS ACTIONS - DONE *****************
        //***********************************************************
        //***********************************************************
        //***********************************************************
        
    default:
        $page = $action . 'Eng.php';
        if ($action == "downloadDocument") {
            $page = "download.php";
            if (empty($_REQUEST["chartName"])){
                $_REQUEST["origFile"] = true;
            }
            if (empty($_REQUEST["dcid"])){
                $_REQUEST["dcid"] = $_REQUEST["id"];
            }
        }
        if (!file_exists($page)){
            $response = array("error" => "Unsupported action: $action");
        }
        else {
            write_to_log("TRACE", "redirecting to $page");
            require_once($page);
            sqlClose($mysqli, 'mainEng - directed page ' .$page);
            return;
        }    
}

$duration = microtime(true) - $start;
write_to_log("INFO", "action:$action  ,username:$username, action start at:$stratTime , action duration:$duration ");
sqlClose($mysqli, 'mainEng - '. $action);

echo json_encode($response);
