@extends('frontend.layouts.app')

@section('content')

    @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>{{ session('error') }}</span>
        </div>
    @endif

    @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>{{ session('success') }}</span>
        </div>
    @endif

    <div id="showM">
        <div class="overlap g8mmenu-close"></div>
        @include('frontend.partials.mobile.header')
        @include('frontend.partials.mobile.sidebar-menu')

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

                <div class="funds tab-deposit">
                    <div class="funds__container">
                        <div class="funds__container-section depo-wrap">
                            <div class="wrapper-balance">
                                <span>Saldo</span>
                                <div class="header-balance" style="display: flex; align-items: center; gap: 8px;">
                                    <strong class="g8-bal-total">IDR {{ number_format(Auth::user()->balance ?? 0, 0, ',', '.') }}</strong>
                                    
                                    <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #f99c2a; cursor: pointer;" title="Refresh Saldo">
                                        <i class="fas fa-sync-alt"></i>
                                    </a>
                                </div>
                            </div>
                            <!-- <div class="deposit-settings">
                                <div class="badge-description bg-main fly-2">
                                    <span class="field-description">Limit Per Transaksi</span>
                                </div>
                                <div class="wrapper-deposit-settings">
                                    <div class="bank-name">
                                        <span>Bank</span>
                                    </div>
                                    <div class="max-min">
                                        <span>Min/Max Limit (IDR)</span>
                                    </div>
                                    <div class="amount">
                                        <span>
                                            <span class="minReq">{{ number_format(general()->min_depo ?? 0, 0, ',', '.') }}</span> -
                                            <span class="maxReq">{{ number_format(general()->min_wd ?? 0, 0, ',', '.') }}</span>
                                        </span>
                                    </div>
                                </div>
                                <div class="wrapper-deposit-settings -va" style="display: none;">
                                    <div class="bank-name">
                                        <span>VA Bank</span>
                                    </div>
                                    <div class="max-min">
                                        <span>Min/Max Limit (IDR)</span>
                                    </div>
                                    <div class="amount">
                                        <span>
                                            <span class="minVaReq">{{ number_format(general()->min_depo ?? 0, 0, ',', '.') }}</span> -
                                            <span class="maxVaReq">{{ number_format(general()->min_wd ?? 0, 0, ',', '.') }}</span>
                                        </span>
                                    </div>
                                </div>
                                <div class="wrapper-deposit-settings">
                                    <div class="bank-name">
                                        <span>E-Money</span>
                                    </div>
                                    <div class="max-min">
                                        <span>Min/Max Limit (IDR)</span>
                                    </div>
                                    <div class="amount">
                                        <span>
                                            <span class="minEMoney">{{ number_format(general()->min_depo ?? 0, 0, ',', '.') }}</span> -
                                            <span class="maxEMoney">{{ number_format(general()->min_wd ?? 0, 0, ',', '.') }}</span>
                                        </span>
                                    </div>
                                </div>
                                <div class="wrapper-deposit-settings">
                                    <div class="bank-name">
                                        <span>Pulsa</span>
                                    </div>
                                    <div class="max-min">
                                        <span>Min/Max Limit (IDR)</span>
                                    </div>
                                    <div class="amount">
                                        <span>
                                            <span class="minPulsa">{{ number_format(general()->min_depo ?? 0, 0, ',', '.') }}</span> -
                                            <span class="maxPulsa">{{ number_format(general()->min_wd ?? 0, 0, ',', '.') }}</span>
                                        </span>
                                    </div>
                                </div>
                            </div> -->
                            
                            <div class="form-detail form-detail--full depo-select-wrap">
                                <ul class="depo-select">
                                    <li data-target="#tab-manual-m" class="depomanual active">Deposit (Manual)</li>
                                    @if($bank->where('type', 'otomatis')->count() > 0)
                                    <li data-target="#tab-otomatis-m" class="depocepat ">
                                        Deposit QRIS
                                        <div class="badge-description bg-green fly">
                                            <span class="field-description">Otomatis</span>
                                        </div>
                                    </li>
                                    @endif
                                </ul>
                            </div>
                            
                            <div class="deposit-content-wrapper">
                                
                                <div id="tab-manual-m">
                                    <form action="{{ route('secure.deposit.submit') }}" method="POST" enctype="multipart/form-data" class="validate-form">
                                        @csrf 
                                        <div class="form-group form-detail list-metode depo-form manual">
                                            <label>Pilih Metode Pembayaran:</label>
                                            <div class="row-list-metode" style="display: flex; gap: 10px; margin-bottom: 15px;">
                                                <div class="btn active" data-type="1" style="cursor: pointer;"><i class="fa fa-credit-card"></i> <span>BANK</span></div>
                                                <div class="btn" data-type="11" style="cursor: pointer;"><i class="fa fa-wallet"></i> <span>E-WALLET</span></div>
                                                <div class="btn" data-type="10" style="cursor: pointer;"><i class="fa fa-mobile"></i> <span>PULSA</span></div>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label><span class="text-danger">*</span> Bank Tujuan (Manual)</label>
                                            <select name="ctl00$MainContent$InputSelectedBankAccount" class="form-control required" id="select-bank-manual-m">
                                               
                                                @foreach($bank->where('type', 'manual') as $b)
                                                    <option value="0,1,{{ $b->id }},1" data-category="{{ $b->kategori }}" data-acc="{{ $b->nomor_rekening }}">
                                                        {{ strtoupper($b->nama_bank) }} - {{ $b->nomor_rekening }} ({{ $b->nama_pemilik }})
                                                    </option>
                                                @endforeach
                                            </select>
                                            <button type="button" class="button button-sm button--yellow btn-copy-rek" style="display:none; margin-top:8px; padding: 5px 10px; font-size: 12px; width: auto;"><i class="fa fa-copy"></i> Salin No Rek Bank</button>
                                        </div>

                                        <div class="form-group">
                                            <label><span class="text-danger">*</span> Total (IDR)</label>
                                            <input type="text" name="ctl00$MainContent$InputDepositAmount" class="form-control required amo" placeholder="Contoh: 50000">
                                        </div>

                                        <div class="form-group">
                                            <label>Bonus / Promosi</label>
                                            <select name="ctl00$MainContent$InputSelectedBonus" class="form-control">
                                                <option value="-1">Tanpa Bonus</option>
                                                @foreach($bonus as $bn)
                                                    <option value="{{ $bn->id }}">{{ $bn->judul }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div class="form-group">
                                            <label>Catatan / No. Referensi Pengirim</label>
                                            <input type="text" name="ctl00$MainContent$InputDepositRemark" class="form-control" placeholder="Nama Pengirim / SN">
                                        </div>

                                        <div class="form-group">
                                            <label>Bukti Setoran (Max 1MB)</label>
                                            <input type="file" name="ctl00$MainContent$InputDepositUpload" accept=".pdf,.jpg,.jpeg,.png,.gif" class="form-control">
                                        </div>

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

                                @if($bank->where('type', 'otomatis')->count() > 0)
                                <div id="tab-otomatis-m" >
                                    <form action="{{ route('secure.deposit.submit') }}" method="POST" enctype="multipart/form-data" class="validate-form">
                                        @csrf 
                                        <p style="font-size: 12px; color: #ccc; margin-bottom: 15px; margin-top: 10px;">Pilih jalur QRIS dan masukkan nominal. QR Code akan di-generate setelah Anda menekan tombol Submit.</p>

                                        <div class="form-group" style="display: none;">
                                            <!-- <label><span class="text-danger">*</span> Pilih Jalur QRIS</label> -->
                                            <select name="ctl00$MainContent$InputSelectedBankAccount" class="form-control required" readonly="">
                                                @foreach($bank->where('type', 'otomatis') as $b)
                                                    <option value="0,1,{{ $b->id }},1">
                                                        {{ $b->nama_pemilik }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div class="form-group">
                                            <label><span class="text-danger">*</span> Total (IDR)</label>
                                            <input type="text" name="ctl00$MainContent$InputDepositAmount" class="form-control required amo" placeholder="Contoh: 50000">
                                        </div>

                                        <div class="form-group">
                                            <label>Bonus / Promosi</label>
                                            <select name="ctl00$MainContent$InputSelectedBonus" class="form-control">
                                                <option value="-1">Tanpa Bonus</option>
                                                @foreach($bonus as $bn)
                                                    <option value="{{ $bn->id }}">{{ $bn->judul }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <input type="hidden" name="ctl00$MainContent$InputDepositRemark" value="Deposit Instan (QRIS)">

                                        <div class="form-group">
                                            <button type="submit" class="button button--yellow btn-submit-native">GENERATE QRIS</button>
                                        </div>
                                    </form>
                                </div>
                                @endif

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @include('frontend.partials.mobile.bottom-nav')
    </div>


    <div id="showD">
        @include('frontend.partials.desktop.header')
        <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 class="active">
                            <a href="/secure/admin/deposit">
                                <i class="fas fa-wallet"></i>
                                <span>Deposit</span>
                            </a>
                        </li>
                        <li>
                            <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 {{ number_format(Auth::user()->balance ?? 0, 0, ',', '.') }}</span>
                    <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #f99c2a; 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 class="text-center">Informasi Akun Anda</span></li>
                            <li><span>Bank:</span> <span>{{ strtoupper(auth()->user()->nama_bank ?? '-') }}</span></li>
                            <li><span>No Rek:</span> <span>{{ auth()->user()->nomor_rekening ?? '-' }}</span></li>
                            <li><span>Nama:</span> <span>{{ auth()->user()->nama_pemilik ?? '-' }}</span></li>
                        </ul>
                    </div>

                    <div class="funds__detail-right depo-wrap">
                        
                        <div class="form-detail form-detail--full depo-select-wrap"> 
                            <ul class="depo-select">
                                <li data-target="#tab-manual-d" class="depomanual active">
                                    <div class="icon-menu"><i class="fa fa-inbox"></i></div>
                                    <p>Deposit (Manual)</p>
                                </li>
                                
                                @if($bank->where('type', 'otomatis')->count() > 0)
                                <li data-target="#tab-otomatis-d" class="depocepat ">
                                    <div class="icon-menu"><i class="fa fa-qrcode"></i></div>
                                    <p>Deposit QRIS (Otomatis)</p>
                                    <div class="badge-description bg-green fly">
                                        <span class="field-description">Instan</span>
                                    </div>
                                </li>
                                @endif
                            </ul>
                        </div>

                        <div class="deposit-content-wrapper">
                            
                            <div id="tab-manual-d">
                                <form action="{{ route('secure.deposit.submit') }}" method="POST" enctype="multipart/form-data" class="validate-form">
                                    @csrf 
                                    
                                    <div class="detail-box">
                                        <div class="deposit-option__list-metode">
                                            <div class="form-group form-detail list-metode depo-form manual">
                                                <label>Pilih Metode Pembayaran:</label>
                                                <div class="row-list-metode" style="display: flex; gap: 10px; margin-bottom: 15px;">
                                                    <div class="btn active" data-type="1" style="cursor: pointer; flex: 1;">
                                                        <i class="fa fa-credit-card"></i> <span>BANK</span>
                                                    </div>
                                                    <div class="btn" data-type="11" style="cursor: pointer; flex: 1;">
                                                        <i class="fa fa-wallet"></i> <span>E-WALLET</span>
                                                    </div>
                                                    <div class="btn" data-type="10" style="cursor: pointer; flex: 1;">
                                                        <i class="fa fa-mobile"></i> <span>PULSA</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                            
                                        <div class="deposit-option">
                                            <div class="deposit-option__form">
                                                <div class="form-detail form-detail--full form-group">
                                                    <label><span class="text-danger">*</span> Bank Tujuan (Manual)</label>
                                                    <select name="ctl00$MainContent$InputSelectedBankAccount" class="form-control required" id="select-bank-manual-d">
                                                        
                                                        @foreach($bank->where('type', 'manual') as $b)
                                                            <option value="0,1,{{ $b->id }},1" data-category="{{ $b->kategori }}" data-acc="{{ $b->nomor_rekening }}">
                                                                {{ strtoupper($b->nama_bank) }} - {{ $b->nomor_rekening }} ({{ $b->nama_pemilik }})
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                    <button type="button" class="button button-sm button--yellow btn-copy-rek" style="display:none; margin-top:8px; padding: 5px 10px; font-size: 12px; width: auto;"><i class="fa fa-copy"></i> Salin No Rek Bank</button>
                                                </div>
                            
                                                <div class="form-detail form-detail--full form-group">
                                                    <label><span class="text-danger">*</span> Total (IDR)</label>
                                                    <input type="text" name="ctl00$MainContent$InputDepositAmount" class="form-control required amo" placeholder="Contoh: 50000">
                                                </div>
                            
                                                <div class="form-detail form-detail--full form-group">
                                                    <label>Bonus / Promosi</label>
                                                    <select name="ctl00$MainContent$InputSelectedBonus" class="form-control">
                                                        <option value="-1">Tanpa Bonus</option>
                                                        @foreach($bonus as $bn)
                                                            <option value="{{ $bn->id }}">{{ $bn->judul }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                            
                                            <div class="deposit-option__info depo-form manual">
                                                <div class="form-detail form-detail--full">
                                                    <div class="wrapper-information">
                                                        <div class="wrapper-icon">
                                                            <i class="fa fa-info"></i>
                                                        </div>
                                                        <span>Silakan transfer ke rekening yang tertera terlebih dahulu, setelah anda melakukan transfer, kemudian isi dan lengkapi form deposit berikut.</span>
                                                    </div>
                                                </div>
                            
                                                <div class="form-detail form-detail--full form-group">
                                                    <label>Catatan / No. Referensi Pengirim</label>
                                                    <input type="text" name="ctl00$MainContent$InputDepositRemark" class="form-control" placeholder="Nama / No Referensi">
                                                </div>
                                                
                                                <div class="form-detail form-detail--full form-group">
                                                    <label>Bukti Setoran (Max 1MB)</label>
                                                    <input type="file" name="ctl00$MainContent$InputDepositUpload" accept=".pdf,.jpg,.jpeg,.png,.gif" class="form-control">
                                                </div>
                                            </div>
                                        </div>
                                        <button type="submit" class="button button--yellow btn-submit-native" style="margin-top: 15px;">SUBMIT DEPOSIT</button>
                                    </div>
                                </form>
                            </div>

                            @if($bank->where('type', 'otomatis')->count() > 0)
                            <div id="tab-otomatis-d">
                                <form action="{{ route('secure.deposit.submit') }}" method="POST" enctype="multipart/form-data" class="validate-form">
                                    @csrf 
                                    <div class="deposit-option">
                                        <div class="deposit-option__form" style="width: 100%;">
                                            <div class="form-detail form-detail--full">
                                                <div class="row-title">
                                                    <span class="field-title" style="color: #f99c2a;">GENERATE QRIS OTOMATIS</span>
                                                </div>
                                                <p style="font-size: 12px; color: #ccc; margin-bottom: 15px;">Pilih jalur QRIS dan masukkan nominal. QR Code akan di-generate setelah Anda menekan tombol Submit.</p>
                                            </div>

                                            <div class="form-detail form-detail--full form-group">
                                                <!-- <label><span class="text-danger">*</span> Pilih Jalur QRIS</label> -->
                                                <select name="ctl00$MainContent$InputSelectedBankAccount" class="form-control required" style="display: none;" readonly="">
                                                    @foreach($bank->where('type', 'otomatis') as $b)
                                                        <option value="0,1,{{ $b->id }},1">
                                                            {{ $b->nama_pemilik }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <div class="form-detail form-detail--full form-group">
                                                <label><span class="text-danger">*</span> Total (IDR)</label>
                                                <input type="text" name="ctl00$MainContent$InputDepositAmount" class="form-control required amo" placeholder="Contoh: 50000">
                                            </div>

                                            <div class="form-detail form-detail--full form-group">
                                                <label>Bonus / Promosi</label>
                                                <select name="ctl00$MainContent$InputSelectedBonus" class="form-control">
                                                    <option value="-1">Tanpa Bonus</option>
                                                    @foreach($bonus as $bn)
                                                        <option value="{{ $bn->id }}">{{ $bn->judul }}</option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <input type="hidden" name="ctl00$MainContent$InputDepositRemark" value="Deposit Instan (QRIS)">
                                        </div>
                                    </div>
                                    <button type="submit" class="button button--yellow btn-submit-native">GENERATE QRIS</button>
                                </form>
                            </div>
                            @endif

                        </div>
                    </div>
                </div>
            </section>
        </div>
        @include('frontend.partials.desktop.footer')
    </div>
@endsection
<div id="qris-overlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.85); z-index:99999; justify-content:center; align-items:center; backdrop-filter: blur(5px);">
    <div style="background:#fff; padding:25px; border-radius:15px; width:90%; max-width:400px; text-align:center; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
        <h4 style="color:#2c3e50; font-weight:900; margin-bottom:10px;"><i class="fas fa-qrcode text-warning"></i> Deposit QRIS</h4>
        <p style="color:#7f8c8d; font-size:13px; margin-bottom:15px; line-height:1.4;">Silakan scan QR Code di bawah ini menggunakan aplikasi E-Wallet atau M-Banking Anda (OVO, DANA, BCA, dll).</p>
        
        <div style="background:#f8f9fa; padding:15px; border-radius:10px; border:2px dashed #bdc3c7; display:inline-block;">
            <img id="qris-image" src="" alt="QR Code" style="width:200px; height:200px; object-fit: contain; display:block; margin: 0 auto;">
        </div>
        
        <h2 style="color:#e67e22; font-weight:900; margin-top:15px; font-size: 28px;" id="qris-amount">Rp 0</h2>
        <p style="color:#95a5a6; font-size:12px; margin-bottom:0;">NO. TRX: <strong id="qris-trx" style="color:#34495e;"></strong></p>
        
        <div style="background:#ffeaa7; color:#d35400; padding:10px; border-radius:8px; margin-top:15px; font-weight:bold;">
            Waktu Kadaluarsa: <span id="qris-timer" style="font-size: 18px;">05:00</span>
        </div>
        
        <p style="font-size: 11px; color:#7f8c8d; margin-top:10px;"><i class="fas fa-circle-notch fa-spin"></i> Menunggu pembayaran otomatis...</p>

        <button type="button" id="btn-cancel-qris" class="button button--register" style="background: #e74c3c; width:100%; margin-top:10px; border:none; padding:12px;">Batalkan Transaksi</button>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {

    // Tampilkan Flash Message bawaan Laravel (Jika disubmit 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';
        });
    }

    // 1. Fungsi Pindah Tab (Mobile & Desktop)
    $('.depo-select li').on('click', function() {
        if($(this).hasClass('active')) return;
        $(this).parent().find('li').removeClass('active');
        $(this).addClass('active');

        let targetId = $(this).attr('data-target');
        $(this).closest('.depo-wrap').find('.deposit-content-wrapper > div').hide();
        $(targetId).fadeIn(300);
    });

    // 2. Fungsi Filter Bank / E-Wallet / Pulsa
    let allBankOptionsM = $('#select-bank-manual-m option').clone();
    let allBankOptionsD = $('#select-bank-manual-d option').clone();

    $('.row-list-metode .btn').on('click', function() {
        let parentWrapper = $(this).closest('form');
        
        parentWrapper.find('.row-list-metode .btn').removeClass('active');
        $(this).addClass('active');

        let selectedType = $(this).attr('data-type');
        let $selectBank = parentWrapper.find('select[name="ctl00$MainContent$InputSelectedBankAccount"]');
        let $btnCopy = parentWrapper.find('.btn-copy-rek'); 
        
        $selectBank.empty();
        $selectBank.append('<option value="">-- Silahkan Pilih Rekening Tujuan --</option>');
        $btnCopy.hide(); 

        let backupOptions = parentWrapper.closest('#showM').length > 0 ? allBankOptionsM : allBankOptionsD;

        backupOptions.each(function() {
            let cat = $(this).attr('data-category');
            if (!cat || cat == selectedType) {
                $selectBank.append($(this).clone());
            }
        });
    });

    $('#showM .row-list-metode .btn.active').trigger('click');
    $('#showD .row-list-metode .btn.active').trigger('click');

    // 3. FITUR: Munculkan Tombol Salin No Rekening
    $('select[name="ctl00$MainContent$InputSelectedBankAccount"]').on('change', function() {
        let accNo = $(this).find(':selected').attr('data-acc');
        let $btnCopy = $(this).closest('.form-group').find('.btn-copy-rek');

        if(accNo) {
            $btnCopy.attr('data-rek', accNo).fadeIn();
        } else {
            $btnCopy.hide();
        }
    });

    // 4. FITUR: Eksekusi Copy to Clipboard saat diklik
    $(document).on('click', '.btn-copy-rek', function(e) {
        e.preventDefault();
        let rek = $(this).attr('data-rek');
        
        let tempInput = $("<input>");
        $("body").append(tempInput);
        tempInput.val(rek).select();
        document.execCommand("copy");
        tempInput.remove();

        let originalHtml = $(this).html();
        $(this).html('<i class="fas fa-check"></i> Tersalin!');
        setTimeout(() => { $(this).html(originalHtml); }, 2000);
    });

    // 5. 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);
    });

    // 6. FITUR: VALIDASI & JCONFIRM DENGAN DOMParser
    $('form.validate-form').on('submit', function(e) {
        e.preventDefault(); 
        let $form = $(this);

        let isValid = true;
        let bankInput = $form.find('select[name="ctl00$MainContent$InputSelectedBankAccount"]');
        let amountInput = $form.find('input[name="ctl00$MainContent$InputDepositAmount"]');

        if(bankInput.val() === '') {
            isValid = false;
            bankInput.addClass('error'); 
        } else {
            bankInput.removeClass('error');
        }

        if(amountInput.val() === '') {
            isValid = false;
            amountInput.addClass('error');
        } else {
            amountInput.removeClass('error');
        }

        if(!isValid) {
            jAlert('Silahkan lengkapi kolom bertanda bintang (*)', 'Peringatan');
            return false;
        }

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

        $.alerts.okButton = 'YA, KIRIM';
        $.alerts.cancelButton = 'BATAL';

        jConfirm('Kirim konfirmasi deposit sebesar IDR ' + nominal + '?', 'Deposit', function(r) {
            if (r == true) {
                executeAjaxSubmit($form, $btn, originalText);
            }
        });
        
        $.alerts.okButton = 'OK';
    });
    
    let qrisInterval;
    let qrisCountdown;

    function executeAjaxSubmit($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'),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                // Karena controller sudah kita set mereturn JSON
                if(response.success) {
                    if(response.is_qris) {
                        $btn.prop('disabled', false).html(originalText);
                        // BUKA POPUP QRIS
                        openQrisOverlay(response.qris_code, response.trx_id, response.amount);
                    } else {
                        // JIKA DEPOSIT MANUAL (BANK/PULSA)
                        jAlert(response.message, 'Berhasil', function() {
                            window.location.href = '/secure/admin/history';
                        });
                    }
                } else {
                    jAlert(response.message, 'Gagal', function() {
                        $btn.prop('disabled', false).html(originalText);
                    });
                }
            },
            error: function(xhr) {
                let errorMsg = xhr.responseJSON && xhr.responseJSON.message 
                               ? xhr.responseJSON.message 
                               : 'Terjadi kesalahan sistem/koneksi.';
                jAlert(errorMsg, 'Error', function() {
                    $btn.prop('disabled', false).html(originalText);
                });
            }
        });
    }
    
    // TAMBAHKAN parameter ke-4: customTimeLeft (Default 300 / 5 Menit)
    function openQrisOverlay(qrisUrl, trxId, amount, customTimeLeft = 300) {
        $('#qris-image').attr('src', qrisUrl);
        $('#qris-amount').text('Rp ' + parseInt(amount).toLocaleString('id-ID'));
        $('#qris-trx').text(trxId);
        
        $('#qris-overlay').css('display', 'flex').hide().fadeIn(300);
    
        // Gunakan customTimeLeft, bukan 300 paten
        let timeLeft = parseInt(customTimeLeft); 
        
        clearInterval(qrisInterval);
        clearInterval(qrisCountdown);
    
        qrisCountdown = setInterval(function() {
            timeLeft--;
            let m = Math.floor(timeLeft / 60).toString().padStart(2, '0');
            let s = (timeLeft % 60).toString().padStart(2, '0');
            $('#qris-timer').text(m + ':' + s);
    
            if (timeLeft <= 0) {
                cancelQrisTransaction(trxId, true);
            }
        }, 1000);
    
        qrisInterval = setInterval(function() {
            $.get('/api/qr/pay_status/' + trxId, function(res) {
                if (res.status === 1) { 
                    clearInterval(qrisInterval);
                    clearInterval(qrisCountdown);
                    jAlert('Pembayaran QRIS Berhasil Terdeteksi!', 'Sukses', function() {
                        window.location.href = '/secure/admin/history';
                    });
                } else if (res.status === 0 || res.status === -1) { 
                    clearInterval(qrisInterval);
                    clearInterval(qrisCountdown);
                    jAlert('Pembayaran ditolak atau dibatalkan.', 'Gagal', function() {
                        $('#qris-overlay').fadeOut();
                        window.location.reload();
                    });
                }
            });
        }, 5000); 
    
        $('#btn-cancel-qris').off('click').on('click', function() {
            jConfirm('Anda yakin ingin membatalkan transaksi QRIS ini?', 'Batal', function(r) {
                if(r) cancelQrisTransaction(trxId, false);
            });
        });
    }
    
    function cancelQrisTransaction(trxId, isTimeout = false) {
        clearInterval(qrisInterval);
        clearInterval(qrisCountdown);
        
        let btnCancel = $('#btn-cancel-qris');
        btnCancel.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Membatalkan...');
    
        $.get('/api/qr/cancel_pay/' + trxId, function(res) {
            let msg = isTimeout ? 'Waktu pembayaran telah habis. Transaksi dibatalkan otomatis.' : 'Transaksi berhasil dibatalkan.';
            jAlert(msg, 'Dibatalkan', function() {
                $('#qris-overlay').fadeOut();
                window.location.reload(); // Refresh halaman
            });
        }).fail(function() {
            // Jika gagal koneksi saat batal
            window.location.reload();
        });
    }
    
    @if(!empty($check_qr))
        @php
            // Hitung sisa waktu di sisi server (PHP)
            $waktuDibuat = \Carbon\Carbon::parse($check_qr->created_at);
            $waktuSekarang = \Carbon\Carbon::now();
            $selisihDetik = $waktuDibuat->diffInSeconds($waktuSekarang);
            $sisaWaktu = 300 - $selisihDetik; // 300 detik = 5 Menit
        @endphp

        let sisaWaktuQRIS = {{ $sisaWaktu }};
        let trxIdPending = '{{ $check_qr->trx_id }}';
        
        let qrisUrlPending = '{!! $check_qr->qris_code !!}';
        let amountPending = '{{ $check_qr->total }}';

        if (sisaWaktuQRIS > 0) {
            // Jika waktu masih ada, beri jeda 500ms agar halaman beres me-load CSS dulu
            setTimeout(function() {
                openQrisOverlay(qrisUrlPending, trxIdPending, amountPending, sisaWaktuQRIS);
            }, 500);
        } else {
            // Jika saat direfresh ternyata waktunya SUDAH HABIS (< 0 detik)
            // Langsung tembak API untuk membatalkan transaksi diam-diam
            $.get('/api/qr/cancel_pay/' + trxIdPending, function() {
                console.log('Transaksi expired berhasil dibersihkan otomatis.');
            });
        }
    @endif
});
</script>
@endpush