<?php

use PHPMailer\PHPMailer\PHPMailer;







require 'vendor/autoload.php';

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



/**

 * Created by PhpStorm.

 * User: brycemoral

 * Date: 6/27/16

 * Time: 1:29 PM

 */

$db = new database();



$rateArray = array();





$listOfCurrencies = "EUR_USD%2CEUR_JPY%2CEUR_GBP%2CUSD_JPY%2CUSD_CHF%2CUSD_CAD%2CGBP_USD%2CGBP_JPY%2CAUD_USD%2CNZD_USD";



$ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/pricing?instruments=" . $listOfCurrencies);

$header = array();

$header[] = 'Content-type: application/json';

$header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$resultsj = curl_exec($ch);

//print_r($results);

//print_r($result);

$results = json_decode($resultsj);

foreach($results->prices as $result){

  //if(sizeof($result->ask) ==  )

    $multipleValue = 1;



  $tempSize = strlen(substr(strrchr($result->closeoutAsk, "."), 1))  ;

if($tempSize == 5){

    $multipleValue = $multipleValue * 10000;

}

else if($tempSize == 4){

         $multipleValue = $multipleValue * 10000;

    }

    else{

         $multipleValue = $multipleValue * 100;

    }

//get recent 30 bars...for trend

$stmt = $db->db->prepare("SELECT * FROM historyData WHERE currency = ? ORDER BY id DESC LIMIT 240");

$stmt->execute(array($result->instrument));

$data= $stmt->fetchall();

$trendCounter = 0;

$sizeData = sizeof($data);

$int = 0;





$arrow = "";



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)

	{

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/download-arrow.svg' width='15'>";

		$arrow = "down";		

	}

	else if($trendCounter < -100)

	{

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/download-arrow.svg' width='15'>";

		$arrow = "down";		

	}

	else {

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/download-arrow.svg' width='15'>";	

		$arrow = "down";	

	}

}

else if($trendCounter > 0) 

{

	if($trendCount > 50)	

	{

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/up-arrow.svg' width='15'>";

		$arrow = "up";	

	}

	else if($trendCount > 100)

	{

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/up-arrow.svg' width='15'>";

		$arrow = "up";	

	}

	else {

		$trend = "<img class='crypt-star pr-1' alt='star' src='images/up-arrow.svg' width='15'>";

		$arrow = "up";	

	}

}

else 

