<?php

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

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

//require_once("sparql.php");
//include_once 'searchWord.php';


$response["rows"] = array();
$userdetails = getUserDetails();
$username = $userdetails['Username'];

if(empty($mysqli)){
    $mysql_local = true;
    $mysqli = sqlCreateConnection("manageEntities");
}


//Write session data and end session
session_write_close();

if (isset($_REQUEST["updateData"]) && $_REQUEST["updateData"]){
    $response = deleteEntity($mysqli, $username);
    $response = insertData($mysqli, $username);
	echo json_encode($response);
}
elseif (isset($_REQUEST["searchConcept"]) && $_REQUEST["searchConcept"]){
	$response = getMangeEntities($mysqli, $_REQUEST["searchConcept"],$_REQUEST["name"],true);	
	ob_clean();
	echo json_encode($response);
}
elseif (isset($_REQUEST["insertData"]) && $_REQUEST["insertData"]){
    $response = insertData($mysqli, $username);
	echo json_encode($response);
}else if (isset($_REQUEST["deleteEntity"]) && $_REQUEST["deleteEntity"]){
	$response = deleteEntity($mysqli, $username);
	echo json_encode($response);
}
else if (isset($_REQUEST["getData"]) && $_REQUEST["getData"]){
  	$sql_user = "";//" AND username = '$username'";
	$sql = "SELECT * FROM entitiesmanage WHERE entity<>\"smart\" $sql_user";
	$res = sqlQuery($mysqli, $sql);
	if (!empty($res)){
		while ($row = $res->fetch_object()) {
			$e = array_filter(explode(";",$row->aggregatedName));
			$m = array_filter(explode(";",$row->aggregatedManual));

			$response["rows"][] = array("Entity" => $row->entity, "Name" => $row->name, "Aggregated" => $e,"Manual"=>$m);
		}
	}
	ob_clean();
	echo json_encode($response);
}
else if (isset($_REQUEST["getSlot"]) && $_REQUEST["getSlot"]){
	$entitiesType = $_REQUEST["concept"];
	$name = $mysqli->real_escape_string($_REQUEST["name"]);

	if ($entitiesType == "person"){
		$concept = "person_object";
	}elseif ($entitiesType == "org"){
		$concept = "organizational_identity";
	}

	$db_slot = array();
		$sql = "SELECT DISTINCT ";
		$first = true;
		foreach ($slotToCaption as $k => $v){
			$e = str_replace("-", "_", $k);
			if ($first){
				$sql .= "$e";
				$first = false;
			}
			else{
				$sql .= ",$e";
			}
		}
		$sql .= " FROM slotdata WHERE conceptName=\"$concept\" AND caption LIKE LOWER(\"$name\")";
		$res = sqlQuery($mysqli, $sql);
		if(!empty($res)){
			while($row = $res->fetch_object()){
				foreach ($slotToCaption as $k => $v){
					$k = str_replace("-", "_", $k);
					if ($row->$k != null){
						if (array_key_exists($v, $db_slot)){
							if (strpos($db_slot[$v], $row->$k) === false)
								$db_slot[$v] .= ", " . $row->$k;
						}else{
							$db_slot[$v] = $row->$k;
						}
					}
				}

			}
		}
	
	foreach ($db_slot as $k => $v){
		$response["rows"][] = array("slot" => $k, "value" => $v);
	}
	ob_clean();
	echo json_encode($response);
}
if(!empty($mysql_local)){
    sqlClose($mysqli, 'manageEntities');
}

//**************************************************************
//**************************************************************
//****************End of flow - start of functions**************
//**************************************************************
//**************************************************************
/**
 * insertData - main inserting entities
 */
