<?php

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


/**
 * deleteEntity - deletes the entity from entitiesmanage table and from the relevant names_agg from the table
 */
function deleteEntity_v2($mysqli, $name, $tag = null){
	$tag = $mysqli->real_escape_string($tag);
	$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_v2($mysqli, $_SESSION['username'], $name, $type, $tag);
	
	//delete only tag from manageEntities
	if(!empty($tag)){
	    $agg_entities = "SELECT aggregatedName FROM entitiesmanage WHERE id=$entity_ind";
	    $res = sqlQuery($mysqli, $agg_entities);
	    if (!empty($res) && $row = $res->fetch_object()) {
	        $entities = $row->aggregatedName;
	        $entities_arr = explode(';', $entities);
	        if (($key = array_search($tag, $entities_arr)) !== false) {
	            unset($entities_arr[$key]);
	        }
	        $entities = implode(';', $entities_arr);
	        $agg_entities = "UPDATE entitiesmanage SET aggregatedName='$entities' WHERE id=$entity_ind";
	        $res = sqlQuery($mysqli, $agg_entities);
	    }
	    
	}
	//delete entire manage entities
	else{
	    //delete from entitiesmanage
	    $sql = "DELETE FROM entitiesmanage WHERE id=$entity_ind" ;
	}
	$res = sqlQuery($mysqli,$sql);
	
	//delete from relations table
	removeRelationsData($mysqli, $_SESSION['username'], $name, $type, $tag); 
	
	ob_clean();
	$response['status'] = "ok";
	return $response;
}



function remove_aggEntity_v2($mysqli, $username, $name, $type, $tag = null){
    global $entitiesTypeToTable;
    $table_name = $entitiesTypeToTable[$type] ?? 'all_concepts_table';
    $sql = "UPDATE $table_name SET names_agg = null WHERE names_agg ='$name'" ;
    if(!empty($tag)){
        $sql .= " AND name_version = '$tag'";
    }
    sqlQuery($mysqli,$sql);
}

function getManageEntities($mysqli, $username, $isAdmin){
    $sql_user = $isAdmin  ? " TRUE " : "  username = '$username'";
    $sql = "SELECT * FROM entitiesmanage WHERE entity<>\"smart\" AND $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" => array_values($e),"Manual"=>$m);
        }
    }
    ob_clean();
    return $response;
}

function insertData_v2($mysqli, $username, $data){
    require_once 'ManageEntitiesEng.php';
    global $manageEntitiesArray;

    
    
    $entitiesName = $mysqli->real_escape_string($data["name"]) ?? null;
    
    $entitiesType = $data["concept"] ?? null;
    
    if(array_key_exists($entitiesType, $manageEntitiesArray)){
        $entitiesType = $manageEntitiesArray[$entitiesType];
    }
    $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;
    }
    $entities = $data["Entities"];
    if(!empty($entities))
        foreach ($entities 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);
    
    /**
     * updates relations
     */
    updateRelations($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::refreshPie($mysqli, $username, $entitiesType);
    
    return $response;
}

/**
 * update the relations table with the new agg name
 * @param unknown $mysqli
 * @param unknown $entitites_str
 * @param unknown $entitiesType
 * @param unknown $new_name
 */
function updateRelations($mysqli, $entitites_str, $entitiesType, $new_name){
    global $entitiesTypeToTable;
    $table=  $entitiesTypeToTable[$entitiesType];
    $names_arr = explode(',', $entitites_str);
    foreach($names_arr as $name){
        $sql = "UPDATE inter_entity_relationship SET subject_agg = '$new_name' WHERE subject=$name AND subject_table='$table'";
        $res = sqlQuery($mysqli,$sql);
        $sql = "UPDATE inter_entity_relationship SET object_agg = '$new_name' WHERE  object=$name AND object_table='$table'";
        $res = sqlQuery($mysqli,$sql);
    }
}

function removeRelationsData($mysqli, $username, $name, $type, $tag){
    global $entitiesTypeToTable;
    $table=  $entitiesTypeToTable[$type];
    $tag_sub = $tag ? " subject='$tag'" : " TRUE ";
    $tag_obj = $tag ? " object='$tag'" : " TRUE ";
    
    $sql = "UPDATE inter_entity_relationship SET subject_agg = NULL WHERE subject_agg='$name' AND subject_table='$table' AND $tag_sub";
    $res = sqlQuery($mysqli,$sql);
    $sql = "UPDATE inter_entity_relationship SET object_agg = NULL WHERE  object_agg='$name' AND object_table='$table' AND $tag_obj";
    $res = sqlQuery($mysqli,$sql);
    
}

?>