{

	$trend = "<i style='color:grey;' class='glyphicon glyphicon-arrow-up'>";

	$arrow = "up";		

}







	$stmt= $db->db->prepare("INSERT INTO historyData (currency, bid, ask, spread, time_added) VALUES (? , ? , ?, ?, NOW())");

	$stmt->execute(array($result->instrument, $result->bids[0]->price, $result->asks[0]->price, round(abs($result->bids[0]->price - $result->asks[0]->price) * $multipleValue, 2) ));



	

	if (isset($_POST['action'])) {

		# code...



		$action = $_POST['action'];



		if ($action == 'tableshow') {

			# code...



			echo "<tr><td><img class='crypt-star pr-1' alt='star' src='images/star.svg' width='15'>" .  $result->instrument . "</td><td>" . $result->bids[0]->price . "</td><td>" .  $result->asks[0]->price . "</td> <td>" . round(abs($result->bids[0]->price - $result->asks[0]->price) * $multipleValue, 2) . "</td><td>" . $trend . "</i></td></tr>";



		}

	}







	$forarray = array('inst'=>$result->instrument, 'bidPrice'=>$result->bids[0]->price, 'askPrice'=>$result->asks[0]->price, 'result'=>round(abs($result->bids[0]->price - $result->asks[0]->price) * $multipleValue, 2), 'trend'=>$arrow);



	array_push($rateArray, json_encode($forarray));





	$symbols = $result->instrument;

	$alert_symbol = str_replace('_', '', $symbols);

	$bidprice = $result->bids[0]->price;



	$getalerts = $db->db->prepare("SELECT * FROM invataTracker WHERE symbol = '$alert_symbol'");

	$getalerts->execute();

	$get_alerts = $getalerts->fetchAll();





	if (!empty($get_alerts)) {

	# code...



	foreach ($get_alerts as $alts) {

		# code...



			$alert_price = $alts['price'];



			$converttofloat = floatval($bidprice);



			$alert_email = $alts['email'];



			if ($converttofloat == $alert_price) {

				# code...



				$alert_id = $alts['id'];



				$uid = $alts['user_id'];



				$getuser = $db->db->prepare("SELECT * FROM users WHERE uid = '$uid'");

				$getuser->execute();

				$userinfo = $getuser->fetch();



				$user_main_id = $userinfo['uid'];



				$getphone = $userinfo['phone'];

				$userEmail = $userinfo['email'];

				$phoneCar = $userinfo['pcarrier'];



				$phone_number = $getphone."@".$phoneCar;



				$alertDate = date('d M Y');



				$alertTime = date('H:i');







				$headers = "MIME-Version: 1.0" . "\r\n";

				$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

				$headers .= 'From: Invata<invata.io>' . "\r\n";





				$message = '<!DOCTYPE html>

				<html>

				<head>

					<title></title>

				</head>

				<body>

					<div style="border:1px solid #eee;padding:20px;">

					<div style="padding-top: 40px;padding-bottom: 40px;text-align: center;">

						<img src="https://trading.invata.io/images/invatalogo.png" style="width: 100px;">

					</div>

					<div style="text-align:center;">

						<p style="font-size:20px;">Alert Triggered - <span style="font-weight:700;">'.$alert_symbol.'</span></p>

						<p style="font-size:20px;">Alert Price - <span style="font-weight:700;">'.$alert_price.'</span></p>

						<p style="font-size:20px;">Alert Date - <span style="font-weight:700;">'.$alertDate.'</span></p>

						<p style="font-size:20px;">Alert Time - <span style="font-weight:700;">'.$alertTime.'</span></p>

						<a href="https://trading.invata.io/dashboard.php" target="_blank" style="background-color: #181818;color: #fff;text-align: center;padding: 10px 40px 15px 40px;text-decoration: none;margin-top:40px;">Move To Dashboard</a>

					</div>



					</div>

				</body>

				</html>';



				$phoneMessage = $alert_symbol." Triggered @ ".$alert_price;





				$delAlert = $db->db->prepare("DELETE FROM invataTracker WHERE id = '$alert_id'");

				if ($delAlert->execute()) {

					# code...



					mail($alert_email,"Invata Alert", $message, $headers);

					mail($userEmail,"Invata Alert", $message, $headers);

					/*mail($phone_number," ", $phoneMessage, "From: Invata <support@invata.io>\r\n");*/

										//Create a new PHPMailer instance

					$mail = new PHPMailer;

					//Tell PHPMailer to use SMTP

					$mail->isSMTP();

					//Enable SMTP debugging

					// 0 = off (for production use)

					// 1 = client messages

					// 2 = client and server messages

					$mail->SMTPDebug = 2;

					//Set the hostname of the mail server

					$mail->Host = 'smtp.gmail.com';

					// use

					// $mail->Host = gethostbyname('smtp.gmail.com');

					// if your network does not support SMTP over IPv6

					//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission

					$mail->Port = 587;

					//Set the encryption system to use - ssl (deprecated) or tls

					$mail->SMTPSecure = 'tls';

					//Whether to use SMTP authentication

					$mail->SMTPAuth = true;





					$mail->Username = "a.deelfaisal123@gmail.com";

					//Password to use for SMTP authentication

					$mail->Password = "PhoolAdeel123";

					//Set who the message is to be sent from

					$mail->setFrom('support@invata.io', 'Invata');

					//Set who the message is to be sent to

					$mail->addAddress($phone_number);

					//Set the subject line

					$mail->Subject = 'Invata Alert';

					//Read an HTML message body from an external file, convert referenced images to embedded,

					//convert HTML into a basic plain-text alternative body

					$mail->Body = $phoneMessage;



					$mail->send();





					$alertDateAndTime = $alertDate." ".$alertTime;



					$insertNotif = $db->db->prepare("INSERT INTO notification(user, symbol, price, dateandtime) VALUES ('$user_main_id', '$alert_symbol', '$alert_price', '$alertDateAndTime')");



					$insertNotif->execute();



				

				}









			}



	}









}







}





if (isset($_POST['action'])) {

	# code...



	$act = $_POST['action'];

	if ($act == 'rateArray') {

		# code...

		print_r(json_encode($rateArray));

	}

}



?>