<?php

session_start();

require_once("demosettings.php");
//include_once("config.php");
include_once("sqlTable.php");
include("loginCheckPoint.php");
include_once("authorizations.php");
//include_once($_SERVER['DOCUMENT_ROOT']. "/iventitymatcherhtm/bsw/utils.php");
include_once 'write_log.php';

//exec("taskkill /fi \"WindowTitle eq joseki2*\"");
//die("here");
$userdetails = getUserDetails();
$canAnalyzeFolder = getUserPermission(CAN_ANALYZER_FOLDER);

$sync = $_REQUEST["sync"] ?? null;
$clean = $_REQUEST["clean"] ?? null;

$mysqli = sqlCreateConnection("homeEng");
//in case background.php executes this file (home.php) to sync doc persons - it passes docId as first parameter
if(IS_CLI) {
    $docId = $argv[1];
}

/*if ($docId) $sync = 1;
else {*/

//}

/*if ($sync == 1)
{
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	$query = "SELECT * FROM person_object";
	$docAppend = " WHERE";
	if ($userdetails['Group_ID'] != 0)
	{
		$query .= " WHERE username='$userdetails[Username]'";
		$docAppend = " AND";
	}
	//append docId to where - for synching this doc persons only
	if ($docId)
		$query .= $docAppend . " docId = " . $docId;
		
	$res = $mysqli->query($query);
	$arr_obj = array();
	$r = $res->fetch_object();
	if (!empty($r)){		
		$i = 0;
		$arr_obj[$i++] = $r;
		while ($res_obj = $res->fetch_object())
		{
			$arr_obj[$i++] = $res_obj; 
		}				
		
		if (is_dir("c:/tmp"))
			$filepath = "c:/tmp/";		
		else 
			$filepath = "c:/temp/";
		//if ($userdetails['Group_ID'] == 0)
			$filename = "DOCEX Entities DB.tsv";
		//else 
		//	$filename = "DOCEX Entities DB-" . $userdetails[Username] .  ".tsv";

		//if only synch docId = create a filename with docId
		if ($docId)
			$filename = str_replace(".tsv", "." . $docId . ".tsv", $filename);
		
		unlink($filepath.$filename);
		foreach ($arr_obj as $obj)
		{
			file_put_contents($filepath.$filename, $obj->id , FILE_APPEND);		
			file_put_contents($filepath.$filename, "\t" . $obj->name . "\n", FILE_APPEND);		
		}
		//delete current watch list (unless appending docId to existing watch list)
		if (!$docId)
		{
		//if ($userdetails['Group_ID'] == 0)
			deleteWatchList("DOCEX Entities DB",$entityMatcher);
		//else 
		//	deleteWatchList("DOCEX Entities DB-" . $userdetails[Username],$entityMatcher);
		}
		$success = loadList($filepath,$filename,$entityMatcher, $docId);
		if (!$success) write_to_log("ERROR", "LoadList failed: " . $errormsg);
		unlink($filepath.$filename);
		//file_put_contents("c:/tmp/DOCEX Entities DB.xml",convertTsvToXml($filepath,$filename));
		$mysqli->close();
	}
	//docId is available only when synching from background.php - then can exit after sync
	if ($docId)
		exit;

}else*/if ($clean == 2)
{
	cleanDB($mysqli, $userdetails);
}

if (key_exists("addTables", $_REQUEST) && $_REQUEST["addTables"])
{
	require_once 'sqlTable.php';
	createDB($mysqli, false);
}

			if( key_exists("err", $_REQUEST) ) 
				$err = $_REQUEST["err"];
			else 
				$err = 0;
			if($err > 0){
				if($err == 1){
					$msg = "The input file exceeded the size limit. Please select a file with size up to 1 MBytes and try again.";
				}else if($err == 2){
					$msg = "Nothing to process. Please provide input data and try again.";
				}
			}
			
			$mysqli = sqlCreateConnection("homeEng");
			
			if (getUserPermission(CAN_SHOW_ALL_USER))
			    $res = sqlQuery($mysqli, "SELECT MAX(id) as i FROM files");
			    
			else 			
			    $res = sqlQuery($mysqli, "SELECT COUNT(id) as i FROM files WHERE username='" . $userdetails['Username'] . "'");
			    
			if (!empty($res))	{
				$row = $res->fetch_object();
			
				$analysedDocuments = $row->i;
			}
						

			$response = array();
			if( isset($msg) ) $response["msg"] = $msg;
			$response["canAnalyzeFolder"] = $canAnalyzeFolder;
			if ($canAnalyzeFolder && is_dir($uploadedFilesPath))
				foreach (glob("$uploadedFilesPath/*", GLOB_ONLYDIR) as $folder)
					$response["folderList"][] = basename($folder);
				
			$response["analysedDocuments"] = $analysedDocuments ?? null;
			sqlClose($mysqli, "homeEng");
			echo json_encode($response);