<?php
// BACA SETTING DARI DATABASE (HANYA QRIS AUTO)
 $web_pay = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM tb_web LIMIT 1"));
 $config_qris = $web_pay['status_qris_auto']; 

 $query2 = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE id = '$id_login'");
 $punya_user = mysqli_fetch_array($query2);

if ($punya_user['status'] == "Suspend") {
    session_destroy();
    header("Location:index.php?pesan=29");
    exit();
}

 $web_setting = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT min_depo FROM tb_web LIMIT 1"));
 $min_depo_db = (int)$web_setting['min_depo']; 
 $min_depo_text = "IDR " . number_format($min_depo_db, 0, ',', '.'); 

 $cekTrxGlobal = mysqli_query($koneksi, "SELECT id FROM tb_transaksi WHERE id_user='$extplayer' AND transaksi='Top Up' AND status='Sukses' LIMIT 1");
 $sudahTrxGlobal = mysqli_num_rows($cekTrxGlobal) > 0;

if ($sudahTrxGlobal) { 
    $qBonusGlobal = mysqli_query($koneksi, "SELECT * FROM tb_promosi WHERE status='active' AND type_bonus != 'new_member'"); 
} else { 
    $qBonusGlobal = mysqli_query($koneksi, "SELECT * FROM tb_promosi WHERE status='active'"); 
}

// Simpan bonus ke array biar nggak hilang
 $listBonus = [];
while ($dBonus = mysqli_fetch_assoc($qBonusGlobal)) {
    $listBonus[] = $dBonus;
}
?>

