<?php
use App\Models\Setting;
use App\Models\PromoDetails;
use App\Models\BankAccount;
use App\Models\Banks;

$userBanks = BankAccount::where('user_id', auth()->user()->id)->get();
$setting = Setting::first();
$banks = Banks::all();


$promoDetails = PromoDetails::all();

$bank_status = [];
foreach ($banks as $bank) {
  $bank_status[$bank->nama_bank] = $bank->status == 1;
}
?>

<style>
  * {
    -webkit-backface-visibility: visible;
  }
  select >option.disble {
    background-color: #d4d4d4;
  }
</style>
<form id="depositForm" class="needs-validation" action="{{ URL::to('account/deposit') }}" method="post" accept-charset="UTF-8" enctype="multipart/form-data" novalidate="novalidate">
  @csrf

  <div class="box-wrapper plr-15">
    <div class="row d-flex">
      <div class="col-md-3 col-xs-4  ">
        <div class="font-weight-bold">
          Metode Penyetoran<span class="text-danger">*</span>
        </div>
      </div>

      <div class="col-md-9 col-xs-8 d-flex flex-wrap">
        <div class="radio_2 ">
          <input class="" id="radioBank5" name="deposite_method" checked="" type="radio" value="5">
          <label class=" " for="radioBank5">
            <span class="radio-title">
             Bank                </span>
            <span class="marked">
              <i class="icon-checkmark"></i>
            </span>
          </label>
        </div>
        <span class="method-check-type" id="checkType">(Manual Cek)</span>
        <span class="deposit-info">
          <span id=""></span>
          Jumlah Deposit IDR
          <span id=""></span>
        </span>
      </div>
    </div>
    <div class="tab">
      <!--- First Tab ----->
      <!------------------------------------ Except Crypto Show Sender Banks Details ------------------------->
      <div class="row d-flex" id="deposit-form-05">
        <div class="col-md-3 col-xs-4  ">
          <div class="font-weight-bold">
            Pilih Rekening<span class="text-danger">*</span>
          </div>
        </div>
        <div class="col-md-9 col-xs-8  d-flex flex-wrap user_bank">
          <div class="col-xs-8" style="padding-left:0px">
            <select class="form-control m-15" data-type="05" id="bank_user_id" name="bank_name" style="height: 35px;" required="">
              <option selected="" value="">- Silahkan pilih -</option>
              @foreach($userBanks as $bank)
              <option value="{{ $bank->bank }} - {{ $bank->no_rek }} - {{ $bank->nama_rek }}" status="1" class="" data-metname="{{ $bank->method }}" data-method="5">
                {{ $bank->bank }}-XXX - XXX -
                {{ substr($bank->no_rek, -4) }}
              </option>
              @endforeach
            </select>
          </div>

          <div class="col-xs-4 mob_add_btn bank_add_btn_sec">
            <button type="button" class="btn btn-primary" id="btn_add_ubank__depo">+ ADD</button>
          </div>
        </div>
      </div>


      <!------------------------------------ Except Crypto Show Sender Banks Details End ------------------------->
      <div class=" deposit-form row d-flex" id="deposit-form-5" style="">
        <div class="col-md-3 col-xs-4  ">
          <div class="font-weight-bold">
            Bank Penerima <span class="text-danger">*</span>
          </div>
        </div>


        <div class="col-md-9 col-xs-8  d-flex flex-wrap">
          <!-- deposit_form.blade.php -->

          <select class="form-control bank_list m-15" data-type="5" data-plugin="bank_list" id="bank_name_5" name="destination_account" required="">
            <option selected="" value="">- Silahkan pilih -</option>
            @foreach($banks as $bank)
            <option value="{{ $bank->select_name }}" data-min-deposit="{{ $bank->min_deposit }}" data-max-deposit="{{ $bank->max_deposit }}" data-p_id="{{ $bank->provider_id }}" bank_name="{{ $bank->nama_bank }}" data-status="{{ $bank->status }}">
              {{ $bank->nama_bank }}
            </option>
            @endforeach
          </select>



          <input type="hidden" id="pID" value="{{ $pID }}">
          <input type="hidden" name="metode_deposit" value="Bank">
          <input type="hidden" name="status" value="1">
          <input type="hidden" name="bank_id" value="1">


          <script>
            $(document).ready(function() {

              var providerSettingID = $('#providerSettingID').val();
              var pID = $('#pID').val();


              $('.bank_list').change(function() {
                var selectedOption = $(this).find('option:selected');
                var selectedBankName = selectedOption.attr('destination_account');
                var selectedProviderID = selectedOption.attr('data-p_id');

                console.log('Bank Name:', selectedBankName);
                console.log('Provider ID:', selectedProviderID);
              });
            });
          </script>
        </div>
      </div>


      <div class="row  info-lst" id="bankList2" style="">
        <div class="col-md-3">
          <div class="qrcode"></div>
        </div>
        <div class="col-xs-12 col-md-9 ">
          <div class="bankInfo-box">

            <script>
              $(document).ready(function() {

                $('[data-toggle="tooltip"]').tooltip();
              });

            </script>
          </div>
        </div>
      </div>

      {{-- ===============================
     BONUS / PROMO DEPOSIT (FINAL)
     =============================== --}}

