<?php
session_start();

require("../includes/db_connect.php");


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((!empty($_POST['accountId'])) && (!empty($_POST['package']))  && (!empty($_POST['amountUSD']))) {

        if ($conn) {
            try {

                $accountId = $_POST['accountId'];
                $package = $_POST['package'];
                $leverage = $_POST['leverage'];
                $amountUSD = round($_POST['amountUSD'], 2);

                if ($package == "Monthly"  && (!empty($leverage))) {
                    die("Invalid request!");
                }

                if (is_numeric($amountUSD) && $amountUSD > 0) {

                    $users_sql = "SELECT * FROM users WHERE accountId=? LIMIT 1";
                    $users_sth = $conn->prepare($users_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                    $users_sth->execute([$accountId]);
                    $users = $users_sth->fetchAll();

                    if (count($users) > 0) {

                        $package_name = "";
                        $margin = 0;

                        switch ($package) {
                            case 'Monthly':
                                $package_name = "Trade (Monthly)";
                                $balance_sql = "SELECT * FROM monthly_trading_balances WHERE accountId=? LIMIT 1";
                                $new_balance_sql = "UPDATE monthly_trading_balances SET trade_amount=? WHERE accountId=?";
                                $history_account = "monthly_trade_history";
                                $history_transactions = "monthly_trade_transactions";
                                $closed_date = closed_date('monthly');

                                switch ($leverage) {
                                    case '1:50':
                                        $margin = $amountUSD * 50;
                                        break;
                                    case '1:100':
                                        $margin = $amountUSD * 100;
                                        break;
                                    case '1:200':
                                        $margin = $amountUSD * 200;
                                        break;
                                    case '1:500':
                                        $margin = $amountUSD * 500;
                                        break;
                                    case '1:1000':
                                        $margin = $amountUSD * 1000;
                                        break;
                                    default:
                                        die('Invalid request!');
                                }

                                $margin = round($margin, 2);
                
                                break;
                            case 'Quarterly':
                                $package_name = "Trade (Quarterly)";
                                $balance_sql = "SELECT * FROM quarterly_trading_balances WHERE accountId=? LIMIT 1";
                                $new_balance_sql = "UPDATE quarterly_trading_balances SET trade_amount=? WHERE accountId=?";
                                $history_account = "quarterly_trade_history";
                                $history_transactions = "quarterly_trade_transactions";
                                $closed_date = closed_date('quarterly');
                                break;
                            case 'Annually':
                                $package_name = "Trade (Annually)";
                                $balance_sql = "SELECT * FROM annual_trading_balances WHERE accountId=? LIMIT 1";
                                $new_balance_sql = "UPDATE annual_trading_balances SET trade_amount=? WHERE accountId=?";
                                $history_account = "annual_trade_history";
                                $history_transactions = "annual_trade_transactions";
                                $closed_date = closed_date('annually');
                                break;
                            case 'Bot':
                                $package_name = "Trade (Community Bot)";
                                $balance_sql = "SELECT * FROM bot_trading_balances WHERE accountId=? LIMIT 1";
                                $new_balance_sql = "UPDATE bot_trading_balances SET trade_amount=? WHERE accountId=?";
                                $history_account = "bot_trade_history";
                                $history_transactions = "bot_trade_transactions";
                                $closed_date = closed_date('quarterly');
                                break;
                            default:
                                die("Invalid request!");
                        }

                        if ($package == "Monthly") {
                            $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                            $balance_sth->execute([$accountId]);
                            $account_balances = $balance_sth->fetchAll();

                            foreach ($account_balances as $key => $value) {
                                $usr_balance = $value['trade_amount'];
                                $usr_margin = $value['margin'];

                                $acc_balance = round($usr_balance, 2);
                                $acc_margin = round($usr_margin, 2);

                                $new_balance = round(($acc_balance + $amountUSD), 2);
                                $new_margin= round(($acc_margin + $margin), 2);

                                 $new_balance_sql = "UPDATE monthly_trading_balances SET trade_amount=?, margin=? WHERE accountId=?";
                                $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $new_margin, $accountId]);

                                if ($update_balance) { 

                                    $inv_sql = "INSERT INTO $history_account (accountId, type, trade_amount, closed_date, has_leverage, leverage, margin) VALUES (?,?,?,?,?,?,?)";

                                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, $package_name, $amountUSD, $closed_date, 1, $leverage, $margin]);
                                    $trade_id = $conn->lastInsertId();
                                    
                                    $inv_sql = "INSERT INTO $history_transactions (accountId, type, trade_amount, profit, recent_profit, closed_date, trade_history_id, has_leverage, leverage, margin) VALUES (?,?,?,?,?,?,?,?,?,?)";

                                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, $package_name, $amountUSD, "0.00", "0.00", $closed_date, $trade_id, 1, $leverage, $margin]);

                                
                                    $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                    $trans_name = "Trade Created";

                                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $package_name, $amountUSD, $trans_name, 1]);

                                    die("success");
                                } else {
                                    die("Unable to update account balance!");
                                }
                            }
                        } else {
                            $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                            $balance_sth->execute([$accountId]);
                            $account_balances = $balance_sth->fetchAll();

                            foreach ($account_balances as $key => $value) {
                                $usr_balance = $value['trade_amount'];

                                $acc_balance = round($usr_balance, 2);

                                $new_balance = round(($acc_balance + $amountUSD), 2);

                                $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);

                                if ($update_balance) { 

                                    $inv_sql = "INSERT INTO $history_account (accountId, type, trade_amount, closed_date) VALUES (?,?,?,?)";

                                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, $package_name, $amountUSD, $closed_date]);
                                    $trade_id = $conn->lastInsertId();
                                    
                                    $inv_sql = "INSERT INTO $history_transactions (accountId, type, trade_amount, profit, recent_profit, closed_date, trade_history_id) VALUES (?,?,?,?,?,?,?)";

                                    $create_inv = $conn->prepare($inv_sql)->execute([$accountId, $package_name, $amountUSD, "0.00", "0.00", $closed_date, $trade_id]);

                                
                                    $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                    $trans_name = "Trade Created";

                                    $create_history = $conn->prepare($req_sql)->execute([$accountId, $package_name, $amountUSD, $trans_name, 1]);

                                    die("success");
                                } else {
                                    die("Unable to update account balance!");
                                }
                            }
                        }
                    } else {
                        die('An unexpected error occurred. Connection failed');
                    }
                } else {
                    die('Please enter a valid amount.');
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid user information.');
    }
} else {
    die('Invalid request.');
}


function convertDate($date)
{
    $dt = str_replace('/', '-', $date);
    return date('Y-m-d', strtotime($dt));
} 

function closed_date($type) {
    $currentDate = date('Y-m-d');
    $nextDate = '';

    switch ($type) {
        case 'monthly':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +31 days'));
            break;
        case 'quarterly':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +92 days'));
            break;
        case 'annually':
            $nextDate = date('Y-m-d', strtotime($currentDate . ' +366 days'));
            break;
        default:
            return "Invalid type argument.";
    }

    return $nextDate;
}