<?php

require_once('../vendor/autoload.php');

$dotenv = \Dotenv\Dotenv::createImmutable(__DIR__ . "/../");

$dotenv->safeLoad();

use Server\Models\User;
use Server\Models\Trade;
use Server\Models\Setting;
use Server\Models\Base\Connection;
use Server\Models\Base\DevConnection;

if (str_starts_with($_SERVER['HTTP_HOST'],'localhost')) {
    new DevConnection;
} else {
    new Connection;
}

$time = time();
$trades = Trade::where('closing_price', null)->orderBy('created_at', 'DESC')->get()->toArray();

try {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET', 'https://probrokerapis3.com/api/prices', ['headers' => ['origin' => $_ENV['NODE_DOMAIN']]]);
    $prices = (array) json_decode($res->getBody());
} catch (Exception $e) {
    $prices = [];
}

$settings = Setting::where('id', 1)->first();

?>

<!DOCTYPE html>
<html>

<head>

    <title>Trades</title>

    <link href="/<?php 
    // echo str_replace(" ", "-", strtolower($_ENV["NODE_NAME"])) . ".css" 
    ?>" rel="stylesheet" />


    <script>
        const root = document.querySelector(":root");

        root.style.setProperty("--hover", "#252b3c");

        root.style.setProperty("--nav-primary-font-colour", "white");
        root.style.setProperty("--nav-secondary-font-colour", "white");

        root.style.setProperty("--background-colour", "#000000");
        root.style.setProperty("--background-font-colour", "#a5bdd9");
        root.style.setProperty("--background-heading-colour", "#ffffff");

        root.style.setProperty("--primary-background", "#0b1118");
        root.style.setProperty("--primary-font-colour", "#a5bdd9");
        root.style.setProperty("--primary-border-colour", "#363c4e");
        root.style.setProperty("--primary-link-colour", "#FFFFFF");

        root.style.setProperty("--secondary-background", "#000000");
        root.style.setProperty("--secondary-font-colour", "#a5bdd9");
        root.style.setProperty("--secondary-heading-colour", "#ffffff");

        root.style.setProperty("--border-colour", "#434651");
    </script>
</head>

<body>

    <br /><br />

    <section class="container">

        <ul class="collection">

