<?php 

include('../classes/database.class.php');

$db = new Database();
$todaydate = date('Y-m-d');

$getCurrency = $_POST['cur'];

$getRate = $db->db->prepare("SELECT * FROM currencyrate WHERE cur = '$getCurrency' ORDER BY id DESC LIMIT 2");
$getRate->execute();
$rateSystem = $getRate->fetchAll();

$currentBid = $rateSystem[0]['bid'];
$currentAsk = $rateSystem[0]['ask'];

$secondLastBid = $rateSystem[1]['bid'];
$secondLastAsk = $rateSystem[1]['ask'];

$changeRate = $secondLastBid - $currentBid;
$changeRatePer = $changeRate / $currentBid * 100;

$getMaxRateBid = $db->db->prepare("SELECT MAX(bid) FROM currencyrate WHERE cur = '$getCurrency' AND date = '$todaydate'");
$getMaxRateBid->execute();
$maxBid = $getMaxRateBid->fetch();
$maxBidRate = $maxBid[0];


$getMaxRateAsk = $db->db->prepare("SELECT MIN(bid) FROM currencyrate WHERE cur = '$getCurrency' AND date = '$todaydate'");
$getMaxRateAsk->execute();
$maxAsk = $getMaxRateAsk->fetch();
$maxAskRate = $maxAsk[0];

$chgRate = number_format((float)$changeRate, 5, '.', '');
$chgRatePer = number_format((float)$changeRatePer, 5, '.', '');

$closeoutask = $rateSystem[0]['closeoutask'];

//get recent 30 bars...for trend
$stmt = $db->db->prepare("SELECT * FROM currencyrate WHERE currency = ? ORDER BY id DESC LIMIT 240");
$stmt->execute(array($getCurrency));
$data= $stmt->fetchall();
$trendCounter = 0;
$sizeData = sizeof($data);
$int = 0;


$rating = "";

while($int < $sizeData)
{
	if($data[$int]['bid'] > $data[$int+1]['bid'])
	{
		$trendCounter++;
	}
	else if($data[$int]['bid'] < $data[$int+1]['bid'])
	{
		$trendCounter--;
	}
	$int++;
}
if($trendCounter < 0)
{
	if($trendCounter < -50)
	{
		$rating = "sell";		
	}
	else if($trendCounter < -100)
	{
		$rating = "sell";		
	}
	else {

		$rating = "strongsell";	
	}
}
else if($trendCounter > 0) 
{
	if($trendCount > 50)	
	{
		$rating = "buy";	
	}
	else if($trendCount > 100)
	{
		$rating = "buy";
	}
	else {
		$rating = "strongbuy";
	}
}
else 
{
	$rating = "buy";
}



$result = array('ask'=>$currentAsk, 'bid'=>$currentBid, 'chg'=>$chgRate, 'chgp'=>$chgRatePer, 'maxbid'=>$maxBidRate, 'maxask'=>$maxAskRate, 'elem'=>$getCurrency, 'rating'=>$rating);

print_r(json_encode($result));

?>