<?php
// ================= TOTAL DEPOSIT & WITHDRAW =================

$where = "id_user='$extplayer'";

// Tambahkan filter tanggal jika ada
$today = date('Y-m-d');

$startDate = isset($_GET['start_date']) && !empty($_GET['start_date'])
    ? $_GET['start_date']
    : $today;

$endDate = isset($_GET['end_date']) && !empty($_GET['end_date'])
    ? $_GET['end_date']
    : $today;

$dateFilter = '';
if ($startDate && $endDate) {
    $dateFilter = "AND tanggal BETWEEN '$startDate 00:00:00' AND '$endDate 23:59:59'";
} elseif ($startDate) {
    $dateFilter = "AND tanggal >= '$startDate 00:00:00'";
} elseif ($endDate) {
    $dateFilter = "AND tanggal <= '$endDate 23:59:59'";
}

$qTotalDeposit = mysqli_query($koneksi,"
  SELECT SUM(total) AS total_deposit
  FROM tb_transaksi
  WHERE id_user='$extplayer'
  AND transaksi='Top Up'
  AND status='Sukses'
  $dateFilter
");

$totalDeposit = mysqli_fetch_assoc($qTotalDeposit)['total_deposit'] ?? 0;

$qTotalWithdraw = mysqli_query($koneksi,"
  SELECT SUM(total) AS total_withdraw
  FROM tb_transaksi
  WHERE id_user='$extplayer'
  AND transaksi='Withdraw'
  AND status='Sukses'
  $dateFilter
");
$totalWithdraw = mysqli_fetch_assoc($qTotalWithdraw)['total_withdraw'] ?? 0;
?>

<main id="main-route">

<!-- HEADER -->
<div class="none-header">
<div class="left" onclick="window.location.href='?page=home'">
    <i class="fas fa-chevron-left"></i> Riwayat Transaksi 
  </div>
  <div class="right">
    <a href="?page=deposit" class="icon-btn-none">
      <i class="fas fa-exchange-alt"></i> Deposit
    </a>      
      <a href="javascript:void(0)" onclick="openLiveChat()" class="button-nav">
        <i class="fas fa-headset m-auto"></i>
      </a>
  </div>
</div>

<div class="main-content transaksi">
<div class="container">

<!-- FILTER -->
<div class="filter-box mb-3">

<div class="select-wrap mb-2">
<select id="trxSelect">
  <option value="deposit" selected>Deposit</option>
  <option value="withdraw">Withdraw</option>
  <option value="bonus">Bonus</option>
  <option value="bethistory">Bet History</option>
</select>
</div>

<div class="row mb-2">
  <div class="col-6 pr-1">
    <div class="date-wrap">
      <i class="fas fa-calendar-alt"></i>
      <input type="text" id="startDate" name="start_date"
        value="<?php echo $startDate; ?>"
        placeholder="Dari Tanggal"
        class="date-ui">
    </div>
  </div>
  <div class="col-6 pl-1">
    <div class="date-wrap">
      <i class="fas fa-calendar"></i>
      <input type="text" id="endDate" name="end_date"
        value="<?php echo $endDate; ?>"
        placeholder="Sampai Tanggal"
        class="date-ui">
    </div>
  </div>
</div>


  <!-- FILTER KHUSUS BET HISTORY -->
  <div id="betFilter" style="display:none">
    <div class="row">
      <div class="col-6 pr-1">
        <select id="gameType">
          <option value="slot">SLOT</option>
          <option value="live">LIVE</option>
          <option value="arcade">ARCADE</option>
        </select>
      </div>
      <div class="col-6 pl-1">
           <select id="provider">
        <option value="">Loading provider...</option>
      </select>
      </div>
    </div>
  </div>
</div>

<!-- TAB CONTENT -->
<div class="tab-content mt-2">

<!-- DEPOSIT -->
<div class="tab-pane fade show active" id="deposit">
  <div class="table-responsive">
    <table class="casino-table">
      <thead>
        <tr>
          <th>Tanggal</th>
          <th>Metode</th>
          <th>Jumlah</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
      <?php
      $qDeposit = mysqli_query($koneksi,"
        SELECT * FROM tb_transaksi
        WHERE $where
        AND transaksi IN ('Top Up','Bonus Refferal')
        $dateFilter
        ORDER BY id DESC
      ");
      while($d=mysqli_fetch_array($qDeposit)){
      ?>
        <tr>
          <td><?= $d['tanggal']; ?></td>
          <td><?= $d['metode']; ?></td>
          <td>Rp <?= number_format($d['total'],0,',','.'); ?></td>
          <td><span class="status <?= strtolower($d['status']); ?>"><?= $d['status']; ?></span></td>
        </tr>
      <?php } ?>
      </tbody>
    </table>
  </div>
</div>

<!-- WITHDRAW -->
<div class="tab-pane fade" id="withdraw">
  <div class="table-responsive">
    <table class="casino-table">
      <thead>
        <tr>
          <th>Tanggal</th>
          <th>Deskripsi</th>
          <th>Jumlah</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
      <?php
      $qWithdraw = mysqli_query($koneksi,"
        SELECT * FROM tb_transaksi
        WHERE id_user='$extplayer'
        AND transaksi='Withdraw'
        $dateFilter
        ORDER BY id DESC LIMIT 10
      ");
      while($w=mysqli_fetch_array($qWithdraw)){
      ?>
        <tr>
          <td><?= $w['tanggal']; ?></td>
          <td>Withdraw</td>
          <td>Rp <?= number_format($w['total'],0,',','.'); ?></td>
          <td><span class="status <?= strtolower($w['status']); ?>"><?= $w['status']; ?></span></td>
        </tr>
      <?php } ?>
      </tbody>
    </table>
  </div>
</div>

<!-- BONUS -->
<div class="tab-pane fade" id="bonus">
  <div class="table-responsive">
    <table class="casino-table">
      <thead>
        <tr>
          <th>Tanggal</th>
          <th>Bonus</th> <!-- ⬅️ judul -->
          <th>Nominal</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
      <?php
            $dateFilterBonus = '';
            $dateFilterScater = '';
            
            if ($startDate && $endDate) {
                $dateFilterBonus  = "AND t.tanggal BETWEEN '$startDate 00:00:00' AND '$endDate 23:59:59'";
                $dateFilterScater = "AND s.created_at BETWEEN '$startDate 00:00:00' AND '$endDate 23:59:59'";
            }
                        $qBonus = mysqli_query($koneksi,"
            (
              SELECT 
                t.id,
                t.tanggal AS tanggal,
                b.judul AS bonus,
                t.nominal AS nominal,
                t.status AS status
              FROM tb_bonus t
              LEFT JOIN tb_promosi b ON b.id = t.id_bonus
              WHERE t.id_user = '$extplayer'
              $dateFilterBonus
            )
            UNION ALL
            (
              SELECT
                s.id,
                s.created_at AS tanggal,
                CONCAT('Scatter ', s.jumlah_scater) AS bonus,
                s.total_bonus AS nominal,
                s.status AS status
              FROM tb_scater s
              WHERE s.id_user = '$extplayer'
              $dateFilterScater
            )
            ORDER BY tanggal DESC
            ");
            
            while($b = mysqli_fetch_assoc($qBonus)){
?>
<tr>
  <td><?= $b['tanggal']; ?></td>
  <td><?= htmlspecialchars($b['bonus']); ?></td>
  <td>Rp <?= number_format($b['nominal'],0,',','.'); ?></td>
  <td>
    <span class="status <?= strtolower($b['status']); ?>">
      <?= ucfirst($b['status']); ?>
    </span>
  </td>
</tr>
<?php } ?>
      </tbody>
    </table>
  </div>
</div>

<!-- BET HISTORY (API) -->
<div class="tab-pane fade" id="bethistory">
  <div class="table-responsive">
    <table class="casino-table">
      <thead>
        <tr>
          <th>Tanggal</th>
          <th>Kode</th>
          <th>Game</th>
          <th>Provider</th>
          <th>Bet</th>
          <th>Win</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody id="betHistoryBody">
        <tr>
          <td colspan="7" align="center">Pilih filter untuk melihat data</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

</div>
</div>
</div>
</main>

<!-- SCRIPT -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<script>
const trxSelect = document.getElementById('trxSelect');
const betFilter = document.getElementById('betFilter');
const startDate = document.getElementById('startDate');
const endDate = document.getElementById('endDate');

// Inisialisasi Flatpickr untuk date picker custom
flatpickr(startDate, {
  dateFormat: "Y-m-d",
  defaultDate: "<?php echo $startDate; ?>",
  onChange: function(selectedDates, dateStr, instance) {
    applyDateFilter();
  }
});

flatpickr(endDate, {
  dateFormat: "Y-m-d",
  defaultDate: "<?php echo $endDate; ?>",
  onChange: function(selectedDates, dateStr, instance) {
    applyDateFilter();
  }
});

trxSelect.addEventListener('change', function () {
  const target = this.value;

  document.querySelectorAll('.tab-pane').forEach(el => {
    el.classList.remove('show','active');
  });

  document.getElementById(target).classList.add('show','active');

  betFilter.style.display = (target === 'bethistory') ? 'block' : 'none';

  if (target === 'bethistory') {
    loadProvider(); 
    loadBetHistory();
  }
});

// Fungsi untuk reload halaman dengan parameter tanggal
function applyDateFilter() {
  const start = startDate.value;
  const end = endDate.value;
  const url = new URL(window.location);
  if (start) url.searchParams.set('start_date', start);
  else url.searchParams.delete('start_date');
  if (end) url.searchParams.set('end_date', end);
  else url.searchParams.delete('end_date');
  window.location.href = url.toString();
}

function loadBetHistory(){
  const tbody = document.getElementById('betHistoryBody');
  if (!tbody) return;

  const gameType = document.getElementById('gameType').value;
  const provider = document.getElementById('provider').value;
  const start = startDate.value;
  const end = endDate.value;

  tbody.innerHTML = `<tr><td colspan="7" align="center">Loading...</td></tr>`;

  let url = `/play/game/bet_history_api.php?game_type=${gameType}&provider=${provider}`;
  if (start) url += `&start_date=${start}`;
  if (end) url += `&end_date=${end}`;

  fetch(url)
    .then(res => res.json())
    .then(res => {
      if (!res.success || !res.data || res.data.length === 0) {
        tbody.innerHTML = `<tr><td colspan="7" align="center">Tidak ada data</td></tr>`;
        return;
      }

      let html = '';
      res.data.forEach(row => {
        html += `
          <tr>
            <td>${row.date}</td>
            <td>${row.trx}</td>
            <td>${row.game}</td>
            <td>${row.provider}</td>
            <td>Rp ${Number(row.bet).toLocaleString()}</td>
            <td>Rp ${Number(row.win).toLocaleString()}</td>
            <td>${row.status}</td>
          </tr>`;
      });
      tbody.innerHTML = html;
    })
    .catch(() => {
      tbody.innerHTML = `<tr><td colspan="7" align="center">Gagal load data</td></tr>`;
    });
}

document.addEventListener('change', function(e){
  if (e.target.id === 'gameType' || e.target.id === 'provider') {
    loadBetHistory();
  }
});
</script>

<script>
function loadProvider() {
  const providerSelect = document.getElementById('provider');
  
  if (!providerSelect) {
    console.warn('Select provider belum ada di DOM');
    return;
  }
  
  console.log('loadProvider() OK');
  
  providerSelect.innerHTML = `<option value="">Loading...</option>`;
  
  fetch('/play/game/provider_api.php')
    .then(res => res.json())
    .then(res => {
      
      console.log('PROVIDER API:', res);
      
      if (!res.success || !Array.isArray(res.providers)) {
        providerSelect.innerHTML = `<option value="">Provider tidak tersedia</option>`;
        return;
      }
      
      let html = `<option value="">Semua Provider</option>`;
      res.providers.forEach(p => {
        html += `<option value="${p.code}">${p.name}</option>`;
      });
      
      providerSelect.innerHTML = html;
    })
    .catch(err => {
      console.error('LOAD PROVIDER ERROR:', err);
      providerSelect.innerHTML = `<option value="">Gagal load provider</option>`;
    });
}
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const params = new URLSearchParams(window.location.search);
  const tab = params.get('tab');

  if (tab) {
    const trxSelect = document.getElementById('trxSelect');
    if (trxSelect) {
      trxSelect.value = tab;
      trxSelect.dispatchEvent(new Event('change'));
    }
  }
});
</script>


<style>
.date-wrap {
  position: relative;
}

.date-wrap i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #f5c16c;
  font-size: 14px;
  pointer-events: none;
}

.date-ui {
  width: 100%;
  padding: 10px 10px 10px 36px;
  background: #111;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  color: #f1f1f1;
  font-size: 13px;
  transition: .2s;
}

.date-ui::placeholder {
  color: #777;
}

.date-ui:focus {
  border-color: #f5c16c;
  box-shadow: 0 0 0 2px rgba(245, 193, 108, .15);
  outline: none;
}

/* FLATPICKR DARK */
.flatpickr-calendar {
  background: #111;
  border: 1px solid #2a2a2a;
  border-radius: 10px;
  color: #fff;
}

.flatpickr-day {
  color: #ccc;
}

.flatpickr-day:hover {
  background: #333;
}

.flatpickr-day.selected,
.flatpickr-day.startRange,
.flatpickr-day.endRange {
  background: #f5c16c;
  color: #000;
}

.flatpickr-months,
.flatpickr-weekdays {
  background: #111;
}
</style>

<link rel="stylesheet" href="luxury-them/custom/css/riwayat.css?v=2.6.0.0">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">