<?php

            echo count($prices) . " PRICES <br/><br/>";

            echo count($trades) . " OPEN TRADES<br/><br/>"; 

            
            foreach ($trades as $trade) {

                $user = User::where('id', $trade->user_id)->first();

                $closing_price = null;
                $calculated_profit = null;

                $type = $trade['type'];
                $amount = $trade['amount'];
                $opening_price = $trade['opening_price'];

                $symobl = $trade['symbol'];

                // cant get closing price
                if (!isset($prices[$symobl])) {

                    // echo "
                    // <li class='collection-item'> 
                    //     CANT GET PRICE {$trade['type']} {$trade['amount']} {$trade['symbol']}
                    // </li>
                    // ";

                    continue;
                }

                $closing_price = $prices[$trade['symbol']];

                if ($type == "BUY" || $type == "HIGHER" || $type == "CALL" || $type == "UP") {
                    $difference = $closing_price - $opening_price;
                }

                if ($type == "SELL" || $type == "LOWER" || $type == "PUT" || $type == "DOWN") {
                    $difference = $opening_price - $closing_price;
                }

                $calculated_profit = $difference * $amount;

                $profit = $trade['profit'] ?? $calculated_profit;



                // time trade
                if ($trade['time'] != null) {

                    // calculate time allowed
            
                    $destination_minutes = $trade['time'];

                    $destination_seconds = $destination_minutes * 60;

                    $destination_hours = $destination_minutes / 60;

                    $destination_days = $destination_hours / 24;



                    // calculate time past
                    $current_timestamp = time();

                    $open_timestamp = $trade['php_timestamp'];

                    $seconds_past = $current_timestamp - $open_timestamp;

                    $minutes_past = $seconds_past / 60;

                    $hours_past = $minutes_past / 60;

                    $days_past = $hours_past / 24;



                    // calculate time remaining
                    $seconds = $destination_seconds - $seconds_past;

                    $minutes = $destination_minutes - $minutes_past;

                    $hours = $destination_hours - $hours_past;

                    $days = $destination_days - $days_past;



                    $sc = floor($seconds) % 60;
                    $mc = floor($minutes) % 60;
                    $hc = floor($hours) % 24;
                    $dc = floor($days) % 365;

                    $duration = $trade['time'];
                    $current_time = new DateTime();
                    $created_time = (new DateTime())->setTimeStamp($trade['php_timestamp']);
                    $time_difference = $current_time->diff($created_time);
                    $minutes_left = $duration - 1 - $time_difference->i;
                    $seconds_left = 60 - $time_difference->s;




                    // close timed trade 
            
                    if ($seconds <= 0) {
                        $closingTrade = Trade::where("id", $trade['id'])->first();

                        $body = [];
                        $body['profit'] = $profit;
                        $body['closing_price'] = $closing_price;

                        if ($closingTrade->profit != null) {
                            $body['profit'] = $closingTrade->profit;
                        }

                        $closingTrade->update($body);


                        // update balance
            
                        if ($settings->trading_balance == "total_only") {

                            $trading_balance_total = $user->trading_balance_total + $body['profit'];


                            if ($trading_balance_total < 0) {
                                $trading_balance_total = 0;
                            }

                            $user->update(["trading_balance_total" => $trading_balance_total]);

                        } else {

                            $trading_balance_deposit = $user->trading_balance_deposit;

                            if ($body['profit'] > 0) {
                                $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                            }

                            if ($body['profit'] < 0) {
                                if (abs($body['profit']) <= $user->trading_balance_profit) {
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                                } else {

                                    // loss if greater than trading balance profit
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];

                                    // but not greater than trading balance deposit
                                    if (abs($trading_balance_profit) <= $user->trading_balance_deposit) {
                                        $trading_balance_deposit = $user->trading_balance_deposit + $body['profit'];  
                                        $trading_balance_profit = 0;
                                    } else {
                                        $trading_balance_profit = 0; 
                                        $trading_balance_deposit = 0;
                                    }

                                }
                            }

                            $user->update(["trading_balance_deposit" => $trading_balance_deposit, "trading_balance_profit" => $trading_balance_profit]);

                        }

                    }

                    continue;
                }





                // untimed trade
            
                if (isset($trade['stop_loss']) || isset($trade['take_profit'])) {

                    // stop loss - close trade
                    if ($trade['stop_loss'] < 0 && $profit <= $trade['stop_loss']) {
                        $closingTrade = Trade::where("id", $trade['id'])->first();

                        $body = [];
                        $body['profit'] = $profit;
                        $body['closing_price'] = $closing_price;

                        if ($closingTrade->profit != NULL) {
                            $body['profit'] = $closingTrade->profit;
                        }

                        $closingTrade->update($body);






                        // update balance start


                        if ($settings->trading_balance == "total_only") {

                            $trading_balance_total = $user->trading_balance_total + $body['profit'];


                            if ($trading_balance_total < 0) {
                                $trading_balance_total = 0;
                            }

                            $user->update(["trading_balance_total" => $trading_balance_total]);

                        } else {

                            $trading_balance_deposit = $user->trading_balance_deposit;

                            if ($body['profit'] > 0) {
                                $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                            }

                            if ($body['profit'] < 0) {
                                if (abs($body['profit']) <= $user->trading_balance_profit) {
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                                } else {

                                    // loss if greater than trading balance profit
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];

                                    // but not greater than trading balance deposit
                                    if (abs($trading_balance_profit) <= $user->trading_balance_deposit) {
                                        $trading_balance_deposit = $user->trading_balance_deposit + $body['profit'];  
                                        $trading_balance_profit = 0;
                                    } else {
                                        $trading_balance_profit = 0; 
                                        $trading_balance_deposit = 0;
                                    }

                                }
                            }

                            $user->update(["trading_balance_deposit" => $trading_balance_deposit, "trading_balance_profit" => $trading_balance_profit]);

                        }






                    }

                    // take profit - close trade
                    if ($trade['take_profit'] > 0 && $profit >= $trade['take_profit']) {
                        $closingTrade = Trade::where("id", $trade['id'])->first();

                        $body = [];
                        $body['profit'] = $profit;
                        $body['closing_price'] = $closing_price;

                        if ($closingTrade->profit != null) {
                            $body['profit'] = $closingTrade->profit;
                        }

                        $closingTrade->update($body);


                        // update balance start

                        if ($settings->trading_balance == "total_only") {

                            $trading_balance_total = $user->trading_balance_total + $body['profit'];


                            if ($trading_balance_total < 0) {
                                $trading_balance_total = 0;
                            }

                            $user->update(["trading_balance_total" => $trading_balance_total]);

                        } else {

                            $trading_balance_deposit = $user->trading_balance_deposit;

                            if ($body['profit'] > 0) {
                                $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                            }

                            if ($body['profit'] < 0) {
                                if (abs($body['profit']) <= $user->trading_balance_profit) {
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];
                                } else {

                                    // loss if greater than trading balance profit
                                    $trading_balance_profit = $user->trading_balance_profit + $body['profit'];

                                    // but not greater than trading balance deposit
                                    if (abs($trading_balance_profit) <= $user->trading_balance_deposit) {
                                        $trading_balance_deposit = $user->trading_balance_deposit + $body['profit'];  
                                        $trading_balance_profit = 0;
                                    } else {
                                        $trading_balance_profit = 0; 
                                        $trading_balance_deposit = 0;
                                    }

                                }
                            }

                            $user->update(["trading_balance_deposit" => $trading_balance_deposit, "trading_balance_profit" => $trading_balance_profit]);

                        }


                    }

                }




            }

            ?>
        </ul>

    </section>
</body>