<!DOCTYPE html>
<html>

<head>
    <?php include 'header.php';  
        
        $email = $user->getEmail();

$qq = mysqli_query($link, "SELECT * FROM trade WHERE email = '$email' ORDER BY id DESC ");
    if (mysqli_num_rows($qq) > 0) {
        while ($tr = mysqli_fetch_assoc($qq)) {
            $status = $tr['status'];
            $trade_type = $tr['trade_type'];
            $amount = $tr['amount'];
            $symbol = $tr['symbol'];
            $units = $tr['units'];
            $trade_interval = $tr['trade_interval'];
            $market = $tr['market'];
            $profit = $tr['profit'];
            $trade_exp = $tr['trade_exp'];
            $trade_set = $tr['trade_set'];
            $win_loss = $tr['win_loss'];
            $tid = $tr['id'];
            $credited = $tr['credited'];

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

            if ($trade_exp == $current_time || $current_time >= $trade_exp) {
                //the status
                if ($win_loss == 1) {
                    $status = 3;
                }elseif ($win_loss == 0) {
                    $status = 2;
                }
                //profit
                if ($win_loss == 1) {
                    $profit = (90/100)*$amount;
                }elseif ($win_loss == 0) {
                    $profit = 0;
                }
                $update = mysqli_query($link, "UPDATE trade SET status = '$status', profit = '$profit', credited = 1 WHERE id = '$tid' ");
                //credit user profit
                if ($update && $credited == 0) {
                    switch ($account_type) {
                        case 'live':
                            $col = 'balance';
                            break;
                        case 'demo':
                            $col = 'demo_balance';
                            break;
                        default:
                            break;
                    }
                    $upuser = mysqli_query($link, "UPDATE user SET $col = $col + '$profit' WHERE email = '$email' " );
                }
            }else{

            }


    }
}
    
    ?>
    <link rel="stylesheet" href="../astromine/user/vendors/materialdesignicons.min.css">
    <link rel="stylesheet" href="../astromine/user/vendors/vendor.bundle.base.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- endinject -->
    <!-- plugin css for this page -->
    <link rel="stylesheet" href="../astromine/user/vendors/dataTables.bootstrap4.css">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
        integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <link rel="stylesheet" href="../astromine/user/dash/css/style.css">
    <link rel="stylesheet" href="../astromine/user/dash/css/user-custom.css">
    <script src="../astromine/user/dash/notiflix-aio-3.2.5.min.js"></script>
    <!-- endinject -->
    <link rel="shortcut icon" href="img/logo.png" />

    <script src="../astromine/user/js/jquery-3.2.1.min.js"></script>
</head>

