<?php

static $conn;

if (!isset($conn)) {

	$servername = "localhost";
	$database = "rockccbq_rocketta";
	$username = "rockccbq_rocketttt";
	$password = ",%+q%RXbz}9P";
	
	try {
		$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
	} catch (Exception $exception) {
		die('An unexpected error occurred. Connection failed.');
	}
}

if ($conn) {

    $usr_sql = "SELECT * FROM quarterly_trade_history WHERE status=:status ORDER BY date DESC";
	$usr_sth = $conn->prepare($usr_sql);
	$usr_sth->execute(array(':status' => 1));
	$quarterly_trade_history = $usr_sth->fetchAll(PDO::FETCH_ASSOC);
	
	foreach ($quarterly_trade_history as $row) {
		$id = $row['id'];
		$accountId = $row['accountId'];
		$date = $row['date'];
		$bot_purchase_id = $row['bot_purchase_id'];

		checkAndCalculateData($id, $accountId, $date, $bot_purchase_id);
	}
	
}else {
	die("Connection failed.");
}

function checkAndCalculateData($id, $accountId, $date, $bot_purchase_id) {

    global $conn;

    $daysElapsed = getDaysElapsed($date);

	if ($daysElapsed >= 90) {
		$datetime = date('Y-m-d H:i:s');

		$sql = 'UPDATE quarterly_trade_history SET status=:status,closed_date=:closed_date WHERE id=:id AND accountId=:accountId';
		$stmt = $conn->prepare($sql);
		$stmt->execute(array(':status'=> 0, ':closed_date'=> $datetime, ':id'=> $id, ':accountId'=> $accountId));
		
		if ($bot_purchase_id != null) {
			$sql = 'UPDATE purchased_bots SET status=:status,closed_date=:closed_date WHERE bot_purchase_id=:bot_purchase_id AND accountId=:accountId';
			$stmt = $conn->prepare($sql);
			$stmt->execute(array(':status'=> 0, ':closed_date'=> $datetime, ':bot_purchase_id'=> $bot_purchase_id, ':accountId'=> $accountId));
		}

		sendMail($accountId,'quarterly');
	}
}

function getDaysElapsed($date) {
	$now = time();
	$trade_date = strtotime($date);
	$datediff = $now - $trade_date;
	return round($datediff / (60 * 60 * 24));
}

function sendMail($accountId, $trade_type)
{

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "accountId=$accountId&trade_type=$trade_type");
    curl_setopt($ch, CURLOPT_URL, 'https://rocketta.io/email/send_trade_expired_mail');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_exec($ch);
    curl_close($ch);

    echo("Trade closed successfully ------> ");
}