<!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>









<?php
// Disable caching so every refresh gets new data
// header("Cache-Control: no-cache, must-revalidate");
// header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

// Database query (adjust $con to your connection)
//require_once("connect.php"); // your connection file
?>

<div class="row clearfix">
  <div class="col-lg-12 col-md-12 col-sm-12">
    <div class="card">
      <div class="body">
        <div class="table-responsive">

<?php
// ✅ TOTAL (All-time)
$queryTotal = mysqli_query($con, "
  SELECT 
    SUM(CASE WHEN trade_options='CALL' THEN tradeAmount ELSE 0 END) AS totalCall,
    SUM(CASE WHEN trade_options='PUT'  THEN tradeAmount ELSE 0 END) AS totalPut
  FROM meddolic_user_trade_history
");
$totalRow = mysqli_fetch_assoc($queryTotal);
$totalCall = $totalRow['totalCall'] ?? 0;
$totalPut  = $totalRow['totalPut'] ?? 0;

// ✅ Last 15 seconds data
// $query15s = mysqli_query($con, "
//   SELECT 
//     SUM(CASE WHEN trade_options='CALL' THEN tradeAmount ELSE 0 END) AS call15s,
//     SUM(CASE WHEN trade_options='PUT'  THEN tradeAmount ELSE 0 END) AS put15s
//   FROM meddolic_user_trade_history
//   WHERE dateTime BETWEEN (NOW() - INTERVAL 15 SECOND) AND NOW()
// ");
// $row15s = mysqli_fetch_assoc($query15s);

// $call15s = (float)($row15s['call15s'] ?? 0);
// $put15s  = (float)($row15s['put15s']  ?? 0);


// Set correct timezone (change as per your region)
mysqli_query($con, "SET time_zone = '+05:30'"); // Example: India timezone

// Query (safe & reliable version)
$query15s = mysqli_query($con, "
    SELECT 
        SUM(CASE WHEN UPPER(trade_options) = 'CALL' THEN tradeAmount ELSE 0 END) AS call15s,
        SUM(CASE WHEN UPPER(trade_options) = 'PUT'  THEN tradeAmount ELSE 0 END) AS put15s
    FROM meddolic_user_trade_history
    WHERE dateTime BETWEEN (NOW() - INTERVAL 15 SECOND) AND NOW()
") or die('SQL Error: ' . mysqli_error($con));

// Fetch result
$row15s = mysqli_fetch_assoc($query15s);

// Convert to float and handle null values
$call15s = (float)($row15s['call15s'] ?? 0);
$put15s  = (float)($row15s['put15s']  ?? 0);



// ✅ If no data in 15s → show 0
if ($call15s <= 0) $call15s = 0;
if ($put15s <= 0)  $put15s = 0;
?>
 
<!-- ✅ Total Summary -->
<div class="amount">
  <!-- <h4 class="text-primary">Total Trade Summary</h4> -->
  <h5>Total CALL Amount: <span class="badge badge-success">$ <?= number_format($totalCall, 2) ?></span></h5>
  <h5>Total PUT Amount:  <span class="badge badge-success">$ <?= number_format($totalPut, 2) ?></span></h5>
</div>
 <h4 class="text-danger mb-3 text-center">Trade Totals (Last <span id="timer" class="text-danger">15</span> Seconds)</h4>
<!-- ✅ 15 Second Live Summary -->
<div class="amount">
 
  <h5>CALL Amount: <span class="badge badge-success">$ <?= number_format($call15s, 2) ?></span></h5>
  <h5>PUT Amount:  <span class="badge badge-success">$ <?= number_format($put15s, 2) ?></span></h5>
</div>

<!-- ✅ Timer Display -->
<!-- <h5 class="text-center mt-3">
  Page auto-refreshing in <span id="timer" class="text-danger">15</span> seconds...
</h5> -->

<script>
// ✅ Simple 15-second countdown + auto refresh
let countdown = 15;
const timerEl = document.getElementById("timer");

const interval = setInterval(() => {
  countdown--;
  timerEl.textContent = countdown;

  if (countdown <= 0) {
    clearInterval(interval);
    location.reload(); // refresh the page every 15s
  }
}, 1000);
</script>

        </div>
      </div>
    </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>