<?php include ("header.php");?> 
<?php 
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['copy'])) {
   echo "<script>alert('You have successfully started copying this trader.'); window.location='dashboard.php';</script>";
   
}
?>
<div class="dashboard-body">
<div class="d-flex justify-content-between mb-3 align-items-center dashboardBodyNav">
   <!----> 
</div>
<div class="container">
   <div class="d-flex justify-content-center">
      <div class="toggle-buttons">
         <button id="providerBtn" class=" active  " onclick="if (!window.__cfRLUnblockHandlers) return false; showProvider()">All Traders</button>
      </div>
   </div>
   <div class="container content   active " id="providerContent">
      <div class="publisher-area">
         <div class="publisher">
            <div class="">
               <div class="row gy-4 justify-content-center">
                  <?php
                     // Fetch all trader data
                     $sql = "
                         SELECT 
                             name AS trader_name,
                             username AS trader_username,
                             gain_percentage,
                             risk_level,
                             trades,
                             investment_capital,
                             copiers,
                             avatar,
                             avg_trade_time,
                             id
                         FROM traders";
                         
                     $result = $conn->query($sql);
                     ?>
                  <?php while ($trader = $result->fetch_assoc()): ?>
                  <div class="col-xxl-3 col-sm-6">
                     <div class="dashboard-cardo">
                        <div class="d-flex justify-content-between align-items-center">
                           <div class="dashboard-card__content">
                              <p class="dashboard-card__coin-titl d-flex justify-content-between">
                                 <span><?php echo $trader['trader_name']; ?></span>
                                 <span>
                                 <img src="assets/images/user_rankings/66928c5d723ca1720880221.png" alt="image" style="width: 20px; height: 20px; margin-top: 5px; margin-left: 4px;">
                                 </span>
                              </p>
                              <a class="text--base text--small" href="trader/profile/<?php echo $trader['trader_username']; ?>">
                              <span>@</span><?php echo $trader['trader_username']; ?>
                              </a>
                           </div>
                           <div class="dashboard-card__content">
                              <div class="text-center">
                                 <img class="user-img" src="assets/images/currency/<?php echo $trader['avatar']; ?>">
                              </div>
                              
                           </div>
                        </div>
                        <hr>
                        <div class="tab-content mt-2">
                           <div class="tab-pane fade show active d-flex d-xl-block flex-wrap gap-2">
                              <div class="trading-left__buy flex-fill">
                                 <div class="trading-left__header flex-between sell-side-order-list-header">
                                    <span class="price__title text-success switch">
                                    <?php echo $trader['gain_percentage']; ?>%
                                    <small class="alert__title text--smaller">Gain</small>
                                    </span>
                                    <span class="amount__title switch">
                                       <p class="just-center self-center risk-indicator circled low"><?php echo $trader['risk_level']; ?></p>
                                       <small class="alert__title text--smaller">Risk</small>
                                    </span>
                                    <span class="total__title switch">
                                    <?php echo number_format($trader['trades']); ?>
                                    <small class="alert__title text--smaller">Trades</small>
                                    </span>
                                    <span class="total__title switch">
                                    $<?php echo number_format($trader['investment_capital']); ?>
                                    <small class="alert__title text--smaller">Inv. Capital</small>
                                    </span>
                                 </div>
                                 <div class="sell-side-order-list"></div>
                              </div>
                           </div>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-3">
                           <div class="dashboard-card__content">
                              <p class="price__title text--small"><?php echo $trader['copiers']; ?> Copiers</p>
                           </div>
                           <div class="dashboard-card__content">
                              <button class="deposit__button btn btn--base w-100" style="padding: 10px 40px!important; font-size: 0.90rem;" data-toggle="modal" data-target="#copyModal<?php echo $trader['trader_username']; ?>">
                              Copy
                              </button>
                           </div>
                        </div>
                     </div>
                  </div>
                  <!-- Modal Structure for Each Trader -->
                  <div class="modal fade" id="copyModal<?php echo $trader['trader_username']; ?>" role="dialog">
                     <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                           <div class="modal-header">
                              <h5 class="modal-title" id="exampleModalLongTitle">Copy <?php echo $trader['trader_name']; ?>'s Trade</h5>
                              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                              </button>
                           </div>
                           <div class="modal-body" style="background-color: #05212a;">
                              <div class="hide--desktop row dashboard-card col-xxl-12 col-md-12" style="margin-left: 0px;">
                                 <div class="row d-flex" style="margin-left: 0px;">
                                    <div class="d-flex justify-content-between align-items-center col-6 mt-4">
                                       <span class="dashboard-card__icon text--success">
                                          <div class="dashboard-card__content">
                                             <div class="text-center">
                                                <img class="user-img-modal" src="assets/images/currency/<?php echo $trader['avatar']; ?>">
                                             </div>
                                             <div class="d-flex justify-content-flex-end">
                                                <img class="flag-img-modal" src="assets/images/language/64aa848532bab1688896645.png">
                                             </div>
                                          </div>
                                       </span>
                                       <span class="m-2"></span>
                                       <span class="dashboard-card__coin-titl switch">
                                          <div class="d-flex justify-content-between">
                                             <span><?php echo $trader['trader_name']; ?> </span>  <span><img src="assets/images/user_rankings/64f904f19bf161694041329.png" alt="image" style="width: 20px; height: 20px; margin-top: 5px; margin-left: 4px;"> </span>
                                          </div>
                                          <p class="text--base text--small"><span>@</span><?php echo $trader['trader_username']; ?></p>
                                       </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-right col-6">
                                       <div class="dashboard-card__content">
                                          <p class="dashboard-card__coin-name mb-0 ">
                                             <span class="price__title text-success switch fs-15">
                                             <?php echo $trader['gain_percentage']; ?>%
                                             <small class="alert__title text--small">Gain</small>
                                             </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="text--base text--small switch fs-15"> <?php echo number_format($trader['trades']); ?>
                                          <small class="alert__title text--small">Trades</small>
                                          </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="amount__title switch">
                                             <p class="price__title just-center self-center fs-15"> $<?php echo number_format($trader['investment_capital']); ?></p>
                                             <small class="alert__title text--small" style="display: block;">Inv. Capital</small>
                                          </span>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row d-flex" style="margin-left: 0px;">
                                    <div class="d-flex justify-content-between align-items-center col-6">
                                       <span class="dashboard-card__icon text--success">
                                          <div class="dashboard-card__content">
                                          </div>
                                       </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-right col-6">
                                       <div class="dashboard-card__content">
                                          <span class="amount__title switch d-flex">
                                             <div>
                                                <p class="just-center self-center risk-indicator circled low"><?php echo $trader['risk_level']; ?></p>
                                             </div>
                                             <div>
                                                <small class="alert__title text--smaller" style="display: block;">Risk rate</small>
                                             </div>
                                          </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <p class="dashboard-card__coin-name mb-0 ">
                                             <span class="price__title text-success switch fs-15">
                                             <?php echo $trader['copiers']; ?>
                                             <small class="alert__title text--smaller">No. Copiers</small>
                                             </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="total__title text--base switch"><?php echo $trader['avg_trade_time']; ?> Days
                                          <small class="alert__title text--smaller">Avg. Trade Time</small>
                                          </span>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              <div class="hide--mobile row dashboard-card col-xxl-12 col-md-12" style="margin-left: 0px;">
                                 <div class="row d-flex" style="margin-left: 0px;">
                                    <div class="d-flex justify-content-between align-items-center col-12 mt-4">
                                       <span class="dashboard-card__icon text--success">
                                          <div class="dashboard-card__content">
                                             <div class="text-center">
                                                <img class="user-img-modal" src="assets/images/currency/<?php echo $trader['avatar']; ?>">
                                             </div>
                                             <div class="d-flex justify-content-flex-end">
                                                <img class="flag-img-modal" src="assets/images/language/64aa848532bab1688896645.png">
                                             </div>
                                          </div>
                                       </span>
                                       <span class="m-2"></span>
                                       <span class="dashboard-card__coin-titl switch">
                                          <div class="d-flex justify-content-between">
                                             <span><?php echo $trader['trader_name']; ?> </span>  <span><img src="assets/images/user_rankings/64f904f19bf161694041329.png" alt="image" style="width: 20px; height: 20px; margin-top: 5px; margin-left: 4px;"> </span>
                                          </div>
                                          <p class="text--base text--small"><span>@</span><?php echo $trader['trader_username']; ?></p>
                                       </span>
                                    </div>
                                    <div class="mt-5 d-flex justify-content-between align-items-right col-12">
                                       <div class="dashboard-card__content">
                                          <p class="dashboard-card__coin-name mb-0 ">
                                             <span class="price__title text-success switch fs-15">
                                             <?php echo $trader['gain_percentage']; ?>%
                                             <small class="alert__title text--small">Gain</small>
                                             </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="text--base text--small switch fs-15"><?php echo number_format($trader['trades']); ?>
                                          <small class="alert__title text--small">Trades</small>
                                          </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="amount__title switch">
                                             <p class="price__title just-center self-center fs-15"> $<?php echo number_format($trader['investment_capital']); ?></p>
                                             <small class="alert__title text--small" style="display: block;">Inv. Capital</small>
                                          </span>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row d-flex" style="margin-left: 0px;">
                                    <div class="d-flex justify-content-between align-items-right col-12">
                                       <div class="dashboard-card__content">
                                          <span class="amount__title switch d-flex">
                                             <div>
                                                <p class="just-center self-center risk-indicator circled low"><?php echo $trader['risk_level']; ?></p>
                                             </div>
                                             <div>
                                                <small class="alert__title text--smaller" style="display: block;">Risk rate</small>
                                             </div>
                                          </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <p class="dashboard-card__coin-name mb-0 ">
                                             <span class="price__title text-success switch fs-15">
                                             <?php echo $trader['copiers']; ?>
                                             <small class="alert__title text--smaller">No. Copiers</small>
                                             </span>
                                       </div>
                                       <div class="dashboard-card__content">
                                          <span class="total__title text--base switch"><?php echo $trader['avg_trade_time']; ?> Days
                                          <small class="alert__title text--smaller">Avg. Trade Time</small>
                                          </span>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </div>
                           <div class="modal-body">
                           <form method="POST" id="copyForm<?php echo $trader['id']; ?>">
                              <input type="hidden" name="trader_id" value="<?php echo $trader['id']; ?>">
                              <div class="containero">
                                 <!-- Amount input section (optional) -->
                                 <div class="amount-input d-none">
                                    <button type="button" onclick="decreaseAmount<?php echo $trader['id']; ?>()">-</button>
                                    <input type="text" name="investment_amount" id="amount<?php echo $trader['id']; ?>" value="<?=$trader['investment_capital']?>" oninput="updateAmountMessage<?php echo $trader['id']; ?>()">
                                    <button type="button" onclick="increaseAmount<?php echo $trader['id']; ?>()">+</button>
                                 </div>

                                 <small>Total Balance: <span style="font-weight: 600;">$<?=number_format($total_balance,2)?> USD</span></small>

                                 <div class="info"><div>10% commission fee on earning</div></div>
                                 <div class="warning" id="amountMessage<?php echo $trader['id']; ?>">Pay $<?php echo number_format($trader['investment_capital']); ?> in order to continue</div>

                                 <button type="button" class="deposit-btn" onclick="submitCopyForm<?php echo $trader['id']; ?>()">DEPOSIT</button>

                                 <div class="copy-trades">
                                    <div>Open trades will be copied from the Leader under the current market conditions and rates of the assets.</div>
                                 </div>
                              </div>
                           </form>

                           <script>
                              function submitCopyForm<?php echo $trader['id']; ?>() {
                                 const form = $("#copyForm<?php echo $trader['id']; ?>");
                                 const formData = form.serialize(); // serialize form data

                                 $.ajax({
                                    url: "processor.php?copytrader", // Your PHP backend script
                                    method: "POST",
                                    data: formData + "&copy=1", // Add action identifier
                                    success: function(response) {
                                          try {
                                             const res = JSON.parse(response);
                                             if (res.status === "success") {
                                                alert(res.message);
                                                window.location.href = "dashboard.php";
                                             } else {
                                                alert(res.message || "An error occurred.");
                                             }
                                          } catch (e) {
                                             console.error("Invalid JSON response", response);
                                             alert("Unexpected server response.");
                                          }
                                    },
                                    error: function(xhr) {
                                          alert("AJAX request failed: " + xhr.statusText);
                                    }
                                 });
                              }
                              </script>


                              <script type="4d45ef26de46de20206471d1-text/javascript">
                                 let originalAmount<?php echo $trader['id']; ?> = <?=$trader['investment_capital']?>;
                                     
                                 function decreaseAmount<?php echo $trader['id']; ?>() {
                                     
                                     let amount = parseInt(document.getElementById('amount<?php echo $trader['id']; ?>').value);
                                     
                                     if (amount > originalAmount<?php echo $trader['id']; ?>) {
                                         document.getElementById('amount<?php echo $trader['id']; ?>').value = amount - 50;
                                         updateAmountMessage<?php echo $trader['id']; ?>();
                                     }
                                     
                                     toggleDecreaseButton<?php echo $trader['id']; ?>();
                                 }
                                 
                                     function increaseAmount<?php echo $trader['id']; ?>() {
                                         let amount = parseInt(document.getElementById('amount<?php echo $trader['id']; ?>').value);
                                         document.getElementById('amount<?php echo $trader['id']; ?>').value = amount + 50;
                                         updateAmountMessage<?php echo $trader['id']; ?>();
                                     }
                                 
                                     function updateAmountMessage<?php echo $trader['id']; ?>() {
                                         let amount = parseInt(document.getElementById('amount<?php echo $trader['id']; ?>').value);
                                         document.getElementById('amountMessage<?php echo $trader['id']; ?>').innerText = `Deposit $${amount.toFixed(2)}, in order to continue`;
                                     }
                                     
                                 
                                     function toggleDecreaseButton<?php echo $trader['id']; ?>() {
                                     let amount = parseInt(document.getElementById('amount<?php echo $trader['id']; ?>').value);
                                     document.getElementById('decrease<?php echo $trader['id']; ?>').disabled = amount <= originalAmount<?php echo $trader['id']; ?>;
                                     }
                                 
                                     toggleDecreaseButton<?php echo $trader['id']; ?>();
                                 
                              </script>
                           </div>
                           <div class="modal-footer">
                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                           </div>
                        </div>
                     </div>
                  </div>
                  <?php endwhile; ?>
               </div>
            </div>
         </div>
      </div>
      <div class="" style="margin: 50px 0px auto;">
         <center>
            <a href="trader" style="text-decoration:none" class="sc-d56ac5c9-0 jVdhmX">
               <div color="#01a7d3" class="sc-496e28ab-0 dCOKro sc-84092d93-7 dvkGAp"><span>+1,233 MORE PRIVATE TRADERS</span></div>
            </a>
         </center>
      </div>
   </div>
</div>
<?php include "modals.php";?>