<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once '../db/koneksi.php';
include_once '../api/nexus.php';
include_once '../api/sgx.php';

if (!isset($_SESSION['kode_admin'])) {
  echo '
        <script>
            alert("Terjadi kesalahan, harap masuk kembali!");
            window.location.replace("' . $alamat_admin . 'keluar.php");
        </script>
    ';
}

$deposit = mysqli_query($koneksi, "SELECT SUM(jumlah) AS total_jumlah_deposit FROM tb_deposit where status = 'Sukses'");
$data_deposit = mysqli_fetch_array($deposit);
$total_jumlah_deposit = $data_deposit['total_jumlah_deposit'];
if ($total_jumlah_deposit == 0) {
  $total_jumlah_deposit = 0;
}

//date_default_timezone_set('Asia/Jakarta');

$deposit_hari_ini = mysqli_query($koneksi, "
    SELECT COALESCE(SUM(jumlah), 0) AS total_jumlah_deposit
    FROM tb_deposit
    WHERE status = 'Sukses'
    AND DATE(created_at) = CURDATE()
");

$data_deposit_hari_ini = mysqli_fetch_assoc($deposit_hari_ini);
$total_jumlah_deposit_hari_ini = $data_deposit_hari_ini['total_jumlah_deposit'];

$wd_hari_ini = mysqli_query($koneksi, "
    SELECT COALESCE(SUM(jumlah), 0) AS total_jumlah_wd
    FROM tb_withdraw
    WHERE status = 'Sukses'
    AND DATE(created_at) = CURDATE()
");

$data_wd_hari_ini = mysqli_fetch_assoc($wd_hari_ini);
$total_jumlah_wd_hari_ini = $data_wd_hari_ini['total_jumlah_wd'];

/*echo "Waktu PHP: " . date('Y-m-d H:i:s');
$cek_waktu_mysql = mysqli_query($koneksi, "SELECT NOW() AS waktu_mysql");
$row = mysqli_fetch_assoc($cek_waktu_mysql);
echo "Waktu MySQL: " . $row['waktu_mysql'];*/

// Query untuk mendapatkan data jumlah withdraw
$withdraw = mysqli_query($koneksi, "SELECT SUM(jumlah) AS total_jumlah_withdraw FROM tb_withdraw where status = 'Sukses'");
$data_withdraw = mysqli_fetch_array($withdraw);
$total_jumlah_withdraw = $data_withdraw['total_jumlah_withdraw'];
if ($total_jumlah_withdraw == 0) {
  $total_jumlah_withdraw = 0;
}

$anggota = mysqli_query($koneksi, "SELECT * FROM tb_user");
$jumlah_anggota = mysqli_num_rows($anggota);

$anggotaharini = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE DATE(created_at) = CURDATE()");
$jumlah_anggota_harini = mysqli_num_rows($anggotaharini);

$promosi = mysqli_query($koneksi, "SELECT * FROM promosi");
$jumlah_promosi = mysqli_num_rows($promosi);

$staff = mysqli_query($koneksi, "SELECT * FROM staff");
$jumlah_staff = mysqli_num_rows($staff);

$_SESSION['lastDepositCount'] = $total_jumlah_deposit;
$_SESSION['lastWithdrawCount'] = $total_jumlah_withdraw;
$_SESSION['lastAnggotaCount'] = $jumlah_anggota;
$_SESSION['lastPromosiCount'] = $jumlah_promosi;
$_SESSION['lastStaffCount'] = $jumlah_staff;

$balanceAgent = $nx->info_agent();
$balanceAgentsgx = $SGX->info_agent();

if (is_string($balanceAgent)) {
  $balanceAgent = json_decode($balanceAgent, true);
  $balanceAgentsgx = json_decode($balanceAgentsgx, true);
}

if ($balanceAgent && isset($balanceAgent['status']) && $balanceAgent['status'] == 1) {
  $balance = isset($balanceAgent['agent']['balance']) ? $balanceAgent['agent']['balance'] : 0;  // Cek jika 'agent_balance' ada
  $balance2 = isset($balanceAgentsgx['data']['balance']) ? $balanceAgentsgx['data']['balance'] : 0;  // Cek jika 'agent_balance' ada

  $currency = isset($balanceAgent['currency']) ? $balanceAgent['currency'] : 'IDR';  // Default 'IDR' jika 'currency' tidak ada

  $currency_symbol = ($currency === 'IDR') ? 'Rp. ' : '';  // Jika currency = 'IDR', simbolnya 'Rp.'

  $formatted_balance = number_format($balance, 0, ',', '.');
  $formatted_balance2 = number_format($balance2, 0, ',', '.');

  //echo $currency_symbol . $formatted_balance;  // Misalnya: Rp. 6.273.975
} else {
  // Menangani error jika data tidak valid
  echo 'Error fetching balance or invalid status.';
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <audio id="notificationSound" preload="auto"></audio>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function () {
      setInterval(checkDataChanges, 5000);
      setInterval(checkNewData, 5000);

      var notificationSound = new Audio('assets/sounds/notification_sound.mp3');

      function checkDataChanges() {
        $.ajax({
          url: 'check_data_changes.php?action=check_data_changes',
          method: 'GET',
          dataType: 'json',
          success: function (response) {
            if (response.dataChanges) {
              playNotificationSound();
              showNotification("Ada perubahan pada data!", "info");
              setTimeout(function () {
                location.reload();
              }, 3000);
            }
          },
          error: function (xhr, status, error) {
            console.error('AJAX Error: ' + status, error);
          }
        });
      }

      function checkNewData() {
        $.ajax({
          url: 'check_new_data.php?action=check_new_data', // File PHP untuk memeriksa data baru
          method: 'GET',
          dataType: 'json',
          success: function (response) {
            if (response.newData) {
              // Jika ada data baru, mainkan suara notifikasi
              playNotificationSound();
              // Perbarui tabel atau elemen lainnya di dasbor
              updateDashboard(response.data);
              // Tampilkan popup notifikasi
              showNotification("Data baru diterima!", "success");
              // Auto reload halaman setelah 3 detik
              setTimeout(function () {
                location.reload();
              }, 3000);
            }
          },
          error: function (xhr, status, error) {
            console.error('AJAX Error: ' + status, error);
          }
        });
      }

      function playNotificationSound() {
        // Mainkan suara notifikasi
        // notificationSound.play();
      }

      function updateDashboard(data) {
        // Fungsi untuk memperbarui dasbor dengan data baru
        // Anda bisa memperbarui tabel atau elemen lainnya di sini
        console.log("Data baru diterima:", data);
        // Misalnya, perbarui tabel deposit dengan data baru
      }

      function showNotification(message, type) {
        var notification = document.createElement('div');
        notification.className = 'notification ' + type;
        notification.textContent = message;
        document.body.appendChild(notification);
        setTimeout(function () {
          notification.style.opacity = '0';
          setTimeout(function () {
            document.body.removeChild(notification);
          }, 400);
        }, 2000);
      }
    });
  </script>

  <div class="container-xxl flex-grow-1 container-p-y">
    <div class="row gy-4 mb-4">
      <div class="col-md-6">
        <div class="fw-bold fs-4 text-center text-md-start">Dashboard</div>
      </div>
      <div class="col-md-6">
        <div class="text-center text-md-end">
          <span><?php echo ucapan() . ', ' . tanggalIndonesia(date('Y-m-d'), true) . ', '; ?></span>
          <span id="jam_sekarang">Jam </span>
        </div>
      </div>
       <?php
      $nx = json_decode($nx->info_agent(), true);
      $sgx = json_decode($SGX->info_agent(), true);
      if ((int)$nx['status'] !== 1 || (int)$sgx['status'] !== 200): ?>
        <div class="col-md-12">
          <div class="card h-100 border border-warning">
            <div class="card-body d-flex align-items-center gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-warning rounded">
                  <i class="mdi mdi-alert-circle mdi-24px"></i>
                </div>
              </div>
              <div>
                <h6 class="mb-1 text-warning">Peringatan</h6>
                <small class="text-muted">
                  Harap koneksikan kedua API terlebih dahulu
                </small>
                <small class="text-muted">
                  - UVGAMING
                </small>
              </div>
            </div>
          </div>
        </div>
      <?php else: ?>
      <div class="col-md-2">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-account-multiple mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo formatAngkaSingkat($jumlah_anggota_harini); ?></h4>
                <small class="text-muted">Anggota Hari ini</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-plus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0">Rp.<?php echo $formatted_balance; ?></h4>
                <small class="text-muted">Agent Balance (NXS)</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-plus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0">Rp.<?php echo $formatted_balance2; ?></h4>
                <small class="text-muted">Agent Balance (SGX)</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-plus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo 'Rp.' . formatAngkaSingkat($total_jumlah_deposit_hari_ini); ?></h4>
                <small class="text-muted">Total Deposit Hari ini</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-plus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo 'Rp.' . formatAngkaSingkat($total_jumlah_wd_hari_ini); ?></h4>
                <small class="text-muted">Total withdraw hari ini</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-plus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo 'Rp.' . formatAngkaSingkat($total_jumlah_deposit); ?></h4>
                <small class="text-muted">Total Deposit keseluruhan</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-cash-minus mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo 'Rp.' . formatAngkaSingkat($total_jumlah_withdraw); ?></h4>
                <small class="text-muted">Total Withdraw keselurhan</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-2">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-account-multiple mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo formatAngkaSingkat($jumlah_anggota); ?></h4>
                <small class="text-muted">Anggota</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-2">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-image mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo formatAngkaSingkat($jumlah_promosi); ?></h4>
                <small class="text-muted">Promosi</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-2">
        <div class="card h-100">
          <div class="card-body d-flex justify-content-between flex-wrap gap-3">
            <div class="d-flex gap-3">
              <div class="avatar">
                <div class="avatar-initial bg-label-primary rounded">
                  <i class="mdi mdi-account-group mdi-24px"></i>
                </div>
              </div>
              <div class="card-info">
                <h4 class="mb-0"><?php echo formatAngkaSingkat($jumlah_staff); ?></h4>
                <small class="text-muted">Staff</small>
              </div>
            </div>
          </div>
        </div>
      </div>
      <?php
      // Query untuk total jumlah deposit yang diproses
      $deposit = mysqli_query($koneksi, "SELECT SUM(jumlah) AS total_jumlah_deposit FROM tb_deposit WHERE status = 'Pending'");
      $data_deposit = mysqli_fetch_array($deposit);
      $total_jumlah_deposit = $data_deposit['total_jumlah_deposit'];
      if ($total_jumlah_deposit === null) {
        $total_jumlah_deposit = 0;
      }

      // Query untuk menampilkan detail deposit yang diproses
      $query_deposit_diproses = mysqli_query($koneksi, "SELECT * FROM tb_deposit WHERE status = 'Pending' ORDER BY created_at DESC");
      ?>

      <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row gy-4 mb-4">
          <div class="col-md-6">
            <div class="fw-bold fs-4 text-center text-md-start">Queued Deposit</div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover table-sm">
                <thead>
                  <tr>
                    <th scope="col" class="text-center">No.</th>
                    <th scope="col" class="text-center">Kode</th>
                    <th scope="col" class="text-center">UserName</th>
                    <th scope="col" class="text-center">Asal</th>
                    <th scope="col" class="text-center">Tujuan</th>
                    <th scope="col" class="text-center">Bonus</th>
                    <th scope="col" class="text-center">Jumlah</th>
                    <th scope="col" class="text-center">Tanggal</th>
                    <th scope="col" class="text-center">Status</th>
                    <th scope="col" class="text-center">Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $nomor_deposit = 1;
                  while ($data_deposit = mysqli_fetch_assoc($query_deposit_diproses)) {
                    $id_deposit = $data_deposit['id'];
                    $id_anggota_deposit = $data_deposit['extplayer'];
                    $kode_deposit = $data_deposit['ref'];
                    $asal_deposit = $data_deposit['bank_asal'];
                    $tujuan_deposit = $data_deposit['bank_tujuan'];
                    $bonus_deposit = 0;
                    $jumlah_deposit = $data_deposit['jumlah'];
                    $tanggal_deposit = $data_deposit['created_at'];
                    $status_deposit = $data_deposit['status'];

                    // Ambil nama pengguna anggota deposit
                    $anggota_deposit = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE extplayer = '$id_anggota_deposit'");
                    if (mysqli_num_rows($anggota_deposit) == 0) {
                      $nama_pengguna_anggota_deposit = "Data anggota tidak ada atau telah dihapus";
                    } else {
                      $data_anggota_deposit = mysqli_fetch_assoc($anggota_deposit);
                      $nama_pengguna_anggota_deposit = $data_anggota_deposit['username'];
                    }

                    // Tentukan kelas status untuk warna latar belakang
                    switch ($status_deposit) {
                      case 'Pending':
                        $status_class = 'text-warning';
                        break;
                      case 'Rejected':
                        $status_class = 'text-danger';
                        break;
                      case 'Sukses':
                        $status_class = 'text-success';
                        break;
                      default:
                        $status_class = '';
                        break;
                    }
                    ?>
                    <tr>
                      <td class="text-center"><?php echo $nomor_deposit++; ?></td>
                      <td class="text-center"><?php echo $kode_deposit; ?></td>
                      <td class="text-center"><?php echo $nama_pengguna_anggota_deposit; ?></td>
                      <td class="text-center"><?php echo $asal_deposit; ?></td>
                      <td class="text-center"><?php echo $tujuan_deposit; ?></td>
                      <td class="text-center"><?php echo $bonus_deposit; ?></td>
                      <td class="text-center"><?php echo 'Rp.' . number_format($jumlah_deposit, 0, ',', '.'); ?></td>
                      <td class="text-center"><?php echo jamTanggalIndonesia($tanggal_deposit); ?></td>
                      <td class="text-center <?php echo $status_class; ?>"><?php echo ucfirst($status_deposit); ?></td>
                      <td class="text-center">
                        <div class="btn-group">
                          <a href="<?php echo $alamat_admin . 'deposit'; ?>"
                            class="btn btn-sm btn-primary waves-effect waves-light" aria-label="Ubah">
                            <span class="tf-icons mdi mdi-cog me-1"></span>
                          </a>
                        </div>
                      </td>
                    </tr>
                    <?php
                  }
                  ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <div class="row gy-4 mb-4">
          <div class="col-md-6">
            <div class="fw-bold fs-4 text-center text-md-start">Queued Withdraw</div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover table-sm">
                <thead>
                  <tr>
                    <th scope="col" class="text-center" style="width: 5%;">No.</th>
                    <th scope="col" class="text-center" style="width: 10%;">Kode</th>
                    <th scope="col" class="text-center" style="width: 20%;">Username</th>
                    <th scope="col" class="text-center" style="width: 20%;">Tujuan</th>
                    <th scope="col" class="text-center" style="width: 15%;">Jumlah</th>
                    <th scope="col" class="text-center" style="width: 15%;">Tanggal</th>
                    <th scope="col" class="text-center" style="width: 10%;">Status</th>
                    <th scope="col" class="text-center" style="width: 5%;">Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $nomor_withdraw = 1;
                  // Query untuk mendapatkan data queued withdraw
                  $query_withdraw_diproses = mysqli_query($koneksi, "SELECT * FROM tb_withdraw WHERE status = 'Pending' ORDER BY created_at DESC");

                  if (!$query_withdraw_diproses) {
                    die("Query failed: " . mysqli_error($koneksi));
                  }

                  // Cek apakah query mengembalikan hasil atau tidak
                  if (mysqli_num_rows($query_withdraw_diproses) > 0) {
                    // Tampilkan data withdraw
                    while ($data_withdraw = mysqli_fetch_assoc($query_withdraw_diproses)) {
                      $id_withdraw = $data_withdraw['id'];
                      $id_anggota_withdraw = $data_withdraw['extplayer'];
                      $kode_withdraw = $data_withdraw['ref'];
                      $tujuan_withdraw = $data_withdraw['bank_asal'];
                      $jumlah_withdraw = $data_withdraw['jumlah'];
                      $tanggal_withdraw = $data_withdraw['created_at'];
                      $status_withdraw = $data_withdraw['status'];

                      // Ambil nama pengguna anggota withdraw
                      $anggota_withdraw = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE extplayer = '$id_anggota_withdraw'");
                      if (!$anggota_withdraw) {
                        die("Query failed: " . mysqli_error($koneksi));
                      }

                      if (mysqli_num_rows($anggota_withdraw) == 0) {
                        $nama_pengguna_anggota_withdraw = "Data anggota tidak ada atau telah dihapus";
                      } else {
                        $data_anggota_withdraw = mysqli_fetch_assoc($anggota_withdraw);
                        $nama_pengguna_anggota_withdraw = $data_anggota_withdraw['username'];
                      }

                      // Tentukan kelas status untuk warna latar belakang
                      switch ($status_withdraw) {
                        case 'Pending':
                          $status_class = 'text-warning';

                          break;
                        case 'Rejected':
                          $status_class = 'text-danger';

                          break;
                        case 'Sukses':
                          $status_class = 'text-success';

                          break;
                        default:
                          $status_class = '';
                          break;
                      }
                      ?>
                      <tr>
                        <td class="text-center"><?php echo $nomor_withdraw++; ?></td>
                        <td class="text-center"><?php echo $kode_withdraw; ?></td>
                        <td class="text-center"><?php echo $nama_pengguna_anggota_withdraw; ?></td>
                        <td class="text-center"><?php echo $tujuan_withdraw; ?></td>
                        <td class="text-center"><?php echo 'Rp.' . number_format($jumlah_withdraw, 0, ',', '.'); ?></td>
                        <td class="text-center"><?php echo jamTanggalIndonesia($tanggal_withdraw); ?></td>
                        <td class="text-center <?php echo $status_class; ?>"><?php echo ucfirst($status_withdraw); ?></td>
                        <td class="text-center">
                          <div class="btn-group">
                            <a href="<?php echo $alamat_admin . 'withdraw'; ?>"
                              class="btn btn-sm btn-primary waves-effect waves-light" aria-label="Ubah">
                              <span class="tf-icons mdi mdi-cog me-1"></span>
                            </a>
                          </div>
                        </td>
                      </tr>
                      <?php
                    } // tutup while
                  } else {
                  }
                  ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
  </div>
</body>

</html>