<?php
require_once 'settings.php';
require_once 'StatisticPageEng.php';
require_once 'proSentPageEng.php';
class ReportGenerator
{

    private $days; //how many days to look back
    private $savedSearches = []; //savedsearch to focus on
    private $concepts = []; //which concepts to present and search
    private $metadata = []; //which concepts to present and search
    private $mysqli;
    private $username;
    private $final_response = [];
    private $date_sql;
    private $timeFrame;
    private $start;
    private $now;
    private $analytics_obj;
    
    function __construct($mysqli, $username){
        $this->mysqli = $mysqli;
        $this->username = $username;
        $settings_class =  new Settings($mysqli, $username);
        $this->analytics_obj = new AnalyticsClass($mysqli, null, null, $username, 50);
        
        
        $response =  $settings_class->getReportSettings();        
        $this->savedSearches = $response["savedSearches"];
        $this->concepts = $response["concepts"];
        $this->metadata = $response["metadata"];
        $this->days = $response["days"];
        $this->handleDates();
        
        $_REQUEST["pastPeriod"] = $this->days;
        $_REQUEST["slices"] = 10;
        $_REQUEST["skip_echo"] = true;
        $_REQUEST["skip_include"] = true;

    }
     
    /**
     * generateReport - main function
     */
    function generateReport(){
        //A - first - get mentions (get pie of all concepts)
        $this->getPies("Mentions");
        foreach($this->savedSearches as $ss_name){   
            $ss_name = $ss_name['savedSearch'];      
            $this->final_response[$ss_name] = [];
            
            //B - search
            write_to_log("INFO", "Searching ".$ss_name);
            $this->search($ss_name);    
            write_to_log("INFO", "Done Searching ".$ss_name);
            
            //C - save search to files
            write_to_log("INFO", "Saving search ".$ss_name);  
            $lastSearchUnique = $this->saveSearchToFiles(); //YOU MUST WORK WITH THIS SS - last search was already deleted in the savesearchtofiles
            write_to_log("INFO", "Done saving search ".$ss_name);
            
            //D - get Trend Data
            write_to_log("INFO", "Trend data ".$ss_name);      
            $this->final_response[$ss_name]["trendData"] = $this->getTrendData($lastSearchUnique);
            write_to_log("INFO", "Done Trend data ".$ss_name);
            
            //E $lastSearchUnique
            write_to_log("INFO", "wordCloud data ".$ss_name);       
            $this->final_response[$ss_name]['wordCloud'] = $this->getWordCloud($lastSearchUnique);
            write_to_log("INFO", "Done wordCloud data ".$ss_name);
            
            //H - get pies for savedSearch
            $this->getPies($ss_name);       
        }    
        return $this->final_response;
    }
    
    /**
     * 
     */
    function handleDates(){
        $this->start = date('Y-m-d h:i:s', strtotime("-$this->days days"));
        $this->now = date('Y-m-d h:i:s');
        $this->timeFrame = "$this->start AND $this->now";
        $this->start = date('Y-m-d', strtotime("-$this->days days"));
        $this->now = date('Y-m-d');
    }

    /**
     * 
     * @param unknown $ss_name
     */
    function search($ss_name){ 
        $searchSmart[] = ["regular" => ["searchSavesearch"=> $ss_name]];
       // $searchSmart[] = ["regular" => ["DateSearch"=> $this->timeFrame]];
        $params = json_encode($searchSmart,true);
        
        $res = getDetailsForSmartSearch_v2($this->mysqli, $this->username, $params);  
        search($this->mysqli, null, $res["searchParameters"], $res["entityParmetersArr"], $res["tableAndCaption"], $params);
        
    }
    
    /**
     * 
     * @return string
     */
    function saveSearchToFiles(){
        //B - save the unique savedsearch to files
        $lastSearchUnique = 'lastsearch' . strval(time());
        saveSearchToFiles($this->mysqli, $lastSearchUnique);
        $_REQUEST["savedsearch"] = $lastSearchUnique;
        
        return $lastSearchUnique;
    }
    
    /**
     * 
     * @param unknown $results_key
     */
    function getPies($results_key){
        //A - get pie on the selected Concepts
        foreach($this->concepts as $concept) {
            
            $_REQUEST["table"] = $concept["concept"];
            $this->final_response[$results_key][$concept["concept"]] = getPie($this->mysqli, true);
        }
        //B - get pie on the selected metadata
        foreach($this->metadata as $md) {
            
            $_REQUEST["table"] = $md["label"];
            $results_key = $results_key == 'Mentions' ? $results_key." - Metadata" : $results_key;
            $this->final_response[$results_key][$md["label"]] = getPie($this->mysqli, true);
        }
    }
    
    /**
     * 
     * @return boolean[]|unknown[]|array[]|string[]|NULL[]|number[]|NULL[][]
     */
    function getTrendData($lastSearchUnique){    

        $_REQUEST["v2"] = "true";
        $_REQUEST["Action"] = "proSentPageEng";
        $_REQUEST["TemplateName"] = "proSentResults";
        $_REQUEST["asAvg"] = "true";
        $_REQUEST["collapse"] = "true";
        $_REQUEST["columnNum"] = "20";
        $_REQUEST["entitiesSelection"] = "saved_search";
        $_REQUEST["freeTextInput"] = "Saved Search";
        $_REQUEST["intervalType"] = "all";
        $_REQUEST["isDateRangeLimitedToMentions"] = "true";
        $_REQUEST["topBannerDisplay"] = "none";
        $_REQUEST["docs_n_occ"] = "true";
        $_REQUEST["fromDate"] = $this->start;
        $_REQUEST["skip_echo"] = true;
        $_REQUEST["savedsearch"] = $lastSearchUnique;
        $res =  getTrend($this->mysqli, true, null, null);
        unset($_REQUEST["freeTextInput"]); //TODO: use something else and not request 
        
        
        return $res;
        
    }
    
    /**
     *
     * @param unknown $lastSearchUnique
     * @return unknown[][]|mixed[][]
     */
    function getWordCloud($lastSearchUnique){
        $res =
        $this->analytics_obj->generateKeywords($this->mysqli, "text","Corpus", "Terms",
            $lastSearchUnique, 40,  "", true);
        $response = [];
        foreach($res["all"] as $label=>$data){
            $response[] = ["label" => $label, "count"=>$data["c"], "type"=>$data["t"]];
        }
        return $response;
    }
}