<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../../config/koneksi.php');

$sid = session_id();
$sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);

// ================= BASE URL =================
if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../../config/url_helper.php');
}
$urlweb = get_active_base_url();

// Cek apakah user sudah login
if (!isset($_SESSION['user'])) {
    header('Location: ' . $urlweb . '/m/?notif=6');
    exit();
}

$user = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE username = '" . $_SESSION['user'] . "'") or die(mysqli_error());
$u = mysqli_fetch_array($user);
$id_user = $u['cuid'];

// Ambil minimum deposit
$minDeposit = isset($s0['mindepo']) ? (int)str_replace(',', '', $s0['mindepo']) : 10000;

include "../header.php";
?>

<div class="container-wrapper acc" style="background-color: black">
    <div class="container container-box noSidePadding">
        <div class="content">
                <div class="box-wrapper plr-15">
                    <form id="qrisDepositForm" method="POST" action="<?php echo $urlweb; ?>/function/generate_qris_otomatis.php">
                        <div class="box-wrapper plr-15">
                            <h4 class="text-center" style="color: gold; margin-top: 20px;">Form Deposit QRIS Otomatis</h4>
                            <hr style="border-color: #333;">
                            
                            <div class="row d-flex mt-3">
                                <div class="col-md-3 col-xs-4">
                                    <div class="font-weight-bold">Username</div>
                                </div>
                                <div class="col-md-9 col-xs-8">
                                    <input type="text" name="username" class="form-control" value="<?php echo htmlspecialchars($u['username']); ?>" readonly required>
                                </div>
                            </div>

                            <div class="row d-flex mt-3">
                                <div class="col-md-3 col-xs-4">
                                    <div class="font-weight-bold">Pilih Bonus</div>
                                </div>
                                <div class="col-md-9 col-xs-8">
                                    <select class="form-control" name="gameid" id="gameid">
                                        <option value="">Tanpa Bonus</option>
                                        <?php
                                        $sql_p = mysqli_query($conn, "SELECT * FROM `tb_post` WHERE kategori = 0");
                                        while ($st = mysqli_fetch_array($sql_p)) {
                                            echo '<option value="' . $st['cuid'] . '">' . htmlspecialchars($st['title']) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <div class="row d-flex mt-3">
                                <div class="col-md-3 col-xs-4">
                                    <div class="font-weight-bold">Nominal (IDR) <span class="text-danger">*</span></div>
                                </div>
                                <div class="col-md-9 col-xs-8">
                                    <input type="number" name="amount" id="amount" class="form-control" 
                                           placeholder="Min: <?php echo number_format($minDeposit, 0, ',', '.'); ?>" 
                                           min="<?php echo $minDeposit; ?>" max="10000000" required>
                                    <small class="text-muted">Minimum: Rp <?php echo number_format($minDeposit, 0, ',', '.'); ?>, Maksimum: Rp 10.000.000</small>
                                </div>
                            </div>

                            <div class="row d-flex mt-4">
                                <div class="col-md-12">
                                    <button type="submit" name="submit" class="btn btn-block" style="background: #f39c12; color: white; font-weight: bold;" id="btnSubmit">
                                        GENERATE QRIS
                                    </button>
                                </div>
                            </div>
                            
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <div id="errorMessage" style="display: none;" class="alert alert-danger"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
        </div>
    </div>
</div>

<script>
document.getElementById('qrisDepositForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const form = this;
    const btnSubmit = document.getElementById('btnSubmit');
    const errorMessage = document.getElementById('errorMessage');
    
    btnSubmit.disabled = true;
    btnSubmit.textContent = 'Memproses...';
    errorMessage.style.display = 'none';
    
    const formData = new FormData(form);
    
    fetch(form.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Langsung redirect ke halaman payment
            const redirectUrl = (data.data && data.data.redirect) ? data.data.redirect : '<?php echo $urlweb; ?>/m/account/qris_payment';
            window.location.href = redirectUrl;
        } else {
            errorMessage.textContent = data.message || 'Terjadi kesalahan. Silakan coba lagi.';
            errorMessage.style.display = 'block';
            btnSubmit.disabled = false;
            btnSubmit.textContent = 'GENERATE QRIS';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        errorMessage.textContent = 'Terjadi kesalahan. Silakan coba lagi.';
        errorMessage.style.display = 'block';
        btnSubmit.disabled = false;
        btnSubmit.textContent = 'GENERATE QRIS';
    });
});
</script>

<?php include "../footer.php"; ?>
