<?php

if(!isset($_SESSION)) session_start();

include_once("config.php");
include("loginCheckPoint.php");
include_once("authorizations.php");
require_once("demosettings.php");
include_once("parseUtils.php");
include_once("sqlUtils.php");
require_once 'searchWord.php';
require_once 'slotToCaption.php';
require_once 'write_log.php';


function informationPage($connection){  
    
    $type_sentiment = ""; //nothing
	write_to_log("PERMORMENCE", "informationPage start-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
	global $skipDuplicate;
	$userdetails = getUserDetails();
	$username = $userdetails['Username'];
	$isAdmin = getUserPermission(CAN_SHOW_ALL_USER,$username);

	$query = "SELECT id,per,loc,org,label FROM savedsearch WHERE userName='$username' AND id = ".getLastSavedSearchId($connection, $username);
	$res = sqlQuery($connection,$query);
	if ($res){
		$obj = $res->fetch_object();		
		$searchPerson = $obj->per;
		$searchOrganization = $obj->org;
		$searchPlaces = $obj->loc;
		$savedsearchId = $obj->id;

		$lastSearch = "SELECT docid FROM savedsearchid WHERE id=$savedsearchId";
		
		$arr_t = array();
		$arr_tables = array('person_object', 'organizational_identity', 'place_object');
		$arr_other_tables = array('counted_theatre');
		
		//add values to arr_t
		$arr_t = handleArrTables($connection, $skipDuplicate, $arr_tables, $lastSearch);
		$arr_t_other = handleArrTables($connection, $skipDuplicate, $arr_other_tables, $lastSearch, true);
		$arr_t = array_merge($arr_t, $arr_t_other);
		
		//here we check if the subject is person/org/location 
		//please note that we fetch the relations list from there - added the type at "subject type" 
		//it suppose to get all the alt-names for the search
		$arr_relation = array();
		$arr_slot = array();
		$arr_kb = array();
		$arr_sentiment_p = $arr_sentiment_l = $arr_sentiment_o =array();
		$aggPerArr = $aggOrgArr = $aggPlaceArr = array();
		
		if (strlen($searchPerson) > 1 || $type_sentiment == "person_object"){
		    write_to_log("PERMORMENCE", "handle_persons_arr start-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		    $results = handle_persons_arr($connection, $arr_t, $searchPerson, $type_sentiment,  $username,$isAdmin, $lastSearch);
			$arr_relation = array_merge($arr_relation, $results['arr_relation']);
			$arr_slot = array_merge($arr_slot, $results['arr_slot']);			
			$arr_sentiment_p =  array_merge($arr_sentiment_p, $results['arr_sentiment_p']);
			$aggPerArr = array_merge($aggPerArr, $results['aggPerArr']);
			$arr_kb = array_merge($arr_kb, $results['arr_kb']);	
			write_to_log("PERMORMENCE", "handle_persons_arr end-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		}
		
		if (strlen($searchOrganization) > 1 || $type_sentiment == "organizational_identity"){
		    write_to_log("PERMORMENCE", "handle_org_arr start-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		    $results = handle_org_arr($connection, $arr_t, $searchOrganization, $type_sentiment, $username,$isAdmin, $lastSearch);
		    $arr_relation = array_merge($arr_relation, $results['arr_relation']);
		    $arr_slot = array_merge($arr_slot, $results['arr_slot']);	
		    $arr_sentiment_o =  array_merge($arr_sentiment_o, $results['arr_sentiment_o']);
		    $aggOrgArr = array_merge($aggOrgArr, $results['aggOrgArr']);
		    $arr_kb = array_merge($arr_kb, $results['arr_kb']);
		    write_to_log("PERMORMENCE", "handle_org_arr end-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		}
		
		if (strlen($searchPlaces) > 1 || $type_sentiment == "place_object"){
		    write_to_log("PERMORMENCE", "handle_place_arr start-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		    $results = handle_place_arr($connection, $arr_t, $searchPlaces, $type_sentiment, $username,$isAdmin, $lastSearch);
		    $arr_relation = array_merge($arr_relation, $results['arr_relation']);
		    $arr_slot = array_merge($arr_slot, $results['arr_slot']);  
		    $arr_sentiment_l =  array_merge($arr_sentiment_l, $results['arr_sentiment_l']);
		    $aggPlaceArr = array_merge($aggPlaceArr, $results['aggPlaceArr']);
		    $arr_kb = array_merge($arr_kb, $results['arr_kb']);
		    write_to_log("PERMORMENCE", "handle_place_arr end-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		}

		$response = array();
		
		/////////////////////////////////
		//
		// Add Manage entities BL
		//
		/////////////////////////////////
		write_to_log("PERMORMENCE", "information start manageEntities-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		$response["personCoRef"] = manageEntities($connection, $arr_t['person_object'],"person",$aggPerArr ?? null);
		$response["org"] = manageEntities($connection, $arr_t['organizational_identity'],"org",$aggOrgArr ?? null);
		$response["place"] = manageEntities($connection, $arr_t['place_object'],"place",$aggPlaceArr ?? null);
		write_to_log("PERMORMENCE", "information end manageEntities-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
			
		//$response["search"] = $label;
		//$response["numberDocument"] =  $numberDocument;
		//$response["precentage"] = $precentage;
		$response["theatre"] = $arr_t['counted_theatre'];
		
		//Positive Sentiment
		if (!empty($arr_sentiment_p['pro']) && sizeof($arr_sentiment_p['pro']['person_object']) > 0){
		  $response["pos"]['Persons'] = $arr_sentiment_p['pro']['person_object'];
		}
		if (!empty($arr_sentiment_o['pro']) && sizeof($arr_sentiment_o['pro']['organizational_identity']) > 0){
		  $response["pos"]['Organisations'] = $arr_sentiment_o['pro']['organizational_identity'];
		}
		if (!empty($arr_sentiment_l['pro']) && sizeof($arr_sentiment_l['pro']['place_object']) > 0){
		  $response["pos"]['Places'] = $arr_sentiment_l['pro']['place_object'];
		}
		
		//Negative Sentiment
		if (!empty($arr_sentiment_p['anti']) && sizeof($arr_sentiment_p['anti']['person_object']) > 0){
		  $response["neg"]['Persons'] = $arr_sentiment_p['anti']['person_object'];
		}
		if (!empty($arr_sentiment_o['anti']) && sizeof($arr_sentiment_o['anti']['organizational_identity']) > 0){
		  $response["neg"]['Organisations'] = $arr_sentiment_o['anti']['organizational_identity'];
		}
		if (!empty($arr_sentiment_l['anti']) && sizeof($arr_sentiment_l['anti']['place_object']) > 0){
		  $response["neg"]['Places'] = $arr_sentiment_l['anti']['place_object'];
		}
		
		$response["kbSlots"] = $arr_kb;
		$response["dbSlots"] = $arr_slot;
		$response["relation"] = $arr_relation;
		
		
		write_to_log("PERMORMENCE", "informationPage end-" . date('H:i:s'.substr((string)microtime(), 1, 8)));
		return $response;
	}
}

function handleArrTables($connection, $skipDuplicate, $arr_tables, $lastSearch, $other_tables = false){
    global $hideConceptInstances;
    foreach ($arr_tables as $val){
        $arr_t[$val] = array();
        
        //1 - create inner_sql columns - if it's from other_tables - with value, if from entities - with name + more columns
        $inner_sql_cols = !$other_tables ? " COUNT(DISTINCT docId) AS s_id,$val.name,$val.ontUrl,$val.orgText,SUM($val.occurrences) AS o " :
            "COUNT(VALUE) AS v,value";
        
        //2 - define name/value for the 
        $group_by_str = !$other_tables ? "NAME" : "VALUE";
        $order_by_str = !$other_tables ? "s_id" : "v";
        
        //3 - hidden concepts
        $hiddenInstancesSql = (!empty($hideConceptInstances) && array_key_exists($val, $hideConceptInstances)) ? "  $group_by_str  NOT IN ('" . join("','", $hideConceptInstances[$val]) . "') "
            : " TRUE ";
        
        //4 - inner sql 
        $inner_sql = $skipDuplicate ? 
        "SELECT $inner_sql_cols FROM $val,unique_files WHERE $hiddenInstancesSql AND unique_files.id IN ($lastSearch) AND unique_files.id=$val.docId GROUP BY $group_by_str" :
        "SELECT $inner_sql_cols FROM $val WHERE $hiddenInstancesSql AND docId IN ($lastSearch) GROUP BY $group_by_str ";
               
        //5 - final sql
        $sql = "SELECT t.* FROM ($inner_sql) AS t ORDER BY t.$order_by_str DESC LIMIT 500";
        
        $res = sqlQuery($connection,$sql);
        if (!empty($res))
        {
            while (($row = $res->fetch_object())!=false){
                //if its entity build object like that
                $obj = new stdClass();
                if(!$other_tables){
                    $obj->doc = $row->s_id;
                    $obj->occurrences = $row->o;
                    $obj->name = $row->name;
                    $obj->orgText = ($row->orgText);
                    $arr_t[$val][$row->name] = $obj;
                }
                //if other tables (counted Theathres..)
                else{
                    $obj->occurrences = $row->v;
                    $obj->name = $row->value;
                    $arr_t[$val][$row->value] = $obj;
                }
                
                unset($obj);
            }
        }
    }
 
    return $arr_t;
}

function handle_persons_arr($connection, $arr_t, $searchPerson, $type_sentiment, $username,$isAdmin, $saved_sql){
    $arrPer = array();
    if (strlen($searchPerson) > 1)
        $arrPer = transferSearchToArray($searchPerson,str_replace("_", "-", ucfirst('person_object')));
        if ($type_sentiment == "person_object"){
            if (!in_array($sentiment_string,$arrPer))
                $arrPer[] = $sentiment_string;
        }
        $sentiment = getSentiment($connection, $arrPer,'person_object',$username,$isAdmin, $saved_sql);
        $arr_sentiment_p = $sentiment['res'];
        $aggPerArr = $sentiment['agg'];
        foreach ($arrPer as $v){
            $arr_kb['Persons'][$v] = getSlotKB($v, 'person_object');
            $ret = getSlotD($connection, $v,'person_object', $arr_kb['Persons'][$v], $aggPerArr[$v]);
            if (!empty($ret)){
                $arr_slot['Persons'][$v] = $ret;
            }
            //remove search person from co-ref array
            if (array_key_exists($v,$arr_t['person_object'])){
                unset($arr_t['person_object'][$v]);
            }
            //get relation
            
            $arr_relation['Persons'][$v] = listRelations($connection, "relation", "", "", "", "", $v, "", null, null, true,null, null,$isAdmin,$username, $saved_sql);
        }
        return array('arr_relation'=>$arr_relation, 'arr_slot'=>$arr_slot ?? [], 'arr_sentiment_p'=>$arr_sentiment_p ?? [], 'arr_kb'=>$arr_kb, 'aggPerArr'=>$aggPerArr);
}

function handle_org_arr($connection, $arr_t, $searchOrganization, $type_sentiment, $username,$isAdmin, $saved_sql){
    $arrOrg = array();
    if (strlen($searchOrganization) > 1)
        $arrOrg = transferSearchToArray($searchOrganization,str_replace("_", "-", ucfirst('organizational_identity')));
        if ($type_sentiment == "organizational_identity"){
            if (!in_array($sentiment_string,$arrOrg))
                $arrOrg[] = $sentiment_string;
        }
        $sentiment = getSentiment($connection, $arrOrg,'organizational_identity',$username,$isAdmin, $saved_sql);
        $arr_sentiment_o = $sentiment['res'];
        $aggOrgArr = $sentiment['agg'];
        foreach ($arrOrg as $v){
            if ($v){
                $ret = getSlotKB($v, 'organizational_identity');
                if (!empty($ret))
                    $arr_kb['Organisations'][$v] = $ret;
                    $ret = getSlotD($connection, $v,'organizational_identity', $arr_kb['Organisations'][$v] ?? null, $aggOrgArr[$v] ?? null);
                    if (!empty($ret))
                        $arr_slot['Organisations'][$v] = $ret;
                        //remove search organisation from co-ref array
                        if (array_key_exists($v,$arr_t['organizational_identity']))
                            unset($arr_t['organizational_identity'][$v]);
                            //get relation                                    
                            $arr_relation['organizational_identity'][$v] = listRelations($connection, "relation", "", "", "", "", $v, "",null, null, true,null, null,$isAdmin,$username, $saved_sql);
                            
            }
        }
        return array('arr_relation'=>$arr_relation, 'arr_slot'=>$arr_slot, 'arr_sentiment_o'=>$arr_sentiment_o, 'arr_kb'=>$arr_kb, 'aggOrgArr' => $aggOrgArr);
}

function handle_place_arr($connection, $arr_t, $searchPlaces, $type_sentiment, $username,$isAdmin, $saved_sql){
    $arrPlace = array();
    if (strlen($searchPlaces) > 1)
        $arrPlace = transferSearchToArray($searchPlaces,str_replace("_", "-", ucfirst('place_object')));
     
        $sentiment = getSentiment($connection, $arrPlace,'place_object',$username,$isAdmin, $saved_sql);
        $arr_sentiment_l = $sentiment['res'];
        $aggPlaceArr = $sentiment['agg'];
        foreach ($arrPlace as $v){
            $ret = getSlotKB($v, 'place_object');
            if (!empty($ret))
                $arr_kb['Places'][$v] = $ret;
                $ret = getSlotD($connection, $v,'place_object', $arr_kb['Places'][$v], $aggPlaceArr[$v]);
                if (!empty($ret))
                    $arr_slot['Places'][$v] = $ret;
                    //remove search place from co-ref array
                    if (array_key_exists($v,$arr_t['place_object']))
                        unset($arr_t['place_object'][$v]);
                        //get relation
                        
                        $arr_relation['Places'][$v] = listRelations($connection, "relation", "", "", "", "", $v, "", null, null, true,null, null,$isAdmin,$username, $saved_sql);
        }
        return array('arr_relation'=>$arr_relation,  'arr_slot'=>$arr_slot , 'arr_sentiment_p'=>$arr_sentiment_p, 'arr_kb'=>$arr_kb , 'aggPlaceArr' => $aggPlaceArr);
}

function manageEntities($connection, $arr, $type, $searchArr){
    
    $query = "SELECT name,aggregatedname,aggregatedmanual FROM entitiesmanage WHERE entity='$type'";
    $res = sqlQuery($connection,$query);
    $typeArr = array();
    while (($obj = $res->fetch_object())!=false){
        $e = explode(";",$obj->aggregatedname);
        foreach ($e as $v){
            $typeArr[$v] = $obj->name;
        }
        $e = explode(",",$obj->aggregatedmanual);
        foreach ($e as $v){
            $typeArr[$v] = $obj->name;
        }
    }
    $newArr = array();
    if (sizeof($typeArr) > 0){
        foreach ($arr as $o){
            if (array_key_exists($o->name, $typeArr)){
                if (array_key_exists($typeArr[$o->name], $newArr)){
                    $newArr[$typeArr[$v]]->occurrences += $o->occurrences;
                    $newArr[$typeArr[$v]]->doc += $o->doc;
                }else{
                    $o->name = $typeArr[$o->name];
                    $newArr[$o->name] = $o;
                }
            }else
                $newArr[$o->name] = $o;
        }
    }else
        $newArr = $arr;
        
        //delete itself
        $newSearchArr = array();
        //if (sizeof($typeArr) > 0){
        foreach ((array)$searchArr as $v){
            if (sizeof($typeArr) > 0 && array_key_exists($v, $typeArr)){
                $newSearchArr[$typeArr[$v]] = $typeArr[$v];
                $newSearchArr[strtolower($typeArr[$v])] = strtolower($typeArr[$v]);
            }
            else{
                if(is_array($v)){
                    foreach ($v as $item_in_v){
                        if(empty($item_in_v)){
                            continue;
                        }
                        if(is_array($item_in_v) && isset($item_in_v['data'])){
                            foreach($item_in_v['data'] as $item){
                                $data_json = json_encode($item, true);
                                $newSearchArr[$data_json] = $data_json;
                                $newSearchArr[strtolower($data_json)] = strtolower($data_json);
                            }
                            continue;
                        }
                        $newSearchArr[$item_in_v] = $item_in_v;
                        $newSearchArr[strtolower($item_in_v)] = strtolower($item_in_v);
                    }
                }
                else{
                    $newSearchArr[$v] = $v;
                    $newSearchArr[strtolower($v)] = strtolower($v);
                }
            }
        }
        $resArr = array();
        if (!empty($newSearchArr)){
            foreach ($newArr as $o){
                if (!array_key_exists($o->name,$newSearchArr) && !array_key_exists(strtolower($o->name),$newSearchArr))// && !array_key_exists(strtolower($o->name),strtolower($newSearchArr)))
                    $resArr[$o->name] = $o;
            }
        }else
            $resArr = $newArr;
            //}else
            //	$resArr = $arr;
            
            return sortArrOfObject($resArr,"doc");
}

function sortArrOfObject($arr,$property){
    $nameArr = $returnArr =array();
    foreach ($arr as $k => $o){
        $nameArr[$k] = $o->{$property};
    }
    arsort($nameArr);
    foreach ($nameArr as $k => $v){
        $returnArr[$k] = $arr[$k];
    }
    return $returnArr;
}

function transferSearchToArray($search, $table){
    $arr = array();
    $output = str_replace("&","^",$search);
    $e = explode("^", $output);
    if (sizeof($e) > 1){
        $arr = $e;
    }
    else{
        $arr[] = $search;
    }
    return $arr;
}

function getSentiment($connection, $arr, $table,$isadmin,$username, $saved_sql){
    $aggArr = array();
    $arr_t = array();
    global $entitiesArray;
    foreach ($arr as $val){
        //get smart search
        $v = $connection->real_escape_string($val);
        $sql = "SELECT aggregatedName FROM entitiesmanage WHERE NAME='$v' AND entity='smart'";
        $res = sqlQuery($connection,$sql);
        if (!empty($res)){
            $obj = $res->fetch_object();
            if(!empty($obj)){
                $conceptArr = json_decode($obj->aggregatedName, true);
                if(isset( $conceptArr[$v][$table]["value"][$v])){
                    $esc_val = "'" . implode("','", $conceptArr[$v][$table]["value"][$v]) . "'";
                    $aggArr[$val] = $conceptArr[$v][$table]["value"][$v];
                }
            }
        }else{
            $gArr = getMangeEntities($connection, $entitiesArray[$table], $val, false, true);
            if (sizeof($gArr["rows"]) < 1){
                $gArr["rows"] = $val;
            }
            $first = true;
            foreach ($gArr["rows"] as $v){
                $aggArr[$val][$v] = $v;
                if ($first){
                    $esc_val = "'" . $connection->real_escape_string($v) . "'";
                    $first = false;
                }else
                    $esc_val .= ",'" . $connection->real_escape_string($v) . "'";
            }
        }
        if(!$isadmin){
            $user_sql =  ",files WHERE files.username='$username' AND   files.id = $table.docid";
        }
        else{
            $user_sql = " WHERE TRUE";
        }
        //anti
        $esc_val = $connection->real_escape_string($val);
        $sql = "SELECT anti_concept.value AS v,COUNT($table.id) AS c FROM anti_concept,$table".$user_sql." AND $table.docId=anti_concept.docId AND $table.id=anti_concept.instanceId AND anti_concept.instanceType='$table' AND $table.docId IN ($saved_sql) AND $table.name IN ('$esc_val') AND $table.name IS NOT NULL GROUP BY VALUE ORDER BY c DESC";
        $res = sqlQuery($connection,$sql);
        $arr_anti = array();
        if (!empty($res))
        {
            while (($row = $res->fetch_object())!=false){
                if(!isset($arr_anti[$row->v])){
                    $arr_anti[$row->v] = 0;
                }
                $arr_anti[$row->v] += $row->c;
                write_to_log("DEBUG", "Information - getsentiment function - key - $row->v doesn't exsist on sentimentConceptToGroup Array");
                
            }
        }
        //pro
        $sql = "SELECT pro_concept.value AS v,COUNT($table.id) AS c FROM pro_concept,$table".$user_sql." AND $table.docId=pro_concept.docId AND $table.id=pro_concept.instanceId AND pro_concept.instanceType='$table' AND $table.docId IN ($saved_sql) AND $table.name IN ('$esc_val') AND $table.name IS NOT NULL GROUP BY VALUE ORDER BY c DESC";
        $res = sqlQuery($connection,$sql);
        $arr_pro = array();
        if (!empty($res))
        {
            while (($row = $res->fetch_object())!=false){
                
                if(!isset($arr_pro[$row->v] )){
                    $arr_pro[$row->v]  = 0;
                }
                $arr_pro[$row->v] += $row->c;
                write_to_log("DEBUG", "Information - getsentiment function - key - $row->v doesn't exsist on sentimentConceptToGroup Array");
                
            }
        }
        arsort($arr_anti);
        arsort($arr_pro);
        $arr = array("anti" => $arr_anti, "pro" => $arr_pro);
        foreach ($arr as $s => $a){
            foreach ($a as $k => $v){
                $arr_t[$s][$table][$val][] = array("name" => $k , "doc" => $v);
            }
        }
    }
    
    
    $ret['res'] = $arr_t;
    $ret['agg'] = $aggArr;
    return $ret;
}

?>