function insertData($mysqli, $username){
	$entitiesName = $mysqli->real_escape_string($_REQUEST["name"]) ?? null;
	$data = json_decode($_REQUEST["EntitiesName"]) ?? null;
    	
	$sum = $_REQUEST["sum"] ?? null;
	$entitiesType = $_REQUEST["concept"] ?? null;
	$manualNames = ""; //null for now 
	$first = true;
	$aggregatedName = "";
	$entitites_str = "";
	$previos_agg = false;
	
	//check if we already has same name and type for this user
	$sql = "SELECT * from entitiesmanage WHERE name='$entitiesName' AND entity='$entitiesType' AND username='$username'" ;
	$res = $mysqli->query($sql);
	if (!empty($res) && $row = $res->fetch_object()) {
	    $entity_ind = $row->id;
	    $type = $row->entity;
	    $agg_names_prev = $row->aggregatedName;
	    $previos_agg = true;
	    $prev_id = $row->id;
	    $aggregatedName = $agg_names_prev;
	}
	
	if(!empty($data))
	foreach ($data as $v){
	    //update the table (agg_names) and return the id of the entity in that table
		if ($first){
		    if($previos_agg && !empty($aggregatedName)){
		        $aggregatedName .= ";";
		    }
			$first = false;
			$aggregatedName .= $mysqli->real_escape_string($v);
			$entitites_str  .= "'".$mysqli->real_escape_string($v) ."'";
		}else{
			$aggregatedName .= ";" . $mysqli->real_escape_string($v);
			$entitites_str  .= ",'".$mysqli->real_escape_string($v) ."'";
		}
	}
	
	//updates the entitiy agg name
	updateEntityTable($mysqli, $entitites_str, $entitiesType, $entitiesName);
	
	if ($entitiesType == "org"){
		$sum = count(getEntitiesManage($entitiesName,$entitiesType,"organizational_identity",$mysqli));
	}else{
		$sum = is_array($entitiesName) ? count($entitiesName) : null;
	}
	if (empty($sum)){
		$sum = 0;
	}

	if($previos_agg){
	    $aggregatedName = $mysqli->real_escape_string($aggregatedName);
	    $sql = "UPDATE entitiesmanage SET aggregatedName = '$aggregatedName' WHERE id='$prev_id'";
	}
	else{
        	$sql = "INSERT INTO entitiesmanage (entity,NAME,aggregatedName,sumPossible,aggregatedManual, username)
        	VALUES (\"$entitiesType\",\"$entitiesName\",\"$aggregatedName\",$sum,'$manualNames', '$username')";
	}
	$res = sqlQuery($mysqli,$sql);
	
	$curr_id = -1;
	$sql_id ="SELECT LAST_INSERT_ID() as id;";
	$res_id = sqlQuery($mysqli,$sql_id);
	$row = $res_id->fetch_object();
	if(!empty($row)){
	    $curr_id = intval($row->id);
	}
    
	$response['status'] = "ok";
	
	CacheEng::refreshCache($mysqli);
	
	return $response;
}

/**
 * updateEntityTable - updating the relevant  tabe (of the entity) with the new values
 */
function updateEntityTable($mysqli, $entitites_str, $entitiesType, $entitiesName){
    require_once 'v2'.DIRECTORY_SEPARATOR.'mainEng_funcs_v2.php';
    global $entitiesTypeToTable;
  
    $concept_id_arr = getConceptsIds($mysqli, false, $entitiesTypeToTable[$entitiesType] ?? $entitiesType);
    $concept_id = $concept_id_arr[0]['id'];

    $entitiesName = $mysqli->real_escape_string($entitiesName);
    $sql = "UPDATE all_concepts_table SET names_agg = '$entitiesName' WHERE concept_type = $concept_id AND name_version IN ($entitites_str)";
    $res = sqlQuery($mysqli,$sql);
    return $res;
}

/**
 * agg_names_maker -creates the relevant json for the names_agg to insert the table
 */
function agg_names_maker($mysqli, $entitiesName, $name, $orgText, $names_agg){
    //convert the json to array
    $names_agg_arr = json_decode($names_agg, true);
    
    //if the value hasnt been configured yet - assign defaults for later fallback
    if(empty($names_agg_arr)){
        $names_agg_arr['original_name'] = $mysqli->real_escape_string($name);
        $names_agg_arr['original_text'] = ($orgText);
    }
    
    //assign the new value for the current user
    $names_agg_arr[$_SESSION['username']] = $mysqli->real_escape_string($entitiesName);
    
    
    return $names_agg_arr;
}

/**
 * deleteEntity - deletes the entity from entitiesmanage table and from the relevant names_agg from the table
 */
function deleteEntity($mysqli, $username){
	$name = $mysqli->real_escape_string($_REQUEST["name"]);
	$sql = "SELECT entity,id from entitiesmanage WHERE name='$name'" ;
	$res = sqlQuery($mysqli, $sql);
	if (!empty($res) && $row = $res->fetch_object()) {
	    $entity_ind = $row->id;
	    $type = $row->entity;
	}
	else{
	    //if it doesnt exists return false;
	    return false;
	}
	//remove the agg names from the entity table	
	remove_aggEntity($mysqli, $_SESSION['username'], $name, $type); 

	//delete from entitiesmanage
	$sql = "DELETE FROM entitiesmanage WHERE id=$entity_ind" ;
	$res = sqlQuery($mysqli,$sql);
	ob_clean();
	$response['status'] = "ok";
	CacheEng::refreshPie($mysqli, $username, $type);
	return $response;
}

function remove_aggEntity($mysqli, $username, $name, $type){
    global $entitiesTypeToTable;
    $sql = "UPDATE $entitiesTypeToTable[$type]  SET names_agg = null WHERE names_agg ='$name'" ;
    sqlQuery($mysqli,$sql);
}

function getAggFromName($mysqli, $username, $name, $type = null){
    global $manageEntitiesArray;
    $type = $manageEntitiesArray[$type] ?? $type;
    $type_sql = empty($type) ? " TRUE " : " entity=\"$type\" ";
    $name = $mysqli->real_escape_string($name);
    $sql = "SELECT aggregatedName FROM entitiesmanage WHERE name=\"$name\" AND $type_sql AND username=\"$username\"" ;
    $res = sqlQuery($mysqli,$sql);
    if (!empty($res) && $row = $res->fetch_object()) {
        $response = explode(';', $row->aggregatedName);
        foreach($response as &$element){
            $element = $mysqli->real_escape_string($element);
        }
        return $response;
    }
    else{
        //if it doesnt exists return false;
        return false;
    }
}

/**
 * cross entity 
 * 
 */

function crossEntity($mysqli, $username, $isAdmin, $entity, $source_table, $dest_table, $duplicateRows = false){
    require_once 'globalArr.php';
    global $entitiesTypeToTable, $group_trend_table;
    $isOrgText = getSystemSettingsProp($mysqli, "isOrgText");
    $extraColumns = getExtraColumns($mysqli);
    
    $col_version = $isOrgText ? "orgText" : "name";
    $return_val = false;
   
    $entity_txt = $entity["label"] ?? $entity;
    $entity_txt = $mysqli->real_escape_string($entity_txt);
    
    if(!$isAdmin){
        return ['error'=> "crossentity can be perform by admins only"];
    }
    
    //check if it's reset command
    if($dest_table == 'reset'){
        return reset_cross_entity($mysqli, $username, $isAdmin, $entity, $source_table);     
    }
    
    //check if it's hide command
    if($dest_table == 'hide'){
        return hide_cross_entity($mysqli, $username, $isAdmin, $entity, $source_table);
    }
    
    //check if the source_table/dest_table came as title and not tables name
    $source_table = strtolower($source_table);
    if(array_key_exists($source_table, $entitiesTypeToTable)){
        $source_table = $entitiesTypeToTable[$source_table];
    }
  
    //fetch the table actual name
    $panels = getPanelsConfiguration($mysqli, $username, "dashboard", "1");

    foreach($panels['panelsConfiguration'] as $key=>$arr){
        if(strtolower(trim($arr["name"])) == strtolower(trim($dest_table))){
            $dest_table = $arr["entity"];
            break;
        }
    }
    
    if($source_table === $dest_table){
        return "source and dest tables are the same";
    }
    $dest_id = -1;
    $source_id = -1;
      
    //fetch the source entity index
    $source_index_sql = "SELECT id FROM concepts_indexes WHERE concept = \"$source_table\"";
    $source_index_res = sqlQuery($mysqli, $source_index_sql);
    if ($source_row = $source_index_res->fetch_object()){
        $source_id = $source_row->id;
    }
  
    
    //fetch the dest entity index
    $dest_index_sql = "SELECT id FROM concepts_indexes WHERE concept = \"$dest_table\"";
    $dest_index_res = sqlQuery($mysqli, $dest_index_sql);
    
    if ($dest_row = $dest_index_res->fetch_object()){
        $dest_id = $dest_row->id;
    }
    
    
    if(!empty($dest_id)){
        //for merge trends - duplicate the rows + use of metadata/extra-column
        if($duplicateRows){
            //if table is in extra-columns (value and not name_version)
            if(preg_grep("/$source_table/i", $extraColumns)){
                $set_sql = "INSERT INTO all_concepts_table (id, username, docid, name_version,concept_type, concept_type_source)
                         (SELECT 0,\"$username\",docid,VALUE,$dest_id,0  AS id FROM $source_table  WHERE VALUE =  \"$entity_txt\")";
            }
            else{
                $set_sql  = "INSERT INTO all_concepts_table 
                            (SELECT 0, docid,name_version,names_agg,clean_name,ontName,ontUrl,docKey,DATE,MODIFIER,country,province,city,anti,pro,\"$username\",occurrences,positive,
                            negative, orgText_version, TYPE, $dest_id, concept_type_source FROM all_concepts_table  WHERE name_version = \"$entity_txt\"
                             AND concept_type = $source_id AND  TRUE )";
            }
            $set_res = sqlQuery($mysqli, $set_sql);
        }
        //Only for dashboard cross entity (without inserting but updating concept type)
        else{
            $set_sql = "UPDATE all_concepts_table SET concept_type = $dest_id WHERE ". $col_version ."_version = \"$entity_txt\"
                AND concept_type = $source_id";
            $set_res = sqlQuery($mysqli, $set_sql);
            if(!empty($set_res)){
                CacheEng::updatePanels($mysqli, $username, $source_table, $entity, $dest_table);    
                
                //insert the cross entity data to the table (for background process)
                $crossEntitiesSql = "INSERT INTO crossentities (entity,orgConcept,destConcept) VALUES(\"$entity_txt\", \"$source_table\", \"$dest_table\") ON DUPLICATE KEY UPDATE entity=entity";
                $set_res = sqlQuery($mysqli, $crossEntitiesSql);
                
                $return_val = array("success"=> "Cross Entity sucess");
            }
        }
    }
 
    return $return_val;
    
}

function hide_entities($mysqli, $username, $isAdmin){
    $requestPayload =file_get_contents('php://input');
    $arr = json_decode($requestPayload, true);
    $entities = $arr['entities'];
    $source_table = $arr['source_table'];
    foreach($entities as $entity){
        hide_cross_entity($mysqli, $username, $isAdmin, $entity, $source_table);
    }
    return true;
}

function hide_cross_entity($mysqli, $username, $isAdmin, $entity, $source_table){
    $sql_user = $isAdmin ? " TRUE " : " username=\"$username\"";
    $entity_label = is_array($entity) ? $entity['label'] : $entity;

    $escaped = $mysqli->real_escape_string($entity_label);
    
    //only if its under a concept
    if(TablesInformation::isColumnExists($mysqli, $source_table, "name_version")){
        $set_sql = "UPDATE all_concepts_table SET concept_type =  -1
        WHERE name_version = '$escaped' AND $sql_user";
        $set_res = sqlQuery($mysqli, $set_sql);
        if(is_array($entity)){
            CacheEng::updatePanels($mysqli, $username, $source_table, $entity);
        }
    }
    //update entitiesManage - ignore section
    $sql = "INSERT INTO hide_entities (entity, names)
    VALUES ('$source_table', '$escaped')
            ON DUPLICATE KEY UPDATE
            names = CONCAT(names, '|$escaped')";

    $set_res = sqlQuery($mysqli, $sql);
    
    if(!empty($set_res)){
        $return_val = array("success"=> "Cross Entity reset");
    }
    return $return_val;
}

function  reset_cross_entity($mysqli, $username, $isAdmin, $entity, $source_table, $group = false){
    global $group_trend_table;
    $return_val = false;
    $entity_txt = $entity["label"] ?? $entity;
    $sql_user = $isAdmin ? " TRUE " : " username=\"$username\"";

    $source_index_sql = "SELECT id FROM concepts_indexes WHERE concept = \"$source_table\"";
    $source_index_res = sqlQuery($mysqli, $source_index_sql);
    if ($source_row = $source_index_res->fetch_object()){
        $source_id = $source_row->id;
    }
     
    $dest_sql = "SELECT concept_type_source FROM all_concepts_table WHERE concept_type=$source_id AND name_version=\"$entity_txt\" AND $sql_user LIMIT 1 ";
    $dest_res = sqlQuery($mysqli, $dest_sql);
    if ($dest_row = $dest_res->fetch_object()){
        $dest_id = $dest_row->concept_type_source;
        
        $sql_dest_table = "SELECT concept FROM concepts_indexes WHERE id = $dest_id ";
        $dest_table_res = sqlQuery($mysqli, $sql_dest_table);
        if ($dest_table_row = $dest_table_res->fetch_object()){
            $dest_table = $dest_table_row->concept;
        }
    }
    
    if($group){
        $set_sql = "DELETE FROM all_concepts_table WHERE concept_type = $source_id AND username=\"$username\"";
    }
    else{
        $set_sql = "UPDATE all_concepts_table SET concept_type =  $dest_id
                    WHERE name_version = \"$entity_txt\" AND concept_type = $source_id AND $sql_user";
    }

    $set_res = sqlQuery($mysqli, $set_sql);
    
    //remove from crossentities the entity
    $ce_sql = "DELETE FROM crossentities  
             WHERE entity = \"$entity_txt\" AND orgConcept = \"$dest_table\" AND destConcept = \"$source_table\"";// AND username=\"$username\"";
    $ce_res = sqlQuery($mysqli, $ce_sql);
    
    if(!empty($set_res) && $source_table !== $group_trend_table){
        CacheEng::updatePanels($mysqli, $username, $source_table, $entity, $dest_table);
        $return_val = array("success"=> "Cross Entity reset");
    }
    return $return_val;
}

function reset_all_cross_entity($mysqli, $username, $isAdmin){
    require_once 'globalArr.php';
    global $entitiesTypeToTable;
    $sql_user = $isAdmin ? " TRUE " : " username=\"$username\"";

    //update the allconcepttable to have matched concept_type & concept_type_source
    $set_sql = "UPDATE all_concepts_table SET concept_type = concept_type_source
    WHERE  $sql_user";
    $set_res = sqlQuery($mysqli, $set_sql);
    
    //delete all crossentities data for that username
    $ce_sql = "DELETE FROM crossentities";// WHERE username=\"$username\"";
    $set_res = sqlQuery($mysqli, $ce_sql);
    
    CacheEng::refreshCache($mysqli, $username);
    
    return !empty($set_res) ? array("success"=> "Cross Entity all reset") : false;

}

/**
 * redo the manage entities
 * @param unknown $mysqli
 * @param unknown $username
 */
function refreshManageEntities($mysqli, $refresh_panel = false){
    session_write_close();
    
    $response = true;
    //get the manage ids
    $sql = "SELECT * from entitiesmanage WHERE entity<>\"smart\" ";//WHERE username='$username'" ;
    $res = $mysqli->query($sql);
    while ($obj = $res->fetch_object()){
        $manageEntities[] = $obj;
    }
    //updates the entitiy agg name
    foreach($manageEntities as $m_element){
        $entitiesType = $m_element->entity;
        $entitiesName = $m_element->name;
        $entities = explode(';', $m_element->aggregatedName);
        $entitites_str = "";
        $first = true;
        foreach($entities as $v){
            if ($first){
                $first = false;
                $entitites_str  .= "'".$mysqli->real_escape_string($v) ."'";
            }else{
                $entitites_str  .= ",'".$mysqli->real_escape_string($v) ."'";
            }
        }
        $res = updateEntityTable($mysqli, $entitites_str, $entitiesType, $entitiesName);
        if($refresh_panel){
            CacheEng::refreshPie($mysqli, $username, $entitiesType);
        }
        if(empty($res)){
            $response = false;
        }
    }
    return $response;
}


//ob_clean();
//echo json_encode($response)

?>
