<style>
.market-trade-list li a {
    background: #eff2f6;
    color: #4a4a4a;
    font-weight: 300;
    padding: 3px 15px;
    border-radius: 5px;
}

.market-trade-list li {
    display: inline-block;
    margin-right: 7px;
    margin-bottom: 20px;
}

.market-trade-list li:last-child {
    margin-right: 0;
}

.market-trade-list li a:hover {
    text-decoration: none;
    background: #26a69a;
    color: #fff;
}
.trade-active {
    text-decoration: none;
    background: #26a69a !important;
    color: #fff !important;
}
.market-trade-percentage li a {
    background: #eff2f6;
    color: #4a4a4a;
    font-weight: 300;
    padding: 3px 15px;
    border-radius: 5px;
}

.market-trade-percentage li {
    display: inline-block;
    margin-right: 7px;
    margin-bottom: 20px;
}

.market-trade-percentage li:last-child {
    margin-right: 0;
}

.market-trade-percentage li a:hover {
    text-decoration: none;
    background: #26a69a;
    color: #fff;
}
.percentage-active {
    text-decoration: none;
    background: #26a69a !important;
    color: #fff !important;
}
 .buy,.sell {
    background: #09D670FF;
    color: #fff;
    text-transform: uppercase;
    padding: 10px;
    margin-top: 30px;
    width: 100%;
    box-shadow: 0px 0px 15px 0px #09d670ffad;
}
.sell {
    background: #C01816FF;
    box-shadow: 0px 0px 15px 0px #C01816FFad;
}
.buytrade{ 
    background: #09D670FF;
    color: #fff;
    font-size:0.6em;
    padding:5px;
}
.selltrade{ 
    background: #C01816FF;
    color: #fff;
    font-size:0.6em;
    padding:5px;
}
.closetradebtn{
font-size: 9px !important;
padding: 5px 15px !important;
}