<body id="page-top" class="bgb">
    <div id="wrapper">
        <?php include 'sidebar.php';    ?>


    <div class="d-flex flex-column" id="content-wrapper"
        style="background-image: url('/account/tm-bg-slide-3.jpg?h=f3530972ac2620357b48b5e8cd817fd4');">

        <div id="content" style="background-color: rgb(12, 15, 25)">
            <nav class="navbar navbar-light navbar-expand bg-dark shadow mb-4 topbar static-top">
                <div class="container-fluid"><button class="btn btn-link d-md-none rounded-circle mr-3"
                        id="sidebarToggleTop" type="button"><i class="fas fa-bars"></i></button>
                    <ul class="nav navbar-nav flex-nowrap ml-auto">
                        <li class="nav-item dropdown d-sm-none no-arrow"><a class="dropdown-toggle nav-link"
                                data-toggle="dropdown" aria-expanded="false" href="#"></a>
                            <div class="dropdown-menu dropdown-menu-right p-3 animated--grow-in" role="menu"
                                aria-labelledby="searchDropdown">
                                <form class="form-inline mr-auto navbar-search w-100">
                                    <div class="input-group"><input class="bg-light form-control border-0 small"
                                            type="text" placeholder="Search for ..." />
                                        <div class="input-group-append"><button class="btn btn-primary py-0"
                                                type="button"><i class="fas fa-search"></i></button></div>
                                    </div>
                                </form>
                            </div>
                        </li>
                        <li class="nav-item dropdown no-arrow mx-1" role="presentation">
                            <div class="nav-item dropdown no-arrow"><a class="dropdown-toggle nav-link"
                                    data-toggle="dropdown" aria-expanded="false" href="#"><span
                                        class="badge badge-danger badge-counter">0</span><i
                                        class="fas fa-bell fa-fw"></i></a>
                                <div class="dropdown-menu dropdown-menu-right dropdown-list dropdown-menu-right animated--grow-in"
                                    role="menu">
                                    <h6 class="dropdown-header">alerts center</h6>

                                    <a class="text-center dropdown-item small text-gray-500" href="#">Show All
                                        Alerts</a>
                                </div>
                            </div>
                        </li>

                        <div class="d-none d-sm-block topbar-divider"></div>
                        <li class="nav-item dropdown no-arrow" role="presentation">
                            <div class="nav-item dropdown no-arrow"><a class="dropdown-toggle nav-link"
                                    data-toggle="dropdown" aria-expanded="false" href="#"><span
                                        class="d-none d-lg-inline mr-2 text-gray-600 small"><?php echo $user->getFullname() ?></span><img class="border rounded-circle img-profile"
                                        src="default.png" /></a>
                                <div class="dropdown-menu shadow dropdown-menu-right animated--grow-in" role="menu"><a
                                        class="dropdown-item" role="presentation" href="profile.php"><i
                                            class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>Profile - <?php echo $user->getFullname() ?>
                                        </a><a class="dropdown-item" role="presentation"
                                        href="profile.php"><i
                                            class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>Update Password</a>
                                    <a class="dropdown-item" role="presentation" href="trade_history.php"><i
                                            class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>History</a>
                                    <div class="dropdown-divider"></div><a class="dropdown-item" role="presentation"
                                        href="logout.php"><i
                                            class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>Logout</a>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <div class="container-fluid" style="background-color: rgb(12, 15, 25)">
                <div class="container">
                        <?php

                            
                            if (isset($_GET['unit']) && $_GET['unit'] == 'cfd') {
                                 include 'cfd.php';
                            }elseif (isset($_GET['unit']) && $_GET['unit'] == 'crypto') {
                                include 'crypto.php';
                            }elseif (isset($_GET['unit']) && $_GET['unit'] == 'stock') {
                                include 'stock.php';
                            }elseif (isset($_GET['unit']) && $_GET['unit'] == 'futures') {
                                include 'futures.php';
                            }else{
                                include 'forex.php';
                            }

                        ?>
                        
                        <div class="modal fade" id="buy-trade-modal" tabindex="-1" role="dialog"
                        aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false"
                        data-backdrop="static" style="margin-top: -100px;">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-body pb-4">

                                    <div id="buychart" class="w-100">
                                        <p id="tradeBuySymbolName"></p>
                                        <div class="tradingview-widget-container"
                                            style="height: 150px; border: solid 1px rgb(89, 89, 89)">
                                            <div class="tradingview-widget-container__widget"></div>
                                        </div>
                                    </div>
                                    <form id="buy-trade-form">
                                        <div class="w-100">
                                            <div class="row mt-3">
                                                <div class="col-md-4 col-4">
                                                    <input type="number" name="amount" class="trade-input"
                                                        id="buy-amount" placeholder="Amount">
                                                </div>
                                                <div class="col-4">
                                                    <select class="trade-input" name="units" id="buy-units">
                                                        <option value="">Units</option>
                                                        <option value='1'>1</option>
                                                        <option value='2'>2</option>
                                                        <option value='3'>3</option>
                                                        <option value='4'>4</option>
                                                        <option value='5'>5</option>
                                                        <option value='6'>6</option>
                                                        <option value='7'>7</option>
                                                        <option value='8'>8</option>
                                                        <option value='9'>9</option>
                                                        <option value='10'>10</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-4 col-4">
                                                    <select class="trade-input" name="interval">
                                                        <option value="1 minute">1 minute</option>
                                                        <option value="3 minutes">3 minutes</option>
                                                        <option value="5 minutes">5 minutes</option>
                                                        <option value="10 minutes">10 minutes</option>
                                                        <option value="20 minutes">15 minutes</option>
                                                        <option value="30 minutes">30 minutes</option>
                                                        <option value="45 minutes">45 minutes</option>
                                                        <option value="60 minutes">1 hour</option>
                                                        <option value="120 minutes">2 hours</option>
                                                        <option value="1440 minutes">1 day</option>
                                                    </select>
                                                </div>
                                                <input type="hidden" name="symbol" value="" id="buy-symbol">
                                                <input type="hidden" name="direction" value="buy">
                                            </div>

                                        </div>

                                        <div class="w-100 mt-3" style="text-align:center;">
                                            <p class="text-success">YOU ARE BUYING THE UNDERLYING ASSET</p>
                                        </div>

                                    </form>

                                    <button class="btn btn-md w-100 mt-2 text-white" id="buy-trade-btn"
                                        style="background-color: rgb(31, 105, 84);">OPEN THIS TRADE</button>

                                    <div style="text-align: right;" class="mt-4">
                                        <button class="btn btn-sm btn-danger" id="close-trade-modal">
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24"
                                                height="24">
                                                <path fill="none" d="M0 0h24v24H0z"></path>
                                                <path
                                                    d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm0-9.414l2.828-2.829 1.415 1.415L13.414 12l2.829 2.828-1.415 1.415L12 13.414l-2.828 2.829-1.415-1.415L10.586 12 7.757 9.172l1.415-1.415L12 10.586z"
                                                    fill="rgba(255,255,255,1)"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="sell-trade-modal" tabindex="-1" role="dialog"
                        aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false"
                        data-backdrop="static" style="margin-top: -100px;">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-body pb-4">
                                    <div id="sellchart" class="w-100">
                                        <p id="tradeSellSymbolName"></p>
                                        <div class="tradingview-widget-container"
                                            style="height: 150px; border: solid 1px rgb(89, 89, 89)">
                                            <div class="tradingview-widget-container__widget"></div>
                                        </div>
                                    </div>

                                    <form id="sell-trade-form">
                                        <div class="w-100">
                                            <div class="row mt-3">
                                                <div class="col-md-4 col-4">
                                                    <input type="number" class="trade-input" name="amount"
                                                        id="sell-amount" placeholder="Amount">
                                                </div>
                                                <div class="col-4">
                                                    <select class="trade-input" name="units" id="sell-units">
                                                        <option value="">Units</option>
                                                        <option value='1'>1</option>
                                                        <option value='2'>2</option>
                                                        <option value='3'>3</option>
                                                        <option value='4'>4</option>
                                                        <option value='5'>5</option>
                                                        <option value='6'>6</option>
                                                        <option value='7'>7</option>
                                                        <option value='8'>8</option>
                                                        <option value='9'>9</option>
                                                        <option value='10'>10</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-4 col-4">
                                                    <select class="trade-input" name="interval">
                                                        <option value="1 minute">1 minute</option>
                                                        <option value="3 minutes">3 minutes</option>
                                                        <option value="5 minutes">5 minutes</option>
                                                        <option value="10 minutes">10 minutes</option>
                                                        <option value="20 minutes">15 minutes</option>
                                                        <option value="30 minutes">30 minutes</option>
                                                        <option value="45 minutes">45 minutes</option>
                                                        <option value="60 minutes">1 hour</option>
                                                        <option value="120 minutes">2 hours</option>
                                                        <option value="1440 minutes">1 day</option>
                                                    </select>
                                                </div>

                                                <input type="hidden" name="symbol" value="" id="sell-symbol">
                                                <input type="hidden" name="direction" value="sell">
                                            </div>
                                        </div>

                                        <div class="w-100 mt-3" style="text-align:center;">
                                            <p class="text-danger">YOU ARE SELLING THE UNDERLYING ASSET</p>
                                        </div>

                                    </form>

                                    <button class="btn btn-md w-100 mt-2 text-white" id="sell-trade-btn"
                                        style="background-color: rgba(196, 61, 41, 0.997)">OPEN THIS TRADE</button>

                                    <div style="text-align: right;" class="mt-4">
                                        <button class="btn btn-sm btn-danger" id="close-trade-modal">
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24"
                                                height="24">
                                                <path fill="none" d="M0 0h24v24H0z"></path>
                                                <path
                                                    d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm0-9.414l2.828-2.829 1.415 1.415L13.414 12l2.829 2.828-1.415 1.415L12 13.414l-2.828 2.829-1.415-1.415L10.586 12 7.757 9.172l1.415-1.415L12 10.586z"
                                                    fill="rgba(255,255,255,1)"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <script>
                        $(document).ready(function () {

                            $(document).on('click', '#buy-trade-btn', function () {
                                if ($("#buy-amount").val() == '') {
                                    Notiflix.Notify.failure('The amount field is required');
                                }

                                if ($("#buy-units").val() == '') {
                                    Notiflix.Notify.failure('The units field is required');
                                }

                                if ($("#buy-amount").val() !== '' && $("#buy-units").val() !== '') {
                                    if (parseInt($("#buy-amount").val()) > <?php echo $user->getBalance() ?> ) {
                                        Notiflix.Notify.failure('Insufficient Balance');
                                    } else {
                                        Notiflix.Confirm.show(
                                            'Confirm',
                                            'You are about to open ' + $('#buy-symbol').val() + ' trade ',
                                            'Yes',
                                            'No',
                                            () => {
                                                $('#buy-trade-form').submit()
                                            },
                                        );
                                    }

                                }
                            });

                            $(document).on('click', '#sell-trade-btn', function () {
                                if ($("#sell-amount").val() == '') {
                                    Notiflix.Notify.failure('The amount field is required');
                                }

                                if ($("#sell-units").val() == '') {
                                    Notiflix.Notify.failure('The units field is required');
                                }

                                if ($("#sell-amount").val() !== '' && $("#sell-units").val() !== '') {
                                    if (parseInt($("#sell-amount").val()) > <?php echo $user->getBalance() ?> ) {
                                        Notiflix.Notify.failure('Insufficient Balance');
                                    } else {
                                        Notiflix.Confirm.show(
                                            'Confirm',
                                            'You are about to open ' + $('#sell-symbol').val() + ' trade ',
                                            'Yes',
                                            'No',
                                            () => {
                                                $('#sell-trade-form').submit()
                                            },
                                        );
                                    }

                                }
                            });

                            $(document).on('submit', '#buy-trade-form', function (e) {

                                e.preventDefault();
                                $("#buy-trade-btn").prop("disabled", true);

                                $.ajaxSetup({
                                    headers: {
                                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                    }
                                });

                                $.ajax({
                                    url: "trade.php",
                                    type: "POST",
                                    data: new FormData(this),
                                    contentType: false, // The content type used when sending data to the server.
                                    cache: false, // To unable request pages to be cached
                                    processData: false,
                                    success: function (e) {
                                        Notiflix.Report.success(
                                            'Placed',
                                            e + '<br><br>',
                                            'Okay',
                                            () => {
                                                window.location.href = "trade_history.php"
                                            }
                                        );
                                    },
                                    error: function (e) {
                                        if (e.status === 422) {
                                            Object.entries(e.responseJSON.errors).forEach(element => {
                                                Notiflix.Notify.failure(element[1][0]);
                                            });
                                        }
                                        if (e.status === 400) {
                                            Notiflix.Notify.failure(e.responseJSON.message);
                                        }
                                        $("#buy-trade-btn").prop("disabled", false);
                                    }
                                });
                            })

                            $(document).on('submit', '#sell-trade-form', function (e) {

                                e.preventDefault();
                                $("#sell-trade-btn").prop("disabled", true);

                                $.ajaxSetup({
                                    headers: {
                                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                    }
                                });

                                $.ajax({
                                    url: "trade.php",
                                    type: "POST",
                                    data: new FormData(this),
                                    contentType: false, // The content type used when sending data to the server.
                                    cache: false, // To unable request pages to be cached
                                    processData: false,
                                    success: function (e) {
                                        Notiflix.Report.success(
                                            'Placed',
                                            e + '<br><br>',
                                            'Okay',
                                            () => {
                                                window.location.href = "trade_history.php"
                                            }
                                        );
                                    },
                                    error: function (e) {
                                        if (e.status === 422) {
                                            Object.entries(e.responseJSON.errors).forEach(element => {
                                                Notiflix.Notify.failure(element[1][0]);
                                            });
                                        }
                                        if (e.status === 400) {
                                            Notiflix.Notify.failure(e.responseJSON.message);
                                        }
                                        $("#sell-trade-btn").prop("disabled", false);
                                    }
                                });
                            })

                            $(document).on('click', '#trade-buy-btn', function () {
                                let e_ = $(this);

                                var my_awesome_script = document.createElement('script');

                                my_awesome_script.setAttribute('src',
                                    "https://s3.tradingview.com/external-embedding/embed-widget-single-quote.js");
                                my_awesome_script.textContent = `
                    {
                    "symbol": "${e_.data('tv-symbol')}",
                    "width": "100%",
                    "colorTheme": "dark",
                    "isTransparent": false,
                    "locale": "en"
                    }
                `;
                                my_awesome_script.async = true
                                document.querySelector('#buychart div').appendChild(my_awesome_script);
                                $('#tradeBuySymbolName').html(e_.data('symbol'))
                                $('#buy-symbol').val(e_.data('symbol'))
                                $('#buy-trade-modal').modal('show');
                            })

                            $(document).on('click', '#trade-sell-btn', function () {
                                let e_ = $(this);

                                var my_awesome_script = document.createElement('script');

                                my_awesome_script.setAttribute('src',
                                    "https://s3.tradingview.com/external-embedding/embed-widget-single-quote.js");
                                my_awesome_script.textContent = `
                    {
                    "symbol": "${e_.data('tv-symbol')}",
                    "width": "100%",
                    "colorTheme": "dark",
                    "isTransparent": false,
                    "locale": "en"
                    }
                `;
                                my_awesome_script.async = true
                                document.querySelector('#sellchart div').appendChild(my_awesome_script);
                                $('#tradeSellSymbolName').html(e_.data('symbol'))
                                $('#sell-symbol').val(e_.data('symbol'))
                                $('#sell-trade-modal').modal('show');
                            })

                            $(document).on('click', '#close-trade-modal', function () {
                                $('#buy-trade-modal').modal('hide');
                                $('#sell-trade-modal').modal('hide');
                                $('#tradeBuySymbolName').html('');
                                $('#tradeSellSymbolName').html('');
                                $('#buychart div').html('');
                                $('#sellchart div').html('');
                                $('#buy-symbol').val('')
                                $('#sell-symbol').val('')
                                $('#buy-amount').val('')
                                $('#sell-amount').val('')
                                $('#buy-units').val('')
                                $('#sell-units').val('')
                            })

                        });

        // Toastify({
        //     text: "This is a toast",
        //     duration: 3000,
        //     destination: "https://github.com/apvarun/toastify-js",
        //     newWindow: true,
        //     close: true,
        //     gravity: "top", // `top` or `bottom`
        //     position: "left", // `left`, `center` or `right`
        //     stopOnFocus: true, // Prevents dismissing of toast on hover
        //     style: {
        //         background: "linear-gradient(to right, #00b09b, #96c93d)",
        //     },
        //     onClick: function() {} // Callback after click
        // }).showToast();
                    </script>
            </div>
        </div>

        <?php include 'footer.php';    ?></body>

</html>