<main id="main-route">
  <div class="none-header">
    <div class="left" onclick="window.location.href='?page=home'"><i class="fas fa-chevron-left"></i> Deposit</div>
    <div class="right">
      <a href="?page=riwayat&start_date=2025-01-01" class="icon-btn-none"><i class="fas fa-history"></i> Riwayat</a>
      <a href="?page=withdraw" class="icon-btn-none"><i class="fas fa-exchange-alt"></i> Withdraw</a>
    </div>
  </div>

  <div class="main-content transaksi">
    <div class="container">
      <ul class="component-tabs nav nav-tabs" id="transactionTabs">
        <li class="nav-item">
          <a class="button-pills nav-link active" id="nav-qris-tab" data-toggle="tab" href="#nav-qris" role="tab" style="pointer-events: auto; position: relative; z-index: 5;">
            <i class="fas fa-bolt"></i><span>Auto Depo</span>
          </a>
        </li>
      </ul>

      <div class="tab-content">
        <div class="tab-pane fade show active" id="nav-qris" role="tabpanel">
          <?php if($config_qris == 'off') { ?>
            <div style="text-align:center; padding:50px 20px; color:#ff4d4f;">
              <i class="fas fa-tools" style="font-size:40px; margin-bottom:15px;"></i>
              <h4 style="color:#fff;">Sedang Maintenance</h4>
              <p>Auto Deposit sedang tidak tersedia saat ini.</p>
            </div>
          <?php } else { ?>
          <div class="transaksi-grid">
            <div class="transaksi-form">
              <div class="transaksi-formulir flip-card premium-form">
                <div class="flip-front">
                  <div class="formulir-title premium-title"><i class="fas fa-bolt"></i><span>Kasir Otomatis</span></div>
                  <div class="formulir-form">
                    
                    <div class="note-info" style="background: linear-gradient(135deg, #4b0082, #240046); border-left: 4px solid #e0aaff; border-radius: 8px; padding: 12px; margin-bottom: 20px;">
                      <span style="color:#e0aaff; font-size:13px;"><i class="fas fa-shield-alt"></i> Transaksi 100% Otomatis. Saldo masuk langsung tanpa menunggu admin.</span>
                    </div>

                    <div style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; padding: 15px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
                      <div>
                        <div style="font-size: 11px; color: #aaa; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Username / User ID</div>
                        <div style="font-size: 18px; font-weight: bold; color: #fff; letter-spacing: 1px;"><?= htmlspecialchars($punya_user['username']) ?></div>
                      </div>
                      <div style="background: #28a745; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-user-check" style="color: #fff;"></i>
                      </div>
                    </div>

                    <div class="form-group modern-field">
                      <label class="modern-label">Pilih Bonus</label>
                      <div class="modern-select-wrapper">
                        <select name="bonus" id="bonusSelectAuto" class="modern-select">
                          <option value="tanpabonus" selected>🎁 Tanpa Bonus</option>
                          <?php foreach ($listBonus as $dBonusAuto) { echo '<option value="'.$dBonusAuto['id'].'">🎉 '.$dBonusAuto['judul'].'</option>'; } ?>
                        </select>
                      </div>
                    </div>

                    <div class="form-group modern-field deposit-amount-box">
                      <label class="deposit-amount-label">Jumlah Deposit</label>
                      <input type="number" name="nominal" id="qrisNominalInput" class="deposit-amount-input" placeholder="Masukkan nominal" min="<?= $min_depo_db ?>" required>
                      <small class="deposit-amount-hint">Minimal deposit <?= $min_depo_text ?></small>
                    </div>
                    
                    <div class="qris-fastpick" style="margin-bottom: 20px;">
                      <div class="qris-fastpick__title"><i class="fas fa-bolt"></i> Pilih Cepat</div>
                      <div class="qris-fastpick__grid">
                        <button type="button" class="qris-fastpick__item" data-amount="10000"><strong>10K</strong><span>IDR 10.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="20000"><strong>20K</strong><span>IDR 20.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="25000"><strong>25K</strong><span>IDR 25.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="50000"><strong>50K</strong><span>IDR 50.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="100000"><strong>100K</strong><span>IDR 100.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="200000"><strong>200K</strong><span>IDR 200.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="500000"><strong>500K</strong><span>IDR 500.000</span></button>
                        <button type="button" class="qris-fastpick__item" data-amount="1000000"><strong>1JT</strong><span>IDR 1.000.000</span></button>
                      </div>
                    </div>

                    <div id="actionButtons">
                      <button type="button" id="btnQris" class="btn-custom-2 full_width" onclick="processAutoCashier()" style="display: flex; align-items: center; justify-content: center; gap: 10px; pointer-events: auto !important; position: relative; z-index: 10; cursor: pointer !important;">
                        <i class="fas fa-qrcode"></i> Generate QRIS
                      </button>
                    </div>

                    <div id="qrisResult" class="text-center mt-4" style="display:none;">
                      <div style="background:#fff; padding:15px; border-radius:15px; display:inline-block; margin-bottom:15px; box-shadow: 0 4px 20px rgba(0,0,0,0.2);">
                        <div id="qrisImage" style="width:190px; height:190px; display:flex; align-items:center; justify-content:center;"></div>
                      </div>
                      <p class="mt-2" id="qrisNominalText" style="font-weight:bold; font-size:20px;"></p>
                      
                      <div id="qrisTimerBox" style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-top:15px;">
                        <div style="font-size: 12px; color: #aaa; margin-bottom: 8px;"><i class="fas fa-clock"></i> Batas Waktu Pembayaran</div>
                        <div id="qrisTimerText" style="font-size: 28px; font-weight: bold; color: #fff; font-family: monospace; letter-spacing: 2px;">20:00</div>
                      </div>
                    </div>

                  </div>
                </div>
              </div>
            </div>
          </div>
          <?php } ?>
        </div>
      </div>
    </div>
  </div>
</main>

<link rel="stylesheet" id="templateStyle" type="text/css" href="luxury-them/custom/css/deposit.css?v=3.8.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
const CONFIG = {
    min_depo: <?= (int)$min_depo_db ?>,
    min_text: "<?= $min_depo_text ?>",
    status_auto: "<?= $config_qris ?>"
};

let autoDepoTimer;
let currentReffId = null;
let checkStatusInterval = null;

function showPremiumLoader(channel) {
    if($('#premiumLoader').length) return;
    $('body').append(`
        <div id="premiumLoader" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.95);z-index:99999;display:flex;align-items:center;justify-content:center;color:#fff;text-align:center;">
            <div>
                <div style="width:80px;height:80px;border:5px solid rgba(255,255,255,0.2);border-top:5px solid #fff;border-radius:50%;margin:0 auto 25px;animation: spin 1s linear infinite;"></div>
                <h4 style="margin:0 0 10px; font-weight: 600;">Menghubungkan ke ${channel}</h4>
                <p style="color:#aaa;margin:0;font-size:14px;">Mohon tunggu sebentar...</p>
            </div>
        </div>
        <style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
    `);
}

function hidePremiumLoader() {
    $('#premiumLoader').fadeOut(200, function() { $(this).remove(); });
}

