<!DOCTYPE html>
<html lang="en">
<?php
include('include/head.php');
include("loginCheck.php");
include('include/header.php');
include('include/menu.php');
?>
<style>
  .amount{
    display: flex;
    justify-content: space-between;
  }
</style>
<div id="main-content">
  <div class="container-fluid">
    <div class="block-header">
      <div class="row">
        <div class="col-lg-5 col-md-8 col-sm-12">
          <h2>
            <a href="javascript:void(0);" onclick="window.history.back();"
              class="btn btn-xs btn-link btn-toggle-fullwidth">
              <i class="fa fa-arrow-left"></i>
            </a>
            Popup Update
          </h2>
          <ul class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard"><i class="icon-home"></i></a></li>
            <li class="breadcrumb-item">Setting</li>
            <li class="breadcrumb-item active">Bet Update</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="row clearfix">
      <div class="col-lg-12 col-md-12 col-sm-12">
        <!-- Popup Update Section -->
        <div class="card">

          <div class="body">
            <div class="table-responsive">
              <?php
              $queryTradeTotals = mysqli_query($con, "
  SELECT 
    SUM(CASE WHEN trade_options = 'CALL' THEN tradeAmount ELSE 0 END) AS total_Call,
    SUM(CASE WHEN trade_options = 'PUT' THEN tradeAmount ELSE 0 END) AS total_Put
  FROM meddolic_user_trade_history
");

$valTradeTotals = mysqli_fetch_array($queryTradeTotals);
$totalCall = $valTradeTotals['total_Call'] ?? 0;
$totalPut  = $valTradeTotals['total_Put'] ?? 0;
              ?>
              <div class="amount">
                  <h5> Total Call Amount: <span class="badge badge-success"> $ <?= $totalCall ?></span> </h5>
                  <h5> Total Put Amount: <span class="badge badge-success"> $ <?= $totalPut ?></span> </h5>
              </div>
               <?php
              // --- Function to fetch CALL & PUT totals for the last 15 seconds ---
function fetchRecentTradeTotals($con) {
  $query = mysqli_query($con, "
    SELECT 
      SUM(CASE WHEN trade_options = 'CALL' THEN tradeAmount ELSE 0 END) AS total_call_amount,
      SUM(CASE WHEN trade_options = 'PUT' THEN tradeAmount ELSE 0 END) AS total_put_amount
    FROM meddolic_user_trade_history
    WHERE dateTime >= (NOW() - INTERVAL 15 SECOND)
  ");

  $result = mysqli_fetch_assoc($query);
  return [
    'callTotal' => $result['total_call_amount'] ?? 0,
    'putTotal'  => $result['total_put_amount'] ?? 0
  ];
}

// --- Handle AJAX refresh request ---
if (isset($_GET['refresh']) && $_GET['refresh'] == '1') {
  header('Content-Type: application/json');
  echo json_encode(fetchRecentTradeTotals($con));
  exit;
}

// --- Initial totals on page load ---
$liveTotals = fetchRecentTradeTotals($con);
?>
<h4 class="text-danger mt-3 text-center"> Live Trade Totals (Last 15 Seconds)</h4>

  <div class="amount">
    <h5>CALL Amount: <span id="callTotal" class="badge badge-success">$ <?= number_format($liveTotals['callTotal'], 2) ?></span></h5>
    <h5>PUT Amount: <span id="putTotal" class="badge badge-success">$ <?= number_format($liveTotals['putTotal'], 2) ?></span></h5>
  </div>

  <script>
    // Function to request updated totals
    function updateTradeTotals() {
      $.ajax({
        url: '?refresh=1',
        method: 'GET',
        dataType: 'json',
        success: function (data) {
          $("#callTotal").text($ ${parseFloat(data.callTotal).toFixed(2)});
          $("#putTotal").text($ ${parseFloat(data.putTotal).toFixed(2)});
        }
      });
    }

    // Auto-refresh every 15 seconds
    setInterval(updateTradeTotals, 15000);
  </script>
               
            </div>
          </div>
        </div>

        <!-- ========================== -->
        <!-- Trade Result Setting Section -->
        <!-- ========================== -->
        <div class="card mt-4">
          <div class="header">
            <h2>Trade Result Setting</h2>
          </div>
          <div class="body">
            <?php
            $q = mysqli_query($con, "SELECT * FROM meddolic_config_game_admin_settings LIMIT 1");
            $setting = mysqli_fetch_assoc($q);
            $mode = $setting['result_mode'] ?? 1;
            $manualResult = $setting['manual_result'] ?? 'WIN';
            ?>
            <form id="tradeModeForm">
              <div class="form-group mb-3">
                <label><strong>Select Result Mode:</strong></label><br>

                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" name="result_mode" id="mode1" value="1"
                    <?= ($mode == 1 ? 'checked' : '') ?>>
                  <label class="form-check-label" for="mode1">Random (Auto WIN/LOSS)</label>
                </div>

                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" name="result_mode" id="mode2" value="2"
                    <?= ($mode == 2 ? 'checked' : '') ?>>
                  <label class="form-check-label" for="mode2">Manual (Admin sets result)</label>
                </div>

                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" name="result_mode" id="mode3" value="3"
                    <?= ($mode == 3 ? 'checked' : '') ?>>
                  <label class="form-check-label" for="mode3">Least Bet Wins</label>
                </div>
              </div>

              <div class="form-group mb-3" id="manualResultBox" style="display: <?= ($mode == 2 ? 'block' : 'none') ?>;">
                <label><strong>Manual Result:</strong></label><br>
                <select class="form-control" name="manual_result" style="max-width:200px;">
                  <option value="WIN" <?= ($manualResult == 'WIN' ? 'selected' : '') ?>>WIN</option>
                  <option value="LOSS" <?= ($manualResult == 'LOSS' ? 'selected' : '') ?>>LOSS</option>
                </select>
              </div>

              <button type="submit" class="btn btn-success">Save Settings</button>
            </form>
          </div>
        </div>
        <div class="card mt-4">
          <div class="table-responsive">
          <div class="header">
            <h2>Trade History</h2>
          </div>
          <div class="body">
            <table class="table table-hover js-basic-example dataTable table-custom mb-0">
              <thead>
                <tr>
                  <th>#</th>
                  <th>UserId</th>
                  <th>Requested Amount</th>
                  <th>Trade type</th>
                  <th> Date</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $count = 0;
                $queryConfig = mysqli_query($con, "SELECT a.* ,b.user_id from meddolic_user_trade_history a , meddolic_user_details b where a.memberId=b.member_id order by a.dateTime DESC");
                while ($valConfig = mysqli_fetch_assoc($queryConfig)) {
                  $count++; ?>
                  <tr>
                    <td><?php echo $count; ?></td>
                    <td><?php echo $valConfig['user_id'] ?></td>
                    <td><?php echo $valConfig['tradeAmount'] ?></td>
                    <td><?php echo $valConfig['trade_options'] ?></td>
                    <td><?php echo $valConfig['dateTime'] ?></td>
                    <td>
                      <?php if ($valConfig['result'] == 'PENDING') { ?>
                        <span class="badge badge-danger">Pending</span>
                      <?php } else if ($valConfig['result'] == 'LOSS') { ?>
                          <span class="badge badge-danger">LOSS</span>
                      <?php } else if ($valConfig['result'] == 'WIN') { ?>
                            <span class="badge badge-success">WIN</span>
                          </td>
                        </tr>
                  <?php }
                } ?>
              </tbody>
            </table>
          </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<?php include('include/footer.php'); ?>

<script>
  function updateImageStatus(imageStatus) {
    $.ajax({
      type: "POST",
      url: 'ajaxCalls/updateImageStatusAjax',
      data: { imageStatus: imageStatus },
      cache: false,
      success: function (data) {
        if (data) {
          alert('Updated Successfully');
          location.reload();
        }
      }
    });
  }

  // Sidebar active
  var d = document.getElementById("Setting");
  d.className += " active";
  var d = document.getElementById("betSetting");
  d.className += " active";

  // Toggle manual result select box
  $('input[name="result_mode"]').on('change', function () {
    if ($(this).val() == '2') {
      $('#manualResultBox').show();
    } else {
      $('#manualResultBox').hide();
    }
  });

  // Save trade result mode
  $('#tradeModeForm').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
      url: 'ajaxCalls/updateTradeModeAjax.php',
      type: 'POST',
      data: $(this).serialize(),
      success: function (response) {
        alert(response);
        location.reload();
      },
      error: function () {
        alert('Error updating settings!');
      }
    });
  });
</script>

</body>

</html>