<?php
header('Content-type: application/json');
include '../../config/database.php';
function _command($products,$version,$total,$speed,$ip){
	$conn = _connectDB();
	$sql_get = "SELECT * FROM `monitor` WHERE Code='".$products."' AND version='".$version."'";
	echo $sql_get;
	$res_get = $conn->query($sql_get);

	if ((int)$res_get->num_rows == 0) {
		$sql = "INSERT INTO `monitor` (Code,Version,Status,Timeout,Total,Speed,ip) VALUES ('".$products."', '".$version."','RUN','"._getTime()."','".$total."','".$speed."','".$ip."')";
		$result = $conn->query($sql);
		$res = ['status'=>true];
	}else{
		$sql = "UPDATE `monitor` SET ip='".$ip."', Timeout='"._getTime()."', Status='RUN' ,Total='".$total."',Speed='".$speed."' WHERE  Code='".$products."' AND Version='".$version."' ";
		echo $sql;
		$result = $conn->query($sql);
		$res = ['status'=>true];
	}
	return $res;
}
if(isset($_POST)){
	if(isset($_POST['products'])  AND isset($_POST['version'])){
		$products = $_POST['products'];
		$version = $_POST['version'];
		$total = 0;
		if(isset($_POST['total'])){
			$total = $_POST['total'];
		}
		$speed = 'not';
		if(isset($_POST['speed'])){	
			$speed = $_POST['speed'];
		}
		$ip = '0.0.0.0';
		if(isset($_POST['ip'])){	
			$ip = $_POST['ip'];
		}		
		echo json_encode(_command($products,$version,$total,$speed,$ip));
	}else{echo json_encode(['status'=>false]);}
}else{echo json_encode(['status'=>false]);}

function _getTime(){
	$current = date("Y-m-d H:i:s");  
	$current =  date("Y-m-d H:i:s", strtotime("+3 min",strtotime($current)));
	return $current;
}