<div class="row d-flex">
    <div class="col-md-3 col-xs-4">
        <div class="font-weight-bold">
            Bonus
        </div>
    </div>

    <div class="col-md-9 col-xs-8 d-flex flex-wrap">
        <div class="m-15" style="width:100%;">

            {{-- PILIH PROMO --}}
            <select class="form-control"
                    name="select_name"
                    id="promo_event">
                <option value="">Pilih promo tersedia</option>

                @foreach($promoDetails as $promo)
                    <option value="{{ $promo->id }}"
                            data-pname="{{ $promo->promo_name }}">
                        {{ $promo->promo_name }}
                    </option>
                @endforeach
            </select>

            <input type="hidden" name="p_name" id="p_name_hidden">
        </div>

        <div class="fs-sm">
            <span>Ada kode promosi?</span>
            <button type="button"
                    class="btn btn-link txt_accent fs-sm"
                    id="btn_add_promo">
                Tambah disini
            </button>
        </div>
    </div>
</div>

{{-- ===============================
     RINCIAN PROMOSI (FONT TIDAK PUTIH)
     =============================== --}}
<div class="row info-lst" id="promoInfo_de001" style="display:none;">
    <div class="col-md-3"></div>
    <div class="col-xs-12 col-md-9">
        <div class="bankInfo-box" style="color:#000;"> {{-- kunci warna --}}

            {{-- HEADER --}}
            <div class="box-title" style="color:#000;">
                <i class="icon-invoice i-invoice"></i>
                Rincian Promosi
                <button type="button"
                        class="btn btn-click pull-right"
                        id="btn-clear-all-promo">
                    CLEAR PROMO
                </button>
            </div>

            {{-- BODY --}}
            <div class="bankInfo-body" style="color:#000;">
                <table class="table table-borderless" style="color:#000;">
                    <tbody>

                        {{-- JUDUL PROMO --}}
                        <tr>
                            <td colspan="2"
                                class="text-center"
                                style="font-weight:700; padding:10px 0; color:#000;">
                                <span id="promo_name" style="color:#000;">-</span>
                            </td>
                        </tr>

                        {{-- JENIS BONUS --}}
                        <tr>
                            <td style="color:#000;">Jenis Bonus</td>
                            <td class="text-right">
                                <span class="label label-warning"
                                      id="jenis_promosi_text"
                                      style="color:#000;">
                                    -
                                </span>
                            </td>
                        </tr>

                        {{-- MIN DEPOSIT --}}
                        <tr>
                            <td style="color:#000;">Min Deposit</td>
                            <td class="text-right">
                                <span class="label label-warning"
                                      id="promo_min_amount_text"
                                      style="color:#000;">
                                    IDR 0
                                </span>
                            </td>
                        </tr>

                        {{-- MAX BONUS --}}
                        <tr>
                            <td style="color:#000;">Maks Bonus</td>
                            <td class="text-right">
                                <span class="label label-warning"
                                      id="promo_max_amount_text"
                                      style="color:#000;">
                                    IDR 0
                                </span>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </div>

            {{-- HIDDEN INPUT --}}
            <input type="hidden" id="jenis_promosi" name="jenis_promosi">
            <input type="hidden" id="promo_min_amount" name="promo_min_amount">
            <input type="hidden" id="promo_max_amount" name="promo_max_amount">

        </div>
    </div>
</div>




{{-- ===============================
     SCRIPT PROMO (AJAX)
     =============================== --}}
<script>
$('#promo_event').on('change', function () {
    const promoId   = $(this).val();
    const promoName = $(this).find(':selected').data('pname') || '';

    $('#p_name_hidden').val(promoName);

    if (!promoId) {
        clearPromo();
        return;
    }

    $.ajax({
        url: "{{ url('/api/promo_details') }}",
        type: "POST",
        data: {
            _token: "{{ csrf_token() }}",
            select_name: promoId,
            method: $('#method').val() // QRIS / BANK / EWALLET
        },
        success: function (res) {
            if (res.status) {
                $('#promoInfo_de001').fadeIn();

                $('#promo_name').text(res.data.judul);
                $('#jenis_promosi_text').text(res.data.jenis_promosi);
                $('#promo_min_amount_text').text('IDR ' + formatNumber(res.data.min_deposit));
                $('#promo_max_amount_text').text('IDR ' + formatNumber(res.data.max_bonus));

                $('#jenis_promosi').val(res.data.jenis_promosi);
                $('#promo_min_amount').val(res.data.min_deposit);
                $('#promo_max_amount').val(res.data.max_bonus);
            } else {
                clearPromo();
                alert(res.message || 'Promo tidak tersedia');
            }
        },
        error: function () {
            clearPromo();
            alert('Gagal mengambil detail promo');
        }
    });
});

