@extends('user.layouts.app')
@section('breadcrumb-first', $breadcrumb->first)
@section('breadcrumb-second', $breadcrumb->second)
@section('content')
<div class="row">
	<div class="col-lg-8">
		<div class="card card-custom grid-margin">
			<div class="card-body">
				<form method="post" action="{{ request()->url() }}" id="input_form">
                    @csrf
                    <input type="text" class="hidden" name="payment" id="payment">
                    <div class="form-group mb-3">
						<label>Metode <text class="text-danger">*</text></label>
						<select class="custom-select" name="deposit_method" id="deposit_method" data-toggle="select2">
							<option value="" selected>Pilih Metode...</option>
                            @foreach($deposit_payments as $payment)
                                <optgroup label="{{ $payment->payment }}">
                                    @php
                                    $methods = \App\Models\DepositMethod::where('payment', $payment->payment)->where([['type', '<>', 'Direct'], ['status', '1']])->get();
                                    @endphp
                                    @foreach($methods as $method)
                                        <option value="{{ $method->id }}">{{ $method->name }} ({{ $method->type }}) </option>
                                    @endforeach
                                </optgroup>
							@endforeach
						</select>
                        <small id="deposit_method"></small>
					</div>
                    <div class="form-group mb-3 hidden" id="phone-number">
                        <label>No. Pengirim <text class="text-danger">*</text></label>
                        <input type="number" class="form-control" name="phone_number" id="phone_number" value="{{ old('phone_number') ?? '' }}">
                        <small id="phone_number"></small>
                    </div>
                    <div class="row">
                        <div class="form-group col-lg-6 mb-3">
                            <label>Jumlah <text class="text-danger">*</text></label>
                            <input type="text" class="form-control autonumeric-currency" name="amount" id="amount" value="{{ old('amount') ?? 'Rp ' }}">
                            <small id="amount"></small>
                            <span id="min"></span>
                        </div>
                        <div class="form-group col-lg-6 mb-3">
                            <label>Saldo Didapat</label>
                            <input type="hidden" id="rate" value="0">
                            <span class="form-control autonumeric-currency" data-a-sign="Rp " data-a-sep="." data-a-dec="," id="balance">Rp</span>
                        </div>
                    </div>
                    <input type="hidden" id="rate" value="0">
                    <div class="button-items d-grid gap-2 hidden" id="process-button">
                        <button type="button" class="btn btn-primary btn-block waves-effect waves-light mt-0" disabled>Mohon Tunggu...</button>
                    </div>
                    <div class="row" id="main-button">
                        <div class="col-6">
                            <div class="button-items d-grid gap-2">
                                <button type="reset" class="btn btn-secondary btn-block waves-effect waves-light mt-0"><i class="mdi mdi-refresh"></i> Reset</button>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="button-items d-grid gap-2">
                                <button type="submit" class="btn btn-custom btn-block waves-effect waves-light mt-0"><i class="mdi mdi-send-outline"></i> Submit</button>
                            </div>
                        </div>
                    </div>
				</form>
			</div>
		</div>
	</div>
	<div class="col-lg-4">
		<div class="card card-custom grid-margin">
			<div class="card-body">
				{!! website_config('other')->deposit_info !!}
			</div>
		</div>
	</div>
</div>
<script src="{{ url('assets/js/snap.js') }}" data-client-key="{{ website_config('midtrans_payment')->client_key }}"></script>
<script type="text/javascript">
	$(document).ready(function() {
        $('#deposit_method').on('change', function() {
			var deposit_method = $('#deposit_method').val();
			$.ajax({
				type: "GET",
				url: "{{ url('ajax/deposit/method/detail') }}",
				data: "deposit_method="+ deposit_method,
				dataType: "json",
				success: function(response) {
					$('#min').html(response.data.min);
                    $('#rate').val(response.data.rate);
                    $('#payment').val(response.data.payment);
                    if (response.data.payment == 'Pulsa') {
                        $('#phone-number').removeClass('hidden');
                    } else {
                        $('#phone-number').addClass('hidden');
                    }
				}, error: function() {
                    swal.fire("Gagal!", "Terjadi kesalahan.", "error");
				}
			});
		});
        $("#input_form").on('submit', function(element) {
            element.preventDefault();
            $.ajax({
                url: $(this).attr('action'),
                method: $(this).attr('method'),
                data: new FormData(this),
                processData: false,
                dataType: 'json',
                contentType: false,
                beforeSend: function() {
                    $('#preloader').fadeIn("slow");
                    $('button:submit').attr('disabled', 'true');
                    $('#process-button').removeClass('hidden');
                    $('#main-button').addClass('hidden');
                    $(document).find('input, select').removeClass('is-invalid').removeClass('is-valid');
                },
                success: function(response) {
                    $('#preloader').fadeOut("slow");
                    $('button:submit').removeAttr('disabled');
                    $('#process-button').addClass('hidden');
                    $('#main-button').removeClass('hidden');
                    if (response.status == false) {
                        if (response.type == 'validation') {
                            $.each(response.message, function(key, value) {
                                $('input#'+key+', select#'+key+'').addClass('is-invalid');
                                $('small#'+key+'').addClass('invalid-feedback').html(value[0]);
                            });
                            showAlert('danger', 'Periksa Input', 3000);
                        } 
                        if (response.type == 'alert') {
                            showAlert(
                                response.hasOwnProperty('alert') ? response.alert : 'danger', 
                                response.message, 
                                response.hasOwnProperty('timeout') ? response.timeout : 5000
                            );
                        }
                        $("input, select").each(function() {
                            if (this.classList.contains('is-invalid') == false && this.name !== 'payment' && this.name !== 'type') {
                                this.classList.add('is-valid');
                            }
                        });
                    } else {
                        $('#input_form')[0].reset();
                        $('#min').html('');
                        if (response.is_midtrans == '1') {
                            snap_pay(response.snap_token);
                        } else {
                            modal('detail', 'Deposit', response.deposit_detail);
                            $('#modal').on('shown.bs.modal', function () {})
                        }
                    }
                },
                error:function(response) {
                    $('#preloader').fadeOut("slow");
                    $('button:submit').removeAttr('disabled');
                    $('#process-button').addClass('hidden');
                    $('#main-button').removeClass('hidden');
                    if (response.status == 429) {
                        var t;
                        Swal.fire({
                            title: "Gagal!", 
                            icon: "error",
                            html: "Coba lagi dalam <strong></strong> detik.",
                            timer: response.getResponseHeader('retry-after') * 1000,
                            onBeforeOpen: function () {
                                Swal.showLoading(), (t = setInterval(function () {
                                    Swal.getContent().querySelector("strong").textContent = (Swal.getTimerLeft() / 1000).toFixed();
                                }, 1000));
                            },
                            onClose: function () {
                                clearInterval(t);
                            },
                        }).then(function (t) {
                            t.dismiss === Swal.DismissReason.timer;
                        });
                    } else {
                        swal.fire("Gagal!", 'Terjadi Kesalahan', "error");
                    }
                },
            });
        });
		$("#amount").keyup(function() { 
			var amount = $('#amount').val(), rate = $('#rate').val()
			var total = (numeric(amount) * rate);
			$('#balance').html(total.toFixed(0)).autoNumeric('update');
		});
        function snap_pay(token) {
            snap.pay(token, {
                onSuccess: function(response){
                    console.log(response);
                },
                onPending: function(response){
                    console.log(response);
                },
                onError: function(response){
                    console.log(response);
                }
            });
        }
	});
</script>
@endsection