.profit-display {
            font-size: 24px;
            font-weight: bold;
            margin-top: 20px;
        }

        .profit-increase {
            color: green;
        }

        .profit-decrease {
            color: red;
        }
        option {
            color:black;
        }
    </style>

    <div class="page-container">
        <div class="main-content">
            <div class="section-gap">
                <div class="container-fluid">
                                        <!--Page Content-->
     <?php 
     $ranks = [
         "Member"=>["name"=>"Member","title"=>"By signing up to the account","image"=>"sCQgIyl0OKzFiO73nmWF.svg"],
         "Leader"=>["name"=>"Leader","title"=>"By earning ".'$50'." from the site","image"=>"TQDUvbD48kmhmV9qifzh.svg"],
         "Captain"=>["name"=>"Captain","title"=>"By earning ".'$200'." from the site","image"=>"hGHllGGCIYfpx5Z2VKrW.svg"],
         "Victor"=>["name"=>"Victor","title"=>"By earning ".'$500'." from the site","image"=>"SaNfYL7WD2pzAAME8Sqb.svg"],
         ];
         
        if($current_active_plan == "Member" || $current_active_plan == "")
            {   
                $activeRank = $ranks['Member'];
            }else{
                $activeRank = $ranks[$current_active_plan];
            }
     ?>               
    
    <div class="row">
        <div class="col-md-12"> 
            <h3 class="my-1 p-1">Welcome, <?php echo $customer_fname.' '.$customer_lname; ?></h3> 
        </div> 
    </div>

    <div class="row sm-gutters">
      <div class="col-md-12 mb15">
        <!-- TradingView Widget BEGIN -->
        <div class="tradingview-widget-container">
          <div class="tradingview-widget-container__widget"></div>
          <script type="text/javascript" src="external-embedding/embed-widget-ticker-tape.js" async="">
            </script>
        </div>
        <!-- TradingView Widget END -->
      </div>
      <div class="col-md-6 mt-4">
          <div class="site-card w-100">
          <div class="site-card-header">
                    <h3 class="title">Open Trade</h3>
                    <!-- <div class="card-header-links">
                        <a href="/user/deposit/log"
                           class="card-header-link">Deposit History</a>
                    </div> -->
                </div>
            <div class="site-card-body">
                <div class="progress-steps-form">
                <ul class="market-trade-list">
                    <li><a href="#!" data-market="Stocks">Stock</a></li>
                    <li><a href="#!" data-market="Crypto">Crypto</a></li>
                    <li><a href="#!" data-market="Indices">Indices</a></li>
                    <li><a href="#!" data-market="Forex">Forex</a></li>
                    <li><a href="#!" data-market="Commodities">Commodities</a></li>
                </ul>
                <form action="/user/dashboard" method="POST" onsubmit="return checksubmit()">
                <div class="input-group">
                <select class="form-control" onchange="runtradebar(this.value)"  id="tradingPairSelect" name="trading_pairs" required>
                 </select>
                      <span class="input-group-text">Pairs</span>
                  </div>
                  <div class="input-group">
                <select class="form-control" disabled>
                  <option value="">Market Price</option>
                 </select>
                      <span class="input-group-text">Entry</span>
                  </div>
                  <input type="hidden" name="trade_market" id="trade_market" required>
                  <div class="input-group">  
                    <input type="number" name="inv_amount" id="inv_amount" class="form-control" min="5" step="0.01" placeholder="Price" required>
                      <span class="input-group-text">USD</span>
                  </div>
                  <!-- <div class="input-group">
                    <input type="number" class="form-control" placeholder="Amount">
                    <div class="input-group-append">
                      <span class="input-group-text">ETH</span>
                    </div>
                  </div> -->
                  <p class="w-100 d-flex justify-content-end">Available: <span>$<?php echo number_format($wallet_balance,2); ?></span></p>
                  <ul class="market-trade-percentage">
                    <li><a href="#!" data-percentage="25">25%</a></li>
                    <li><a href="#!" data-percentage="50">50%</a></li>
                    <li><a href="#!" data-percentage="75">75%</a></li>
                    <li><a href="#!" data-percentage="100">100%</a></li>
                  </ul>
                <div class="input-group">
                <select class="form-control" name="investment_time" required>
                  <?php for($x=1;$x<60;$x++){ ?>
                  <option value="<?php echo $x; ?>"><?php echo $x; ?> Minute</option>
                  <?php } ?>
                 </select>
                      <span class="input-group-text">Trading Time</span>
                  </div>

                  <!-- <p>Volume: <span>0 BTC = 0 USD</span></p>
                  <p>Margin: <span>0 BTC = 0 USD</span></p> -->
                  <p class="w-100 d-flex justify-content-end">Fee: <span>$0.021</span></p>
                  <div class="d-flex justify-content-between">
                  <button class="btn sell" name="opentrade" type="submit" value="sell" style="margin-right:10px">Sell</button>
                  <button class="btn buy" name="opentrade" type="submit" value="buy" style="margin-left:10px">Buy</button>
                  </div>
                </form>
                <script>
                
                     var totalBal = '<?php echo $wallet_balance; ?>'; 
                     var is_total_day_limit_true = <?php echo ($is_total_day_limit_true)? 'true' : 'false'; ?>;
                     function checksubmit(){
                            if(parseInt(totalBal) < document.querySelector('#inv_amount').value){     
                                    Swal.fire({
                                            icon: 'error',
                                            title: 'Balance too Low to Trade',
                                            text: 'Fund your Account, and try again!'
                                            });
                            return false;
                                       }
                        if(is_total_day_limit_true){
                            Swal.fire({
                                            icon: 'error',
                                            title: 'Daily Limit Reached',
                                            text: 'Please Wait till tomorrow to trade again, or upgrade your plan!'
                                            });
                            return false;
                        }
                        return true;
                    }
                const percentageLinks = document.querySelectorAll('.market-trade-percentage a');
                const percentageInput = document.getElementById('inv_amount');
                const totalNumber = parseInt(totalBal); // Replace this with the number you want to calculate percentages of

                percentageLinks.forEach(link => {
                link.addEventListener('click', function(event) {
                // Remove the active class from all links
                document.querySelectorAll('.market-trade-percentage li a').forEach(item => item.classList.remove('percentage-active'));
                // Add the active class to the clicked link
                this.classList.add('percentage-active');
                event.preventDefault();
                const percentage = this.getAttribute('data-percentage');
                const calculatedValue = (percentage / 100) * totalNumber;
                percentageInput.value = calculatedValue;
            });
        });
                </script>  
                </div>
              </div>
            </div>