$('#btn-clear-all-promo').on('click', function () {
    $('#promo_event').val('');
    clearPromo();
});

function clearPromo() {
    $('#promoInfo_de001').hide();

    $('#promo_name').text('-');
    $('#jenis_promosi_text').text('-');
    $('#promo_min_amount_text').text('IDR 0');
    $('#promo_max_amount_text').text('IDR 0');

    $('#jenis_promosi').val('');
    $('#promo_min_amount').val('');
    $('#promo_max_amount').val('');
    $('#p_name_hidden').val('');
}

function formatNumber(num) {
    return new Intl.NumberFormat('id-ID').format(num || 0);
}
</script>
            </div>
            <div class="fs-sm" style="  ">
              <span style="">Ada kode promosi? </span> <button class="btn btn-link txt_accent fs-sm" id="btn_add_promo" type="button">Tambah disini</button>
            </div>
            <div class="" id="f_grp_promo_code" style="display:none; margin-top:5px;  ">
              <div class="input-group uline">
                <input type="text" disabled="" id="pcode_not_confirm" name="pcode_not_confirm" class="ignore form-control underline " placeholder="Masukkan kode promo" value="">
                <span class="input-group-btn">
                  <button class="btn btn-link  " id="btn_apply_pcode" type="button">Apply</button>
                  <button class="btn btn-link" id="btn_clear_pcode" style="display:none;" type="button">Clear</button>
                </span>
              </div>
              <!-- /input-group -->
            </div>
            <div class="" style="position: relative; width:100% ; margin-bottom:5px; ">
              <input type="hidden" disabled="" id="promo_code" name="promo_code" class="form-control " value="">
            </div>

          </div>
        </div>
      </div>
      <div class="row info-lst" id="promoInfo_de001" style="display: none;">
        <div class="col-md-3"></div>
        <div class="col-xs-12 col-md-9 ">
          <div class="bankInfo-box" id="promoList">

            <!-- Promo List -->

          </div>
        </div>
      </div>
      
<script>
    $(document).ready(function() {
        var messages = {
            nominal: {
                required: "Jumlah deposit tidak boleh kosong",
                number: "Jumlah deposit harus berupa angka",
                min_deposit: "Jumlah deposit harus lebih besar dari minimal deposit (:minDeposit)",
                max_deposit: "Jumlah deposit melebihi maksimal deposit (:maxDeposit)"
            }
        };

        $('.bank_list').change(function() {
            var selectedOption = $(this).find('option:selected');
            var minDeposit = parseFloat(selectedOption.data('min-deposit'));
            var maxDeposit = parseFloat(selectedOption.data('max-deposit'));

            $('.min-deposit-amounts b').text(minDeposit);
            $('.max-deposit-amounts b').text(maxDeposit);
        });

        $('#nominal').focusout(function() {
            var formattedValue = $(this).val().replace(/[^\d.-]/g, '');
            var depositAmount = parseFloat(formattedValue);
            var minDeposit = parseFloat($('.min-deposit-amounts b').text());
            var maxDeposit = parseFloat($('.max-deposit-amounts b').text());

            if (isNaN(depositAmount)) {
                Swal.fire(messages.nominal.number);
                $(this).val('');
            } else if (depositAmount < minDeposit) {
                Swal.fire(messages.nominal.min_deposit.replace(':minDeposit', minDeposit));
                $(this).val('');
            } else if (depositAmount > maxDeposit) {
                Swal.fire(messages.nominal.max_deposit.replace(':maxDeposit', maxDeposit));
                $(this).val('');
            }
        });

        $('#nominal').priceFormat({
            prefix: '',
            centsLimit: 0,
            thousandsSeparator: ',',
            clearOnEmpty: true
        });
    });
