<?php 
include('../classes/database.class.php');
$db = new database();
$sym = $_POST['sym'];

$getRowNum = $db->db->prepare("SELECT COUNT(*) FROM atr WHERE sym = '$sym'");
$getRowNum->execute();
$numberofrows = $getRowNum->fetchColumn();


$getResult = $db->db->prepare("SELECT * FROM atr WHERE sym = '$sym' ORDER BY id DESC LIMIT 14");
$getResult->execute();
$allResults = $getResult->fetchAll();

$getallranges = array();

$averageResult = 0.0000;

foreach ($allResults as $resultsRanges) {
	# code...
	array_push($getallranges, $resultsRanges['tr']);
}


if ($numberofrows < 14) {
	# code...
	$avg = array_filter($getallranges);
	$average = array_sum($getallranges)/count($getallranges);
	$averageResult = $average;


}else{

	$getatrquery = $db->db->prepare("SELECT * FROM atrvalues WHERE sym = '$sym'");
	$getatrquery->execute();
	$getatrfetch = $getatrquery->fetch();

	$atrinertq = "";

	if (empty($getatrfetch)) {
		# code...
		$avg = array_filter($getallranges);
		$average = array_sum($getallranges)/count($getallranges);
		$atrinertq = "INSERT INTO atrvalues(sym, atr) VALUES ('$sym', '$average')";
	}else{



		$current_tr = $getallranges[0]['tr'];
		$atr_value = $getatrfetch['atr'];
		$atr_multiply = $atr_value * 13;
		$current_atr_with_tr = $atr_multiply + $current_tr;

		$now_atr = $$current_atr_with_tr / 14;

		$averageResult = $now_atr;

		$updataeatr = "UPDATE atrvalues SET atr = '$averageResult' WHERE sym = '$sym'";


	}

	$insrtatr = $db->db->prepare($atrinertq);
	$insrtatr->execute();


}

$averageResult = number_format((float)$averageResult, 5, '.','');

print_r(json_encode(array('result'=>$averageResult, 'syms'=>$sym)));


?>