<?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_v2($connection, $merged_data, $name = null, $table = null){
    
    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, search_values FROM savedsearch WHERE userName='$username' AND id = ".getLastSavedSearchId($connection, $username);
    $res = sqlQuery($connection,$query);
    if ($res){
        $obj = $res->fetch_object();
        $search_vals = json_decode($obj->search_values, true);
        $savedsearchId = $obj->id;
        
        //if empty - return only names for tabs
        if(empty($name)){
            if(empty($search_vals)){
                return [];
            }
            return getSearchedItems($connection, $search_vals, $merged_data);   
        }
        
        $lastSearch = "SELECT docid FROM savedsearchid WHERE id=$savedsearchId";
        
        //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 = array();
        $aggPerArr = $aggOrgArr = $aggPlaceArr = array();

        $results = handle_arr($connection, $name,  $table, $username,$isAdmin, $lastSearch);
//         $arr_relation = array_merge($arr_relation, $results['arr_relation']);
        $arr_slot = array_merge($arr_slot, $results['arr_slot']);
        $arr_sentiment =  array_merge($arr_sentiment, $results['arr_sentiment']);
        $aggPerArr = array_merge($aggPerArr, $results['aggPerArr']);
        $arr_kb = array_merge($arr_kb, $results['arr_kb']);

        $response = array();
        
        $response["pos"] = $arr_sentiment['pro'];
        $response["neg"] = $arr_sentiment['anti'];

        $pos_count = count($response["pos"]);
        $neg_count = count($response["neg"]);
        $total_sentiment = $pos_count + $neg_count;
        if($total_sentiment > 0){
            $response["posPercentage"] = ($pos_count / $total_sentiment) * 100;
            $response["negPercentage"] = ($neg_count / $total_sentiment) * 100;
        }

        $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 getSearchedItems($connection, $elements_arr, $merged_data){
    $results = array();
    foreach($elements_arr as $table=>$value){
        $pretty_name = TablesInformation::getConceptPresentName($table);
        $full_results[$pretty_name] = [];
        foreach($value as $inner_val){
            $inner_arr = transferSearchToArray($inner_val);
            foreach($inner_arr as $entity){
                $full_results[$pretty_name][] = $entity;
            }
        }
        $full_results[$pretty_name] = implode("^", $full_results[$pretty_name]);
        
        $extra_cols = getExtraColumns($connection);
        
        if(!(array_key_exists($pretty_name,$merged_data) || array_key_exists($table,$merged_data)) && 
            !array_key_exists($pretty_name, $extra_cols) &&
            !array_key_exists($table, $extra_cols)){
            write_to_log("TRACE", "$table - is under restrict_entity_info_arr");     
            continue;
        }
        foreach($value as $inner_val){
            $inner_arr = transferSearchToArray($inner_val);
            foreach($inner_arr as $entity){
                $results[] = array("type" => $table, "name" => $entity);     
            }
        }
    }
    
    
    return ["full" => $full_results, "filtered" => $results];
}

function handle_arr($connection, $name, $table, $username,$isAdmin, $saved_sql){
    if($table == 'organizational_identity'){
        $arrOrg = transferSearchToArray($name);
        $sentiment = getSentiment_v2($connection, $arrOrg,'organizational_identity',$username,$isAdmin, $saved_sql);      
    }
    elseif($table == 'place_object'){
        $arrPlace = transferSearchToArray($name);
        $sentiment = getSentiment_v2($connection, $arrPlace,'place_object',$username,$isAdmin, $saved_sql);   
    }
    else{
        $sentiment = getSentiment_v2($connection, $name, $table, $username,$isAdmin, $saved_sql);
    }

    $arr_sentiment = $sentiment['res'];
    $aggPerArr = $sentiment['agg'];
    $arr_kb = getSlotKB($name, $table);
    $arr_slot = getSlotD_v2($connection, $name, $table, $arr_kb[$name] ?? null, $aggPerArr[$name] ?? null);
    
//     $arr_relation[] = listRelations($connection, "relation_v2", $table, "", "", "", $name, "", null, null, true,null, null,$isAdmin,$username, $saved_sql);
    
    return array('arr_slot'=>$arr_slot ?? null, 'arr_sentiment'=>$arr_sentiment ?? [], 'arr_kb'=>$arr_kb, 'aggPerArr'=>$aggPerArr);
}


function getSentiment_v2($connection, $val, $table,$isadmin,$username, $saved_sql){
    require_once 'parseUtils.php';
    $aggArr = array();
    $arr_t = array();
    global $entitiesArray;
    //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 name,COUNT($table.id) AS amount 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 amount DESC";
    $res = sqlQuery($connection,$sql);
    $arr = $res->fetch_all(MYSQLI_ASSOC);
    $arr_anti = getTreeArr($connection,  $arr);
    
    //pro
    $sql = "SELECT pro_concept.value AS name,COUNT($table.id) AS amount 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 amount DESC";
    $res = sqlQuery($connection,$sql);
    $arr = $res->fetch_all(MYSQLI_ASSOC);
    $arr_pro = getTreeArr($connection,  $arr);
    
    $arr_t = array("anti" => $arr_anti, "pro" => $arr_pro);
        
    $ret['res'] = $arr_t;
    $ret['agg'] = $aggArr;
    return $ret;
}

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

?>