</script>

      <div class="row d-flex">
        <div class="col-md-3 col-xs-4 ">
          <div class="font-weight-bold">
            Jumlah Deposit<span class="text-danger">*</span>
          </div>
        </div>
        <div class="col-md-9 col-xs-8">
          <div class=" d-flex flex-wrap">
            <input type="tel" class="form-control m-15" placeholder="0.00" id="nominal" name="nominal" autocomplete="off" required="">
          </div>

          <p class="min-max-notes">
            Min Deposit <span class="min-deposit-amounts" style="padding-right: 30px;"><b></b></span>
            Max Deposit <span class="max-deposit-amounts"><b></b></span>
          </p>
        </div>
      </div>

      <div class="row d-flex">
        <div class="col-md-3 col-xs-4  ">
          <div class="font-weight-bold">
            Keterangan
          </div>
        </div>
        <div class="col-md-9 col-xs-8 d-flex flex-wrap">
          <input type="text" class="form-control m-15" id="ref_no" maxlength="35" minlength="5" name="keterangan" placeholder="No. Referensi / Nama Pengirim">
        </div>
      </div>
      <div class="row d-flex">
        <div class="col-md-3 col-xs-4 ">
          <div class="font-weight-bold">
            Bukti Transfer
          </div>
        </div>
        <div class="col-md-9 col-xs-8 d-flex flex-wrap">
          <div class="file-drop-area file-drop-area-receipt m-15">
            <span class="btn btn-secondary " i18n="">Pilih File</span>
            <span class="file-msg">
              atau seret dan taruh file di sini                   </span>
            <input class="file-input" name="bukti_transfer" id="receipt" type="file">
          </div>
        </div>
      </div>

      <!--  only for curacao_lic (TODO: change $curacao_lic) -->
      <!--  only for curacao_lic-->

      <div class="row d-flex">
        <div class="col-md-12 d-flex flex-wrap">
          <label>
            <input type="checkbox" class="form-check-input" id="exampleCheck1" name="termcondition">
            Saya telah membaca dan menyetujui Syarat dan Ketentuan Promosi. Kami tidak menerima jenis setoran dalam bentuk cek. Semua jenis pembayaran dalam bentuk cek ke akun kami akan diabaikan. </label>
        </div>
      </div>
    </div>
    <!--- second Tab end----->
    <div class="row d-flex">
      <div class="col-md-3 col-xs-4  ">
      </div>
      <div class="col-md-9 col-xs-8 d-flex flex-wrap">
        <div class="m-15">
          <button type="button" class="btn btn-primary" id="backBtn" onclick="load_method_form()">Back</button>

          <button type="submit" class="btn btn-secondary" id="submitBtn">Deposit</button>
        </div>
      </div>
    </div>
  </div>
  <input type="hidden" id="stage_val">
</form>

<script>
    function load_method_form() {
        showLoadingImgFn();
        $.get('/account/load_methods_form',function(d) {
            $('.content-form').html(d);
            removeLoadingImgFn();
        }).fail(
            function(xhr, status, error){
                removeLoadingImgFn();
                sweetAlert(xhr.responseJSON? xhr.responseJSON.message : xhr.responseText);   
            }
        );
    }
    $(document).ready(function () {
        // load_method_form();
    })
</script>