</div>
<div class="col-md-6 mt-4">
        <div class="site-card">
            <div class="site-card-header">
                <h3 class="title">Active Trades</h3>
                <div class="card-header-links">
                        <a href="/user/trade-logs"
                           class="card-header-link">Trade History</a>
                    </div>
            </div>
            <div class="site-card-body table-responsive">
            <?php 
            
            // print_r(($assist->getJSONActiveTrade()));
            $isTradeEmpty = (count($assist->getActiveTrades()) === 0)?true:false;
            foreach($assist->getActiveTrades() as $trades){ ?>
            <div class="site-card" style="margin-bottom:5px;">
                <div class="site-card-header">
                    <h3 class="title"><span class="<?php echo ($trades['trade_type']=='sell')?'selltrade':'buytrade'; ?>" style="text-transform: uppercase;"><?php echo $trades['trade_type']; ?></span> <?php $trading_pairs = explode(':',$trades['trading_pairs']); echo $trading_pairs[1].'('.$trades['trade_market'].')'; ?></h3>
                    <div class="card-header-links">
                        <a href="/user/deposit/log"
                           class="card-header-link small bg-danger closetradebtn">close trade</a>
                    </div>
                </div>
                <div class="site-card-body">
                     <div class="row">
                        <div class="col-4"><small>Time:</small><h5 style="font-size:1em;font-weight:600;color:#0765F3FF;"><?php echo $trades['investment_time']; ?> Mins</h5></div>
                        <div class="col-4"><small>Price(USDT):</small><h5 style="font-size:1em;"><?php echo number_format($trades['invest_amount'],2); ?></h5></div>
                        <div class="col-4"><small>PnL(USDT):</small><h5 style="font-size:1em;font-weight:800;" id="displayprofit-<?php echo $trades['investment_id']; ?>">+<?php echo number_format(200,2); ?></h5></div>
                        <div class="col-4"><small>Type:</small><h5 style="font-size:1em;"><?php echo $trades['trade_market']; ?></h5></div>
                        <div class="col-4"><small>Execution:</small><h5 style="font-size:1em;font-weight:800;color:#26a69a;"><?php echo $trades['execution']; ?></h5></div>
                        <div class="col-4"><small>Status:</small><h5 style="font-size:1em;font-weight:800;color:#20C50AFF;"><?php echo $trades['trade_status']; ?></h5></div>
                        <div class="col-12"><small>Total loss prevention implemented!</small></div>
                     </div>
                     <!-- <div class="profit-display" id="profitDisplay">$0.00</div> -->
                </div>
            </div>
            <?php } 
            if($isTradeEmpty){
                ?>

        <div class="col-md-12 col-12 d-flex justify-content-center">
            <div class="w-100 d-flex flex-column justify-content-center align-items-center" style="height:200px">
                <i class="anticon anticon-file" style="font-size:70px;color:gray"></i>
                <h4 style="font-size:1em; margin-top:30px;color:gray">No Active Trade!</h4>
            </div>
        </div>

        <?php
            }
            
            ?>
                
            </div>


        </div>
</div>
      <div class="col-md-12">
        <div class="main-chart" style="height:500px">
