<?php
	include_once("loginCheckPoint.php");
	include_once("authorizations.php");
	require_once("demosettings.php");
	require_once 'parseUtils.php';	
	
	$userdetails = getUserDetails();
	$username = $userdetails['Username'];
	$commonFilter = "WHERE timeStamp IS NOT NULL";
	$mysqli = sqlCreateConnection("json_request");	
	
	if ($_REQUEST["getStatus"]){
		$sql = "SELECT isRunning FROM user_status WHERE username=\"$username\""; 												
		$res = $mysqli->query($sql);		
		if(is_object($res)){
			$row = $res->fetch_object();
			if ($row->isRunning == 0)
				$response["isRunning"] = false;	
			else{										
				$sql = "SELECT filename,date FROM files $commonFilter ORDER BY id DESC LIMIT 1,1";
				$res = $mysqli->query($sql);
				if(is_object($res)){
					
					$row = $res->fetch_object();
					$response["fileName"] = $row->filename;
					$response["isRunning"] = true;	
					$db_time = strtotime($row->date);					
					$t = time();					
					if (($db_time - $t) > 300)
					{
						$sql = "UPDATE user_status SET isRunning=0 WHERE username=\"$username\""; 												
						$res = $mysqli->query($sql);
						write_to_log("ERROR", "UPDATE user_status SET isRunning=0 t=$t time=".$db_time);						
					}				
				}else{
					$response["fileName"] = "";
					$response["isRunning"] = true;	
				}
			}
		}
		
		echo json_encode($response);
	}else{		
		$limit = 3000;
		$table = $_REQUEST["table"];				
		
		$sql = "SELECT DISTINCT $table.name FROM $table ORDER BY $table.name LIMIT $limit";
		$res = $mysqli->query($sql);
		$tableNames = array();
		if(!empty($res)){
			while($row = $res->fetch_object()){
				$tableNames[] = $row->name;
			}
		}
		
		echo json_encode($tableNames);
	}
	sqlClose($mysqli, 'jsonRequest');
	
?>