<script>
  window.removeOptions = function ($select, $options) {
    window.setOriginalSelect($select);
    $options.remove();
  }

  window.restoreOptions = function ($select) {
    var ogHTML = $select.data("originalHTML");
    if (ogHTML != undefined) {
      $select.html(ogHTML);
    }
  }
  window.setBankUserOptions = function (method) {

    var $s = $('select#bank_user_id');
    window.restoreOptions($s);
    var $optsToRemove = $s.find('option').not('[data-method='+ method +']').not('[value=""]');
    if (method == 5) {
      $optsToRemove = $optsToRemove.not('[data-method='+ 7 +']');
    }
    window.removeOptions($s, $optsToRemove);

  }


  var secret_key = 'aa';
  var bank_min_amount = _min_amount = "10000";
  var bank_max_amount = _max_amount = "100000";
  var min_string = "The minimum deposit amount is";
  var max_string = "The maximum deposit amount is";
  var method = 5;
  var providerSettingID = "{{ $pID }}";
  var pID = "{{ $pID }}";
  var agent_code = '2M3HYAA';

  $(document).ready(function () {
    $('#user_identification-field').hide();
    $('#source-fund-field').hide();
    $('#source_fund').prop('disabled', true);
    $('#user_identification').prop('disabled', true);
    $('#source_fund').prop('disabled', true);

    window.setBankUserOptions(method);
    $('#bankInfo_de001').hide();
    $('#promoInfo_de001').hide();

    var onFirstLoad = true;
    function onChgDepositeMethod() {
      $('.deposit-form').hide();
      $('#deposit-form-'+ $(this).val()).show();
      $('select.bank_list').prop('disabled', true);
      $('select.bank_list').val('');
      $('#bank_name_'+ $(this).val()).prop('disabled', false);
      $('#bank_user_id').prop('disabled', false);

      if (method == 6) {
        $('#ref_no').attr('placeholder', 'No Ref /No Serial /No Pengirim');
      } else {
        $('#ref_no').attr('placeholder', 'No. Referensi / Nama Pengirim');
      }
      $('#bankList').html('');
      $('#bankInfo_de001').hide();

    }




    function checkDepositAmount() {
      var amt = parseInt($('#deposite_amount').val().replace(',', '')) || 0;
      if ($('#deposite_amount').hasClass('has-error') || !$('#max_depo_alert').val() || $('#max_depo_alert').val() == 0 || amt < parseInt($('#max_depo_alert').val())) {
        $('#user_identification-field').hide();
        $('#source-fund-field').hide();
        $('#source_fund').prop('disabled', true);
        $('#user_identification').prop('disabled', true);
        $('#source_fund').prop('disabled', true);
      } else {
        $('#user_identification-field').show();
        $('#source-fund-field').show();
        $('#user_identification').prop('disabled', false);
        $('#source_fund').prop('disabled', false);
      }
    }


    $('input[name=deposite_method]').change(onChgDepositeMethod);

    $('input[name=deposite_method][value="' + method+ '"]').each(onChgDepositeMethod);

    $('#deposite_amount').on('keyup', function(e) {
      $(this).val(formatNumberInput(e.target, ''));

    });

    $('#deposite_amount').on('blur', function(e) {
      $(this).val(formatNumberInput(e.target, 'blur'));

    });

    $('.bank_list').on('change', function () {

      var status = $(this).find("option:selected").data('status');
      var select_name = $(this).val();
      var position = $(this).find(":selected").index();
      $('#bankList').html('');
      $('#bankInfo_de001').hide();
      var type = $(this).data('type');
      var provider_Id = $(this).find(":selected").data('p_id');
      $('input[id=bank_to_provider]').val(provider_Id);

      bank_max_amount = _max_amount;
      bank_min_amount = _min_amount;
      $('.min_deposit').val(_min_amount);
      $('.max_deposit').val(_max_amount);
      var _self = this;

      function onSelBankIsNotEmpty() {
        $('#bankInfo_de001').fadeIn();
        var _bank_min = $('#bank_min_deposit').val();
        var _bank_max = $('#bank_max_deposit').val();
        bank_min_amount = parseInt(_bank_min);
        bank_max_amount = parseInt(_bank_max);
        $('.min-deposit-amount').html('<b>' + window.commaSeparateNumber(bank_min_amount) + '</b>');
        $('.max-deposit-amount').html('<b>' + window.commaSeparateNumber(bank_max_amount) + '</b>');
        var o = {
          msg: ''
        };
        var cal_min_amount = getMinDepoWithPromo(bank_min_amount, o);
        var msgMin = o.msg;

        adddepositAmtRules(cal_min_amount, bank_max_amount, msgMin);
      }
      function onSelBankIsEmpty() {
        var o = {
          msg: ''
        };
        var cal_min_amount = getMinDepoWithPromo(bank_min_amount, o);
        var msgMin = o.msg;
        adddepositAmtRules(cal_min_amount, bank_max_amount, msgMin);
      }


      function showSelectedData(selectedOption) {

        var selectedData = getDataBasedOnOption(selectedOption);


        $('#bankList2').html(selectedData).fadeIn();
      }


      function getDataBasedOnOption(option) {
        var token = $("input[name='_token']").val();

        $.ajax({
          url: '/deposit-bank-details',
          type: 'POST',
          data: {
            select_name: option,
            _token: token,
            type: type,
            provider_id: provider_Id
          },
          success: function (response) {

            var htmlData = formatBankDetails(response);
            $('#bankList2').html(htmlData);
          },
          error: function (xhr, status, error) {
            console.error(error);
          }
        });
      }


      function formatBankDetails(bankDetails) {
        var html = '';
        html += '<div class="col-md-3">';
        html += '<div class="qrcode"></div>';
        html += '</div>';
        html += '<div class="col-xs-12 col-md-9">';
        html += '<div class="bankInfo-box" id="bankInfo_de001">';
        html += '<div class="box-title">';
        html += '<i class="icon-invoice i-invoice"></i>';
        html += 'Rincian Deposit Akun';
        html += '<div class="pull-right acc_status">';
        html += 'STATUS : <span class="text-success">ONLINE</span>';
        html += '</div>';
        html += '<input type="hidden" id="depo_acc_status" value="ONLINE">';
        html += '</div>';

        html += '<table class="table table-borderless text-right info-box--001">';
        html += '<tbody>';
        html += '<tr class="text-left first">';
        html += '<td class="col-xs-12 col-md-6" colspan="2">';
        if (bankDetails[0].qr_status == 1) {
          html += '<img src="' + bankDetails[0].image_qr_url + '" alt="" style="display:block; margin:auto; height: 200px;">';
        } else {}
        html += '<small>Nama Akun bank</small>';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="">';
        html += '<td class="col-xs-12 col-md-6" colspan="2">';
        html += '<input id="plIh33EE" value="' + bankDetails[0].nama_penerima + '" class="copy-input">';
        html += '<a href="javascript:void(0);" data-sel="plIh33EE" class="btn btn-link btn-copy lbl">';
        html += '<span class="">' + bankDetails[0].nama_penerima + '</span>';
        html += '<i class="icon-copy"></i>';
        html += '</a>';
        html += '<div class="btn btn-link btn-copy lbl" style="display: none;"></div>';
        html += '<div class="btn btn-link btn-copy lbl" style="display: none;"></div>';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="text-left first">';
        html += '<td class="col-xs-12 col-md-6" colspan="2">';
        html += '<small>Rekening Bank No</small>';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="">';
        html += '<td class="col-xs-12 col-md-6" colspan="2" style="padding-bottom: 10px;">';
        html += '<input id="zJZvyLqGGt" value="' + bankDetails[0].no_rek + '" class="copy-input">';
        html += '<a href="javascript:void(0);" data-sel="zJZvyLqGGt" class="btn btn-link btn-copy lbl">';
        html += '<span class="" style="white-space: normal; word-break: break-word;">' + bankDetails[0].no_rek + '</span>';
        html += '<i class="icon-copy"></i>';
        html += '</a>';
        html += '<div class="btn btn-link btn-copy lbl" style="display: none;"></div>';
        html += '<div class="btn btn-link btn-copy lbl" style="display: none;"></div>';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="text-left tr_type2">';
        html += '<td class="col-xs-6 col-md-6"><small>Min Deposit</small></td>';
        html += '<td class="col-xs-6 col-md-6 text-right">';
        html += '<span class="lbl">IDR' + parseFloat(bankDetails[0].min_deposit).toLocaleString('en-US', {
          minimumFractionDigits: 2
        }) + '</span>';
        html += '<input type="hidden" id="bank_min_deposit" class="min_deposit" value="' + bankDetails[0].min_deposit + '">';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="text-left tr_type2">';
        html += '<td class="col-xs-6 col-md-6"><small i18n="">Max Deposit</small></td>';
        html += '<td class="col-xs-6 col-md-6 text-right">';
        html += '<span class="lbl">IDR' + parseFloat(bankDetails[0].max_deposit).toLocaleString('en-US', {
          minimumFractionDigits: 2
        }) + '</span>';
        html += '<input type="hidden" id="bank_max_deposit" class="max_deposit" value="' + bankDetails[0].max_deposit + '">';
        html += '</td>';
        html += '</tr>';
        html += '<tr class="text-left tr_type2">';
        html += '<td class="col-xs-6 col-md-6"><small i18n="">Komisi Bank / Transaksi</small></td>';
        html += '<td class="col-xs-6 col-md-6 text-right">';
        html += '<span class="lbl">IDR 0.00</span>';
        html += '</td>';
        html += '</tr>';
        html += '<input type="hidden" id="admin_fee" value="IDR 0.00">';
        html += '<input type="hidden" id="percent_check" value="">';
        html += '<tr class="text-left tr_type2">';
        html += '<td class="col-xs-6 col-md-6"><small i18n="">Subsidi Bank / Transaksi</small></td>';
        html += '<td class="col-xs-6 col-md-6 text-right">';
        html += '<span class="lbl">IDR 0</span>';
        html += '</td>';
        html += '</tr>';
        html += '<input type="hidden" id="subsidi" value="IDR 0">';
        html += '</tbody>';
        html += '</table>';
        html += '</div>';

        return $(html).hide().fadeIn();
      }


      $('select.bank_list2').on('change', function () {
        var selectedOption = $(this).val();

        showSelectedData(selectedOption);

      });

      if (!!select_name) {
        showSelectedData();
      } else {
        onSelBankIsEmpty();

      }



      return false;

    });


    $('#btn_add_ubank__depo').click(function(e) {

      // $(this).prop('disabled',  true);
      $('#regbank_popup__depo').html('');
      $('#regbank_popup__depo').load('/regaccform?type=' + method, function() {
        $('#regbank_popup__depo').nifty("show");
        if (method == 5) {
          window.bindBankRegFormVal('#bank_register_popup');
        } else {
          window.bindNewFundRegFormVal("#pulsa_register_form");
        }

      });
    });


    function getMinDepoWithPromo(bank_min, msgMin) {
      msgMin.msg = min_string;
      bank_min = bank_min? bank_min: _min_amount;
      var selPromoInd = $('.promoList').find(":selected").index();
      var hasSelPromo = !!selPromoInd || !!$('#promo_code').val();
      if (!hasSelPromo) {
        return bank_min;
      } else {

        promo_min_amount = parseInt($('#promo_min_amount').val());

        if (!!promo_min_amount) {

          if (promo_min_amount > bank_min) {
            msgMin.msg = "Persyaratan minimal deposit untuk promo adalah  ";

            return promo_min_amount;
          }
        }

      }

      return bank_min;
    }
    $('select[data-plugin="bank_list"][data-type="'+ method + '"]').prop('disabled', false).val(providerSettingID).trigger('change');
    $('select[data-plugin="bank_list"][data-type="'+ method + '"]').find('option').each(function(index, element) {
      let provider_id = $(element).data('p_id');
      let provider_setting_id = element.value;
      if (provider_id == pID && provider_setting_id == providerSettingID) {
        $(element).prop('selected', 'selected').trigger('change');
      }

    });
    onFirstLoad = false;
    $('.promoList').on('change',
      function () {
        var promo_id = $(this).val();

        $('#promoList').html('');
        $('#promoInfo_de001').hide();

        if (promo_id == 0) {
          // Handle when no promo selected
        } else {
          $('input[name="promo_code"]').val('');
          $('input[name="promo_code"]').prop('disabled', true);

          function cbPromoList(r) {
            if (r.status) {
              $('input[name="pcode_not_confirm"]').val('').prop('disabled', true);
              $('#btn_apply_pcode').prop('disabled', true);
            }
          }

          // Send AJAX request to get promo details
          getPromoNAddDepoRules(promo_id, cbPromoList);
        }
        return false;
      });



    function adddepositAmtRules(intMin,
      intMax,
      msgMin) {
      $("#deposite_amount").rules("remove",
        "min max");
      $("#deposite_amount").rules("add",
        {
          min: intMin,
          max: intMax,

          messages: {
            min: msgMin + window.currencyCode + window.commaSeparateNumber(intMin),
            max: "Jumlah deposit maksimum adalah" + window.currencyCode + window.commaSeparateNumber(intMax),
          }
        });
    }



    $('#btn_add_promo').click(function() {
      $('#f_grp_promo_code').fadeIn();
      var v = $('#promo_event').val();
      if (!!v && v != 0) {
        $('#pcode_not_confirm').prop('disabled', true);
      } else {
        $('#pcode_not_confirm').prop('disabled', false);
      }
      $(this).parent().hide();
      return false;
    });
    var btn_click = false;
    $('#btn_apply_pcode').click(function(e) {
      if (btn_click == true) {
        return;
      }
      btn_click = true;
      e.preventDefault();
      $(this).prop('disabled', true);

      function cbPromoCode(r) {
        if (r.status) {

          $('#promo_event').val(0).prop('disabled', true);
          $('input[name="promo_code"]').prop('disabled', false).val($('input[name="pcode_not_confirm"]').val());
          $('input[name="pcode_not_confirm"]').prop('disabled', true); //when pcode correct , user shud click clear btn
          $('#btn_apply_pcode').hide();
          $('#btn_clear_pcode').show();
          depoValidator.showErrors({
            "promo_code": null
          });
        } else {
          depoValidator.showErrors({
            "promo_code": r.msg
          });
        }

        setTimeout(function() {
          $('#btn_apply_pcode').prop('disabled', false).blur().focusout();
          btn_click = false;
        }, 2000);
      }

      var v = $('#pcode_not_confirm').val();
      var r = {
        'status': true,
        'msg': ''
      };
      if (!v || (v && v.length < 2)) {
        r.status = false;
        r.msg = "Kode promo tidak boleh lebih dari 8 karakter";
      } else if (!v || (v && v.length > 15)) {
        r.status = false;
        r.msg = "Kode promo tidak boleh lebih dari 15 karakter";
      } else {
        r = getPromoNAddDepoRules(v, cbPromoCode, "/promo_details", true);
        return false;
      }

      cbPromoCode(r);

      return false;
    });


    $(document).on('click',
      '#btn_clear_pcode, #btn-clear-all-promo',
      function() {
        $('input[name="promo_code"]').prop('disabled', false).val('');
        $('input[name="pcode_not_confirm"]').prop('disabled', false).val('');
        $('#promo_event').prop('disabled', false).val(0);
        $('#btn_apply_pcode').prop('disabled', false);
        $('#btn_clear_pcode').hide();
        $('#btn_apply_pcode').show();
        $("#promoList").html('');
        $('#promoInfo_de001').hide();
        var msgMin = min_string;
        adddepositAmtRules(bank_min_amount, bank_max_amount, msgMin);
        return false;
      }
    );


    fileUploadReceipt('.file-drop-area-receipt');
    fileUploadReceipt('.file-drop-area-user_identification');

    function fileUploadReceipt(className) {
      var droppedFiles = false;
      $(className).on('drag dragstart dragend dragover dragenter dragleave drop',
        function(e) {
          e.preventDefault();
          e.stopPropagation();
        })
      .on('dragover dragenter',
        function() {
          $(this).addClass('is-dragover');
        })
      .on('dragleave dragend drop',
        function() {
          $(this).removeClass('is-dragover');
        })
      .on('drop',
        function(e) {
          droppedFiles = e.originalEvent.dataTransfer.files;
          $(this).find('input[type="file"]').prop('files', droppedFiles);

          if (droppedFiles) {
            $(this).find('.file-msg').html(droppedFiles[0].name);
          } else {

            $(this).find('.file-msg').html('   or drag and drop file here');
          }
        });

      $(className+' input[type="file"]').on('change',
        function(e) {
          var file = e.target.files;
          if (file) {
            var fileName = file[0]?file[0].name: '   or drag and drop file here';

            $(className+' .file-msg').html(fileName);
          } else {
            $(className+' .file-msg').html('   or drag and drop file here');
          }
        })
    }


    $('#btn_clear_pcode').click(function() {
      $('#promoList').html('');
    });


    var depoValidator = $("#depositForm").validate({
      // Specify validation rules
      ignore: ".ignore",
      rules: {
        nominal: {
          required: true,
          number: true,
        },
        bank_name: {
          required: true
        },
        destination_account: {
          required: true
        },
        bank_user_id: {
          required: true,
        },
        deposite_method: {
          required: true
        },
        // promo_event: {
        //     required:true
        // },
        promo_code: {
          minlength: 2,
          maxlength: 15,
          validatePromoCode: true
        },
        termcondition: {
          required: true
        },
        receipt: {
          extension: 'jpeg|jpg|png|bmp',
        },
        ref_no: {
          pattern: /^[a-zA-Z0-9, .\/\\\-]+$/,
          maxlength: 35,
          minlength: 5,
        }
      },

      messages: {
        nominal: {
          required: "Jumlah deposit tidak boleh kosong",
          number: "Jumlah deposit harus berupa angka",
        },
        bank_name: {
          required: " tidak boleh kosong",
        },
        destination_account: {
          required: " tidak boleh kosong",
        },
        bank_user_id: {
          required: " tidak boleh kosong",
          remote: "Please Select Valid Bank"
        },
        deposite_method: {
          required: " tidak boleh kosong",
        },
        promo_event: {
          required: "Metode Promosi diperlukan. Silakan pilih Metode Promosi.",
        },
        termcondition: {
          required: "Syarat dan ketentuan diperlukan",
        },
        receipt: {
          extension: "File yang dipilih tidak valid",
        },
        ref_no: {
          pattern: "Hanya huruf, angka, koma, spasi, dan - / \\ ",
          maxlength: "Maksimal 20 karakter saja",
          minlength: "Diperlukan minimal 5 karakter",
          required: " tidak boleh kosong",
        },
        min_deposit: "Jumlah deposit harus lebih besar dari minimal deposit (:minDeposit)",
        max_deposit: "Jumlah deposit melebihi maksimal deposit (:maxDeposit)"
      },

      errorElement: "em",
      errorPlacement: function(error, element) {
        error.addClass("help-block mlr-15");
        element.addClass("has-feedback");
        if (element.prop("type") === "checkbox") {
          error.insertAfter(element.parent("label"));
        } else {
          error.insertAfter(element);
        }
        if (!element.next("i")[0]) {
          $("<i class='icon-cancel form-control-feedback absolute m-15'></i>").insertAfter(element);
        }
      },
      success: function(label, element) {
        if (!$(element).next("i")[0]) {
          $("<i class='icon-checkmark  form-control-feedback absolute m-15'></i>").insertAfter($(element));
        }
      },
      highlight: function(element, errorClass, validClass) {
        $(element).addClass("has-error").removeClass("has-success");
        $(element).next("i").addClass("icon-cancel").removeClass("icon-checkmark");
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).addClass("has-success").removeClass("has-error");
        $(element).next("i").addClass("icon-checkmark").removeClass("icon-cancel");
      },

     submitHandler: function (form) {
    console.log($(form).serialize());

    function cbSubmit() {
        const $btn = $(form).find('button[type="submit"]');
        $btn.prop('disabled', true);

        window.ajax_submit(form)
            .done(function (d) {

                // ✅ CEK RESPONSE YANG BENAR
                if (d.success === true) {

                    // reset form
                    form.reset();
                    $('.info-lst').hide();
                    $('.bankInfo-box').html('');
                    $('.file-drop-area .file-msg')
                        .html('or drag and drop file here');

                    $(form).validate().resetForm();

                    // 🔔 ALERT SUKSES (INI YANG SEKARANG PASTI MUNCUL)
                    sweetAlert(
                        d.message || 'Deposit berhasil dikirim',
                        'success',
                        transMsgs.success
                    ).then(function () {

                        if (d.redirectUrl) {
                            location.href = d.redirectUrl;
                        } else {
                            location.reload();
                        }

                    });

                } else {
                    // ❌ backend kirim success:false
                    sweetAlert(
                        d.message || 'Terjadi kesalahan',
                        'error',
                        'Gagal'
                    );
                    $btn.prop('disabled', false);
                }

            })
            .fail(function (xhr) {

                let msg = 'Terjadi kesalahan';

                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }

                sweetAlert(msg, 'error', 'Error');
                $btn.prop('disabled', false);
            });
    }

    // 🔒 PROMO CONFIRM LOGIC (TIDAK DIUBAH)
    if (
        !!$('#pcode_not_confirm').val() &&
        !$('#promo_code').val() &&
        (!$('#promo_event').val() || $('#promo_event').val() == 0)
    ) {
        sweetAlert(
            transMsgs.pCodeConfirm,
            'warning',
            'Warning',
            true
        ).then(function (isConfirm) {
            if (isConfirm) {
                cbSubmit();
            }
        });
    } else {
        cbSubmit();
    }

    return false; // ⛔ stop submit normal
      }
    });




  });
</script>