<!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container" style="height:100%;width:100%">
  <div class="tradingview-widget-container__widget" style="height:calc(100% - 32px);width:100%"></div>
  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js" async>
  {
  "autosize": true,
  "symbol": "BINANCE:BTCUSDT",
  "interval": "D",
  "timezone": "Etc/UTC",
  "theme": "light",
  "style": "1",
  "locale": "en",
  "allow_symbol_change": true,
  "calendar": false,
  "support_host": "https://www.tradingview.com"
}
  </script>
</div>
<!-- TradingView Widget END -->
        </div>
      </div>
      <!-- <div class="mt-2" style="border: 1px solid #363a45"> -->


      <!-- </div> -->
      
      
      
      </div>  

                    <!--Page Content-->
                </div>
            </div>
        </div>
    </div>


    <!-- Automatic Popup -->
<?php if($welcome_modal == "true"){
    $assist->updateWelcome();
    ?> 
<div id="auto-popup" class="auto-popup-section">
    <div class="auto-popup-dialog animated fadeInUp">
        <button class="auto-popup-close auto-popup-close-now" onclick="updatePopup()"><i icon-name="x"></i></button>
        <div class="auto-popup-dialog-inner"
             style="background: url(/images/auto-pop.jpg) no-repeat;">
            <div class="row">
                <div class="col-md-12 col-12">
                    <div class="auto-pop-content">
                        <h2>Congratulation!</h2>
                        <h3>You got a Signup Bonus
                            <span>5 USD</span></h3>
                        <button class="site-btn grad-btn auto-popup-close-now" onclick="updatePopup()"><i
                                class="anticon anticon-check"></i> Got it</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php } ?>

<script src="/app/index.js"></script>
<!-- <script>
        // Configuration
        const initialProfit = 100; // Starting profit
        const targetProfit = -1000; // Target profit to reach
        const totalMinutes = 0.5; // Number of minutes to reach the target profit
        const intervalTime = 1000; // Update every 1 second (1000 milliseconds)
        const allowDecrement = true; // Set to true to allow random decrements in the profit

        const totalSteps = (totalMinutes * 60 * 1000) / intervalTime; // Total number of steps for updates
        const averageStepChange = Math.abs(targetProfit - initialProfit) / totalSteps; // Average change per step
        let currentProfit = initialProfit;
        let previousProfit = initialProfit;

        const profitDisplay = document.getElementById('profitDisplay');

        function simulateProfitFluctuation() {
            previousProfit = currentProfit;

            // Determine if we should increase or decrease profit
            let isIncrease = allowDecrement ? Math.random() > 0.5 : false; // 50% chance to increase if decrements are allowed

            // If the target profit is negative, we need to prioritize decreasing
            if (targetProfit < 0 && currentProfit > targetProfit) {
                isIncrease = false; // Force decrease to reach the negative target
            }

            const fluctuationAmount = Math.random() * averageStepChange;

            // Adjust profit based on the direction
            currentProfit += isIncrease ? fluctuationAmount : -fluctuationAmount - averageStepChange;

            // Ensure the profit does not exceed the initial profit or fall below the target profit
            currentProfit = Math.max(targetProfit, Math.min(currentProfit, initialProfit));

            // Update the display
            updateProfitDisplay(currentProfit, previousProfit);

            // Continue the simulation until we reach the target profit
            if (currentProfit > targetProfit) {
                setTimeout(simulateProfitFluctuation, intervalTime);
            }
        }

        function updateProfitDisplay(current, previous) {
            const formattedProfit = `$${current.toFixed(2)}`;
            profitDisplay.textContent = formattedProfit;

            // Change the display color based on the profit value
            if (current < 0) {
                // If the profit is negative, always show red color
                profitDisplay.classList.remove('profit-increase');
                profitDisplay.classList.add('profit-decrease');
            } else {
                // Default logic for positive values
                if (current > previous) {
                    profitDisplay.classList.remove('profit-decrease');
                    profitDisplay.classList.add('profit-increase');
                } else {
                    profitDisplay.classList.remove('profit-increase');
                    profitDisplay.classList.add('profit-decrease');
                }
            }
        }

        // Start the simulation
        simulateProfitFluctuation();
    </script> -->