<?php $__env->startSection('content'); ?>

    <?php if(session('error')): ?>
        <div style="background: #ff4d4d; color: white; padding: 15px; text-align: center; font-weight: bold; z-index: 9999; position: relative; display: none;" id="flash-error">
            <i class="fas fa-exclamation-triangle"></i> <span><?php echo e(session('error')); ?></span>
        </div>
    <?php endif; ?>

    <?php if(session('success')): ?>
        <div style="background: #28a745; color: white; padding: 15px; text-align: center; font-weight: bold; z-index: 9999; position: relative; display: none;" id="flash-success">
            <i class="fas fa-check-circle"></i> <span><?php echo e(session('success')); ?></span>
        </div>
    <?php endif; ?>

    <div id="showM">
        <div class="overlap g8mmenu-close"></div>
        <?php echo $__env->make('frontend.partials.mobile.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        <?php echo $__env->make('frontend.partials.mobile.sidebar-menu', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

        <div class="content">
            <div class="funds__container-section">
                
                <div class="wrapper-toggle">
                    <a href="<?php echo e(route('secure.deposit')); ?>" class="btn"><i class="fas fa-wallet"></i> Deposit</a>
                    <a href="<?php echo e(route('secure.withdrawal')); ?>" class="btn active"><i class="fas fa-money-bill"></i> Withdrawal</a>
                </div>

                <div class="funds">
                    <div class="funds__container">
                        <div class="funds__container-section">
                            
                            <div class="wrapper-balance">
                                <span>Saldo</span>
                                <div class="header-balance" style="display: flex; align-items: center; gap: 8px;">
                                    <strong class="g8-bal-total total-icon-new">IDR <?php echo e(number_format(Auth::user()->balance ?? 0, 0, ',', '.')); ?></strong>
                                    <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #f99c2a; cursor: pointer; font-size: 14px;" title="Refresh Saldo">
                                        <i class="fas fa-sync-alt"></i>
                                    </a>
                                </div>
                            </div>
                            
                            <table class="table table-sm deposit-settings-offline">
                                <tbody>
                                    <tr>
                                        <td>Min Limit (IDR)</td>
                                        <th><span class="minReq">50.000</span></th>
                                    </tr>
                                    <tr>
                                        <td>Bank Name</td>
                                        <th><span class="bankName"><?php echo e(strtoupper(Auth::user()->nama_bank ?? '-')); ?></span></th>
                                    </tr>
                                    <tr>
                                        <td>Bank Account No</td>
                                        <th><span class="bankAccNo"><?php echo e(Auth::user()->nomor_rekening ?? '-'); ?></span></th>
                                    </tr>
                                    <tr>
                                        <td>Bank Account Name</td>
                                        <th><span class="bankAccName"><?php echo e(Auth::user()->nama_pemilik ?? '-'); ?></span></th>
                                    </tr>
                                </tbody>
                            </table>
                            
                            <form id="confirm-form-2" action="<?php echo e(route('secure.withdrawal.submit')); ?>" method="POST" class="validate-form-wd">
                                <?php echo csrf_field(); ?> 
                                
                                <div class="form-group my-banks" style="display: none;">
                                    <label><span class="text-danger">*</span> Tarik ke Rekening</label>
                                    <input type="text" name="bank" class="form-control" value="<?php echo e(strtoupper(Auth::user()->nama_bank ?? '')); ?> - <?php echo e(Auth::user()->nomor_rekening ?? ''); ?> (<?php echo e(Auth::user()->nama_pemilik ?? ''); ?>)" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                                </div>
                                
                                <div class="form-group w-amo-av">
                                    <label>Saldo Yang Tersedia</label>
                                    <p class="w-amo-av-dd g8-bal-total">IDR <?php echo e(number_format(Auth::user()->balance ?? 0, 0, ',', '.')); ?></p>
                                </div>
                                
                                <div class="form-group w-amo">
                                    <label><span class="text-danger"> *</span> Total Penarikan (IDR)</label>
                                    <input type="text" name="RealAmount" class="form-control required amo" placeholder="Contoh: 50000">
                                </div>
                                
                                <div class="form-group" style="display: none;">
                                    <label>Keterangan / Catatan</label>
                                    <input type="text" name="keterangan" class="form-control" placeholder="Opsional">
                                </div>

                                <div class="form-group">
                                    <button type="submit" class="button button--yellow btn-submit-native">SUBMIT</button>
                                </div>
                            </form>
                            
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <?php echo $__env->make('frontend.partials.mobile.bottom-nav', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>


    <div id="showD">
        <?php echo $__env->make('frontend.partials.desktop.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        <section class="profile">
            <div class="wrapper">
                <div class="profile__nav">
                    <ul>
                        <li>
                            <a href="/secure/admin/profile">
                                <i class="far fa-user"></i>
                                <span>Profile</span>
                            </a>
                        </li>
                        <li >
                            <a href="/secure/admin/deposit">
                                <i class="fas fa-wallet"></i>
                                <span>Deposit</span>
                            </a>
                        </li>
                        <li class="active">
                            <a href="/secure/admin/withdrawal">
                                <i class="fas fa-money-bill"></i>
                                <span>Withdrawal</span>
                            </a>
                        </li>
                        <li>
                            <a href="/secure/admin/bonus">
                                <i class="fas fa-dollar-sign"></i>
                                <span>Bonus</span>
                            </a>
                        </li>
                        <li>
                            <a href="/secure/admin/history">
                                <i class="fas fa-history"></i>
                                <span>History</span>
                            </a>
                        </li>
                        <li>
                            <a href="/secure/admin/referral">
                                <i class="fas fa-users"></i>
                                <span>Referral</span>
                            </a>
                        </li>
                        <li>
                            <a href="/secure/admin/messages">
                                <i class="fas fa-envelope"></i>
                                <span>Messages</span>
                            </a>
                            <div class="notif-wrapper hide">
                                <div class="notif-info notanim"></div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </section>

        <div class="wrapper">
            <section class="balance">
                <div class="g8-bal-top"><p>Saldo</p>
                    <span class="g8-bal-total">IDR <?php echo e(number_format(Auth::user()->balance ?? 0, 0, ',', '.')); ?></span>
                    <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #000; cursor: pointer;" title="Refresh Saldo">
                        <i class="fas fa-sync-alt"></i>
                    </a>
                </div>
            </section>

            <section class="funds">
                <div class="funds__detail">
                    
                    <div class="funds__detail-left">
                        <ul>
                            <li><span>Min Limit (IDR):</span><span><span class="minReq">50.000</span></span></li>
                            <li><span>Bank Name:</span><span class="bankName"><?php echo e(strtoupper(Auth::user()->nama_bank ?? '-')); ?></span></li>
                            <li><span>Bank Account No:</span><span class="bankAccNo"><?php echo e(Auth::user()->nomor_rekening ?? '-'); ?></span></li>
                            <li><span>Bank Account Name:</span><span class="bankAccName"><?php echo e(Auth::user()->nama_pemilik ?? '-'); ?></span></li>
                        </ul>
                    </div>

                    <div class="funds__detail-right">
                        <form id="confirm-form" action="<?php echo e(route('secure.withdrawal.submit')); ?>" method="POST" class="validate-form-wd">
                            <?php echo csrf_field(); ?> 
                            <div class="detail-box">
                                <div class="form-detail form-detail--full"><label class="field-title">Withdrawal Information</label>
                                    <hr>
                                </div>
                                <div class="deposit-option">
                                    <div class="deposit-option__form">
                                        
                                        <div class="form-detail form-detail--full my-banks" style="display: none;">
                                            <label><span class="text-danger">*</span> Tarik ke Rekening</label>
                                            <input type="text" name="bank" class="form-control" value="<?php echo e(strtoupper(Auth::user()->nama_bank ?? '')); ?> - <?php echo e(Auth::user()->nomor_rekening ?? ''); ?> (<?php echo e(Auth::user()->nama_pemilik ?? ''); ?>)" readonly style="background-color: #e9ecef; cursor: not-allowed; width: 100%;">
                                        </div>
                                        
                                        <div class="form-detail form-detail--full w-amo">
                                            <label><span class="text-danger">*</span> Total Penarikan (IDR)</label>
                                            <input type="text" name="RealAmount" class="form-control required amo" placeholder="Contoh: 50000" style="width: 100%;">
                                        </div>
                                        
                                        <div class="form-detail form-detail--full" style="display: none;">
                                            <label>Keterangan / Catatan</label>
                                            <input type="text" name="keterangan" class="form-control" placeholder="Opsional" style="width: 100%;">
                                        </div>

                                    </div>
                                    <div class="deposit-option__info">
                                        <div class="form-detail form-detail--full w-amo-av">
                                            <label>Saldo Yang Tersedia</label>
                                            <h3 class="w-amo-av-dd g8-bal-total">IDR <?php echo e(number_format(Auth::user()->balance ?? 0, 0, ',', '.')); ?></h3>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="button button--yellow btn-submit-native">SUBMIT</button>
                        </form>
                    </div>

                </div>
            </section>
        </div>
        <?php echo $__env->make('frontend.partials.desktop.footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script type="text/javascript">
$(document).ready(function() {

    // 1. Tampilkan Flash Message (Jika non-AJAX)
    if($('#flash-error span').text().trim() !== '') {
        jAlert($('#flash-error span').text(), 'Gagal');
    }
    if($('#flash-success span').text().trim() !== '') {
        jAlert($('#flash-success span').text(), 'Berhasil', function() {
            window.location.href = '/secure/admin/history';
        });
    }

    // 2. Fungsi Refresh Saldo
    $('.btn-refresh-balance').on('click', function(e) {
        e.preventDefault();
        let $icons = $('.btn-refresh-balance i'); 
        let $balanceSpans = $('.g8-bal-total');

        $icons.addClass('fa-spin');
        
        $.ajax({
            url: "<?php echo e(route('api.balance')); ?>", 
            type: "GET",
            success: function(response) {
                $icons.removeClass('fa-spin');
                if (response && response.d) {
                    $balanceSpans.html(response.d);
                }
            },
            error: function() {
                $icons.removeClass('fa-spin');
                console.error("Gagal mengambil data saldo terbaru.");
            }
        });
    });

    // 3. Fitur Pemisah Ribuan (1.000.000)
    $('.amo').on('keyup', function() {
        var value = $(this).val().replace(/[^,\d]/g, '');
        var split = value.split(',');
        var sisa = split[0].length % 3;
        var rupiah = split[0].substr(0, sisa);
        var ribuan = split[0].substr(sisa).match(/\d{3}/gi);

        if(ribuan) {
            var separator = sisa ? '.' : '';
            rupiah += separator + ribuan.join('.');
        }
        rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
        $(this).val(rupiah);
    });

    // 4. FITUR: VALIDASI, POPUP KONFIRMASI & AJAX
    $('form.validate-form-wd').on('submit', function(e) {
        e.preventDefault(); 
        let $form = $(this);

        let isValid = true;
        let amountInput = $form.find('input[name="RealAmount"]');

        // Validasi Nominal
        if(amountInput.val() === '') {
            isValid = false;
            amountInput.addClass('error');
            amountInput.css('border', '1px solid red');
        } else {
            amountInput.removeClass('error');
            amountInput.css('border', '');
        }

        if(!isValid) {
            jAlert('Silahkan masukkan nominal penarikan Anda!', 'Peringatan');
            return false;
        }

        let $btn = $form.find('button[type="submit"]');
        let originalText = $btn.html();
        let nominal = amountInput.val();

        // Konfirmasi dengan jConfirm bawaan Template Anda
        $.alerts.okButton = 'YA, TARIK DANA';
        $.alerts.cancelButton = 'BATAL';

        jConfirm('Kirim permintaan withdraw sebesar IDR ' + nominal + '?', 'Withdrawal', function(r) {
            if (r == true) {
                executeAjaxSubmitWD($form, $btn, originalText);
            }
        });
        
        $.alerts.okButton = 'OK'; // Kembalikan teks tombol default
    });

    function executeAjaxSubmitWD($form, $btn, originalText) {
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Memproses...');
        
        let formData = new FormData($form[0]);

        $.ajax({
            url: $form.attr('action'), // Otomatis mengambil rute 'secure.withdrawal.submit'
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                // Karena Controller sudah membalas dengan JSON, kita langsung baca properti 'success'-nya
                if (res.success) {
                    $.alerts.okButton = 'OK'; 
                    jAlert(res.message || 'Permintaan withdraw Anda telah berhasil dikirim.', 'Berhasil', function() {
                        window.location.href = res.redirect_url || '/secure/admin/history';
                    });
                } else {
                    // Jika validasi saldo kurang / TO belum tercapai
                    $.alerts.okButton = 'OK';
                    jAlert(res.message, 'Gagal', function() {
                        $btn.prop('disabled', false).html(originalText);
                    });
                }
            },
            error: function(xhr) {
                let msg = 'Terjadi kesalahan sistem/koneksi.';
                if(xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                
                $.alerts.okButton = 'OK';
                jAlert(msg, 'Error', function() {
                    $btn.prop('disabled', false).html(originalText);
                });
            }
        });
    }

});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('frontend.layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /www/wwwroot/website/sewa/butuhjp/resources/views/frontend/pages/secure/withdrawal.blade.php ENDPATH**/ ?>