<?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 demo_trade_history WHERE status=:status ORDER BY date DESC";
	$usr_sth = $conn->prepare($usr_sql);
	$usr_sth->execute(array(':status' => 1));
	$subscription_packages = $usr_sth->fetchAll(PDO::FETCH_ASSOC);
	
	foreach ($subscription_packages as $row) {
		$id = $row['id'];
		$accountId = $row['accountId'];
		$type = $row['type'];
		$trade_amount = round($row['trade_amount'], 2);
		$profit = round($row['profit'], 2);
		$recent_profit = round($row['recent_profit'], 2);
		$recent_date = $row['recent_date'];
		$date = $row['date'];

		checkAndCalculateData($id, $accountId, $type, $trade_amount, $profit, $recent_date, $date);
	}
	
	echo("Request working");
}else {
	die("Connection failed.");
}

function checkAndCalculateData($id, $accountId, $type, $trade_amount, $profit, $recent_date, $date) {

    global $conn;

    $closing_date = addDaysToDate(new DateTime(convertDate($date)), 31);
    $days_running = getWeekdayDifference(new DateTime(convertDate($date)), $closing_date);

    $usr_sql = "SELECT * FROM demo_trade_cron_profit_history WHERE accountId=:accountId AND trade_id=:trade_id LIMIT 1";
    $usr_sth = $conn->prepare($usr_sql);
    $usr_sth->execute(array(':accountId' => $accountId, ':trade_id' => $id));
    $history = $usr_sth->fetchAll(PDO::FETCH_ASSOC);

    if (count($history) > 0) {

        foreach ($history as $row) {
            $hs_profit = $row['profit'];
            $hs_recent_date = $row['recent_date'];
            $hs_days_elapsed = $row['days_elapsed'];
            $hs_day_profit = $row['day_profit'];
            $hs_day_profit_used = $row['day_profit_used'];
            $hs_day_day_run = $row['day_run'];

            $total_profit = $trade_amount * 4; 

            $remaining_profit_calc = $total_profit - $hs_profit;
            $days_remaining = $days_running - $hs_days_elapsed;
            
            if ($days_remaining > 0) {

                if ($remaining_profit_calc > 0) {
                    $hs_recent_date_format = new DateTime(convertDate($hs_recent_date));
                    if ($hs_recent_date_format->format('Y-m-d') == date('Y-m-d')) {
                        //Use day profit
                        echo("same day");
                        /*if ($hs_day_day_run <= 3) {
                            $credit_amount = 0;
                            $new_hs_profit_used = 0;

                            if ($hs_day_day_run  == 3) {
                                $credit_amount = max(($hs_day_profit - $hs_day_profit_used), 0);
                                $new_hs_profit_used = round($hs_day_profit,2);
                            }else {
                                $day_profit_remaining = $hs_day_profit - $hs_day_profit_used;
                                $credit_amount_calc = $day_profit_remaining / (4 - $hs_day_day_run);
                                $credit_amount = round(rand(($credit_amount_calc/1.5),$credit_amount_calc), 2);
                                $new_hs_profit_used = round(($hs_day_profit_used + $credit_amount), 2);
                            }

                            $new_profit = $hs_profit + $credit_amount;

                            $new_day_run = $hs_day_day_run + 1;

                            $datetime = date('Y-m-d H:i:s');

                            $sql = 'UPDATE demo_trade_cron_profit_history SET day_profit_used=:day_profit_used, profit=:profit, day_run=:day_run, recent_profit=:recent_profit, recent_date=:recent_date WHERE trade_id=:trade_id AND accountId=:accountId';
                            $stmt = $conn->prepare($sql);
                            $stmt->execute(array(':day_profit_used'=> $new_hs_profit_used, ':profit'=> $new_profit, ':day_run'=> $new_day_run, ':recent_profit'=> $credit_amount, ':recent_date'=> $datetime, ':trade_id'=> $id,':accountId'=> $accountId));

                            $sql = 'UPDATE demo_trade_history SET profit=:profit,recent_profit=:recent_profit,recent_date=:recent_date  WHERE id=:trade_id AND accountId=:accountId';
                            $stmt = $conn->prepare($sql);
                            $stmt->execute(array(':profit'=> $new_profit, ':recent_profit'=> $credit_amount, ':recent_date'=> $datetime, ':trade_id'=> $id, ':accountId'=> $accountId));

                            $inv_sql = "INSERT INTO demo_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?)";
                            $create_inv = $conn->prepare($inv_sql)->execute(array($accountId, $type, $trade_amount, $new_profit, $credit_amount, $datetime, $date));

                            $balance_sql = "SELECT * FROM demo_trading_balances WHERE accountId=:accountId LIMIT 1";
                            $balance_sth = $conn->prepare($balance_sql);
                            $balance_sth->execute(array(':accountId'=>$accountId));
                            $trading_balances = $balance_sth->fetchAll(PDO::FETCH_ASSOC);

                            foreach ($trading_balances as $row) {
                                $usr_profit = round($row['profit'], 2);

                                $new_profit_calc = round(($usr_profit + $credit_amount), 2);
                                $balance_sql = "UPDATE demo_trading_balances SET profit=:profit WHERE accountId=:accountId";
                        
                                $update_balance = $conn->prepare($balance_sql)->execute(array(':profit'=>$new_profit_calc, ':accountId'=>$accountId));
                            }
                        }else {
                            echo("Day run completed for trade. ");
                        }*/
                    }else {
                        //Calculate day profit
                        echo("diff day <br/>");
                        /*$day_profit_calc = $remaining_profit_calc / $days_remaining;

                        $day_profit = round($day_profit_calc, 2);

                        if ($day_profit_calc > 0 && $days_remaining > 1) {
                            $day_profit = round(rand(($day_profit_calc/1.5),$day_profit_calc),2);
                        }

                        $day_random_credit_calc = $day_profit / 4;

                        $day_random_credit = round(rand(($day_random_credit_calc/1.5),$day_random_credit_calc), 2);

                        $new_profit = $hs_profit + $day_random_credit;

                        $datetime = date('Y-m-d H:i:s');

                        $new_days_elapsed = $hs_days_elapsed + 1;
                        $new_days_remaining = max(($days_remaining - 1), 0);

                        $sql = 'UPDATE demo_trade_cron_profit_history SET days_elapsed=:days_elapsed, days_remaining=:days_remaining, day_profit=:day_profit, day_profit_used=:day_profit_used, day_run=:day_run, profit=:profit, recent_profit=:recent_profit, recent_date=:recent_date WHERE trade_id=:trade_id AND accountId=:accountId';
                        $stmt = $conn->prepare($sql);
                        $stmt->execute(array(':days_elapsed'=>$new_days_elapsed, ':days_remaining'=>$new_days_remaining, ':day_profit'=>$day_profit, ':day_profit_used'=>$day_random_credit,':day_run'=> 1, ':profit'=>$new_profit, ':recent_profit'=>$day_random_credit, ':recent_date'=>$datetime, ':trade_id'=>$id, ':accountId'=>$accountId));

                        $sql = 'UPDATE demo_trade_history SET profit=:profit,recent_profit=:recent_profit,recent_date=:recent_date  WHERE id=:trade_id AND accountId=:accountId';
                        $stmt = $conn->prepare($sql);
                        $stmt->execute(array(':profit'=>$new_profit, ':recent_profit'=>$day_random_credit, ':recent_date'=>$datetime, ':trade_id'=>$id, ':accountId'=>$accountId));

                        $inv_sql = "INSERT INTO demo_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?)";
                        $create_inv = $conn->prepare($inv_sql)->execute(array($accountId, $type, $trade_amount, $new_profit, $day_random_credit, $datetime, $date));

                        $balance_sql = "SELECT * FROM demo_trading_balances WHERE accountId=:accountId LIMIT 1";
                        $balance_sth = $conn->prepare($balance_sql);
                        $balance_sth->execute(array(':accountId'=>$accountId));
                        $trading_balances = $balance_sth->fetchAll(PDO::FETCH_ASSOC);

                        foreach ($trading_balances as $row) {
                            $usr_profit = round($row['profit'], 2);

                            $new_profit_calc = round(($usr_profit + $day_random_credit), 2);
                            $balance_sql = "UPDATE demo_trading_balances SET profit=:profit WHERE accountId=:accountId";
                    
                            $update_balance = $conn->prepare($balance_sql)->execute(array(':profit'=>$new_profit_calc, ':accountId'=>$accountId));
                        }*/
                    }
                }

            }else {
                //Close demo trade
                echo("Close trading.");
                /*$datetime = date('Y-m-d H:i:s');

                $sql = 'UPDATE demo_trade_cron_profit_history SET status=?,  closed_date=:closed_date WHERE trade_id=:trade_id AND accountId=:accountId';
                $stmt = $conn->prepare($sql);
                $stmt->execute(array(':status'=>0, ':closed_date'=>$datetime, ':trade_id'=>$id, ':accountId'=>$accountId));

                $sql = 'UPDATE demo_trade_history SET status=?,  closed_date=:closed_date WHERE id=:trade_id AND accountId=:accountId';
                $stmt = $conn->prepare($sql);
                $stmt->execute(array(':status'=>0, ':closed_date'=>$datetime, ':trade_id'=>$id, ':accountId'=>$accountId));

                $inv_sql = "INSERT INTO demo_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, closed_date, date) VALUES (?,?,?,?,?,?,?,?)";
                $create_inv = $conn->prepare($inv_sql)->execute(array($accountId, $type, $trade_amount, $hs_profit, $hs_day_profit, $hs_recent_date, $datetime, $date));*/
            }
        }
        
    }else {
        //Create first trade profit history
        echo('new history <br/>');

        /*$total_profit = $trade_amount * 4; 

        $day_profit_calc = $total_profit / $days_running;

        $day_profit = round($day_profit_calc, 2);

        if ($day_profit_calc > 0) {
            $day_profit = round(rand(($day_profit_calc/1.5),$day_profit_calc),2);
        }

        $day_random_credit_calc = $day_profit / 4;

        $day_random_credit = round(rand(($day_random_credit_calc/1.5),$day_random_credit_calc), 2);

        $days_remaining = $days_running - 1;

        $datetime = date('Y-m-d H:i:s');

        $d_sql = "INSERT INTO demo_trade_cron_profit_history (trade_id, accountId, type, trade_amount, days_elapsed, days_remaining, day_profit, day_profit_used, day_run, profit, recent_profit, recent_date, opened_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";

        $conn->prepare($d_sql)->execute(array($id, $accountId, $type, $trade_amount, 1, $days_remaining, $day_profit, $day_random_credit, 1, $day_random_credit, $day_random_credit, $datetime, $date));

        $new_profit = $profit + $day_random_credit;

        $sql = 'UPDATE demo_trade_history SET profit=:profit,recent_profit=:recent_profit,recent_date=:recent_date WHERE id=:trade_id AND accountId=:accountId';
        $stmt = $conn->prepare($sql);
        $stmt->execute(array(':profit'=>$new_profit, ':recent_profit'=>$day_random_credit, ':recent_date'=>$datetime, ':trade_id'=>$id, ':accountId'=>$accountId));

        $inv_sql = "INSERT INTO demo_trade_transactions (accountId, type, trade_amount, profit, recent_profit, recent_date, date) VALUES (?,?,?,?,?,?,?)";
        $create_inv = $conn->prepare($inv_sql)->execute(array($accountId, $type, $trade_amount, $new_profit, $day_random_credit, $datetime, $date));

        $balance_sql = "SELECT * FROM demo_trading_balances WHERE accountId=:accountId LIMIT 1";
        $balance_sth = $conn->prepare($balance_sql);
        $balance_sth->execute(array(':accountId'=>$accountId));
        $trading_balances = $balance_sth->fetchAll(PDO::FETCH_ASSOC);

        foreach ($trading_balances as $row) {
            $usr_profit = round($row['profit'], 2);

            $new_profit_calc = round(($usr_profit + $day_random_credit), 2);
            $balance_sql = "UPDATE demo_trading_balances SET profit=:profit WHERE accountId=:accountId";
    
            $update_balance = $conn->prepare($balance_sql)->execute(array(':profit'=>$new_profit_calc, ':accountId'=>$accountId));
        }*/
        
    }
   
}

function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $isWeekday = function (\DateTime $date) {
        return $date->format('N') < 6;
    };

    $days = $isWeekday($endDate) ? 1 : 0;

    while($startDate->diff($endDate)->days > 0) {
        $days += $isWeekday($startDate) ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
    }

    return $days;
}

function addDaysToDate($startDate, $daysToAdd)
    {
        // loop for X days
        for ($i = 0; $i < $daysToAdd; $i++) {
            // get what day it is next day
            $nextDay = $startDate->modify('+1 day');
            
            // if it's Saturday or Sunday get $i-1
            //if (in_array($nextDay->format('w'), [0, 6])) {
             //   $i--;
            //}
        }
    return $nextDay;
}

function convertDate($date) {
	$dt = str_replace('/', '-', $date);

	return date('Y-m-d', strtotime($dt));
}

?>