function startAutoDepoTimer(duration) {
    let timer = duration;
    let minutes, seconds;
    const display = $('#qrisTimerText');
    display.css('color', '#fff');

    if (autoDepoTimer) clearInterval(autoDepoTimer);

    autoDepoTimer = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (timer <= 120) {
            display.css('color', '#ff4d4f'); 
        } else if (timer <= 300) {
            display.css('color', '#faad14'); 
        }

        if (--timer < 0) {
            clearInterval(autoDepoTimer);
            clearInterval(checkStatusInterval);
            alert('Waktu pembayaran QRIS telah habis. Silahkan buat transaksi baru.');
            $('#qrisResult').slideUp(200);
            $('#actionButtons').slideDown(200);
            $('#btnQris').prop('disabled', false).css('opacity', '1');
            $('#qrisNominalInput').val('');
            $('.qris-fastpick__item').removeClass('active');
        }
    }, 1000);
}

function startPollingStatus(reffId) {
    currentReffId = reffId;
    if (checkStatusInterval) clearInterval(checkStatusInterval);
    
    checkStatusInterval = setInterval(function() {
        if (!currentReffId) return;
        $.ajax({
            url: 'function/cek_status_depo.php',
            type: 'GET',
            data: { reff_id: currentReffId },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'Sukses') {
                    clearInterval(checkStatusInterval);
                    clearInterval(autoDepoTimer);
                    $('#qrisTimerBox').html(`
                        <div style="text-align:center;">
                            <div style="font-size:40px; color:#28a745; margin-bottom:10px;"><i class="fas fa-check-circle"></i></div>
                            <div style="font-size:20px; font-weight:bold; color:#28a745;">PEMBAYARAN BERHASIL!</div>
                            <p style="color:#aaa; font-size:13px; margin-top:5px;">Saldo telah otomatis masuk ke akun Anda.</p>
                        </div>
                    `);
                    setTimeout(() => { window.location.href = '?page=profile'; }, 3000);
                }
            }
        });
    }, 5000);
}

function processAutoCashier() {
    if (CONFIG.status_auto === 'off') {
        alert('Maaf, fitur pembayaran otomatis sedang dinonaktifkan.');
        return;
    }

    const nominalInput = $('#qrisNominalInput').val();
    const nominal = Number(nominalInput);

    if (!nominalInput || nominal < CONFIG.min_depo) {
        alert('Masukkan nominal! Minimal ' + CONFIG.min_text);
        return;
    }

    const originalHtml = $('#btnQris').html();

    $('#btnQris').prop('disabled', true).css('opacity', '0.7').html('<i class="fas fa-circle-notch fa-spin"></i> Loading...');
    showPremiumLoader('QRIS');

    $.ajax({
        url: '/function/proses_api.php',
        type: 'POST',
        data: { 
            nominal: nominal, 
            channel: 'QRIS',
            bonus: $('#bonusSelectAuto').val() 
        },
        dataType: 'json',
        timeout: 15000,
        success: function(res) {
            hidePremiumLoader();
            if (res.status) {
                if (res.action === 'redirect') {
                    window.location.replace(res.redirect_url);
                } else if (res.action === 'qris') {
                    $('#qrisImage').html(`<img src="${res.qris_image}" style="width:190px;height:190px;border-radius:10px;" alt="QRIS">`);
                    $('#qrisNominalText').html(`Total Bayar: <span style="color:#28a745;">IDR ${parseInt(res.total).toLocaleString('id-ID')}</span>`);
                    $('#qrisResult').slideDown(300);
                    $('#actionButtons').slideUp(200);
                    startAutoDepoTimer(20 * 60); 
                    startPollingStatus(res.reff_id);
                }
            } else {
                alert('Error: ' + (res.message || 'Gagal memproses transaksi.'));
                $('#btnQris').prop('disabled', false).css('opacity', '1').html(originalHtml);
            }
        },
        error: function(xhr, status) {
            hidePremiumLoader();
            let msg = 'Koneksi gagal.';
            if (status === "timeout") msg = 'Server timeout. Coba lagi.';
            if (xhr.status === 404) msg = 'File API tidak ditemukan (proses_api.php)!';
            alert(msg);
            $('#btnQris').prop('disabled', false).css('opacity', '1').html(originalHtml);
        }
    });
}

$(document).ready(function() {
    $('.qris-fastpick__item').on('click', function() {
        const val = $(this).data('amount');
        $(this).addClass('active').siblings().removeClass('active');
        $('#qrisNominalInput').val(val).trigger('change');
    });
});
</script>
