@extends('layouts.member')
@section('css')
    <style>
        a {
            color: #000000;
        }

        .payment ul {
            margin: 0;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
        }

        .payment ul li {
            list-style: none;
            margin: 0 3px 3px 0;
            border: 1px solid #ccc;
            border-radius: 2px;
        }
    </style>
@endsection
@section('content')
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>Balance</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#">Home</a></li>
                            <li class="breadcrumb-item active">Balance</li>
                        </ol>
                    </div>
                </div>
            </div><!-- /.container-fluid -->
        </section>

        <!-- Main content -->
        <section class="content">
            <!-- Default box -->
            @foreach ($information as $item)
                <div class="alert alert-{{ $item->category }} alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    {{ $item->name }} {{ $item->description }}
                </div>
            @endforeach
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-sm-12">
                            <h5>Your Balance : <strong>{{ $balance }}</strong></h5>
                            <hr />
                        </div>
                        <div class="col-sm-12">
                            <form id="dataForm" method="POST" action="" class="form-horizontal">
                                @csrf
                                <div class="row">
                                    <div class="col-sm-3">
                                        <div class="form-group">
                                            <label for="amount" class="control-label">Payment</label>
                                            <select class="form-control" name="payment_channel" id="payment_channel"
                                                required>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-sm-3">
                                        <div class="form-group">
                                            <label for="amount" class="control-label">Amount</label>
                                            <div class="input-group mb-3">
                                                <input type="text" class="form-control price" id="amount"
                                                    name="amount" placeholder="Enter Amount" required>
                                                <div class="input-group-prepend">
                                                    <button type="button" class="btn btn-danger btn-clear"
                                                        data-target="#amount"><i class="fa fa-trash"></i></button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-3">
                                        <div class="form-group">
                                            <label for="discount_code" class="control-label">Discount Code</label>
                                            <div class="input-group mb-3">
                                                <input type="text" class="form-control" id="discount_code"
                                                    name="discount_code" placeholder="Enter Discount Code">
                                                <div class="input-group-prepend">
                                                    <button type="button" class="btn btn-danger btn-clear"
                                                        data-target="#discount_code"><i class="fa fa-trash"></i></button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label for="" class="control-label">&nbsp;</label>
                                            <button type="submit" class="btn btn-success btn-block" id="btnPayNow">Pay
                                                Now</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="col-sm-12">
                            <small>🚨 Minimum Topup: <strong>IDR
                                    {{ number_format($setting->min_amount, 0, '.', ',') }}</strong></small><br />
                            <small>🚨 Payment Expired : <strong>{{ $setting->payment_expired / 60 }}
                                    Hours</strong></small><br />
                            <hr>
                            <h5>📢 Perhatian!!!</h5>
                            <ol class="pl-2 ml-2">
                                <li>
                                    Kosongkan kolom <strong>Discount Code</strong> jika Anda tidak memiliki kode tersebut.
                                </li>
                                <li>
                                    E-Wallet yang didukung meliputi OVO, Dana, GoPay, LinkAja, BCA Mobile, ShopeePay, dan
                                    lainnya yang mendukung QRIS.
                                </li>
                                <li>
                                    Untuk pengguna ponsel, gambar QRIS dapat diunduh atau diambil tangkapan layarnya.
                                    Kemudian, buka aplikasi yang mendukung scan Qris dan lakukan pemindaian menggunakan file
                                    gambar tersebut.
                                </li>
                                <li>
                                    Harap selesaikan pembayaran dalam waktu 3 jam (lebih cepat lebih baik). Pastikan
                                    membayar sesuai dengan nominal yang tercantum, termasuk biaya administrasi. Jika
                                    pembayaran tidak diselesaikan dalam waktu 3 jam, transaksi akan dianggap kedaluwarsa.
                                    Silakan lakukan top-up ulang untuk melanjutkan.
                                </li>
                                <li>
                                    Untuk pilihan channel Gateway Alfamart atau Indomaret, Pelanggan akan dikenakan biaya
                                    admin.
                                </li>
                            </ol>
                        </div>
                        <div class="col-sm-12">
                            <hr />
                            <h5>Support Payment Gateway</h5>
                            <div class="payment my-3">
                                <ul id="payment_channel_list">
                                </ul>
                                <div style="clear: left"></div>
                            </div>
                            <hr />
                        </div>
                        <div class="col-sm-12">
                            <h5>Top Up History</h5>
                        </div>
                        <div class="col-sm-12">
                            <div class="table-responsive">
                                <table id="table1" class="table table-sm w-100">
                                    <thead>
                                        <tr>
                                            <th class="text-center">No</th>
                                            <th class="text-center">Request Date</th>
                                            <th class="text-center">Amount</th>
                                            <th class="text-center">Payment Type</th>
                                            <th class="text-center">Discount</th>
                                            <th class="text-center">Status</th>
                                            <th class="text-center">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.card-body -->
            </div>
            <!-- /.card -->

        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
@endsection
@section('js')
    <script>
        $(function() {
            var table = $('#table1').DataTable({
                responsive: true,
                processing: true,
                serverSide: true,
                ajax: "{{ route('member.balance.history') }}",
                order: [
                    [1, 'desc']
                ],
                columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        orderable: false,
                        searchable: false,
                        className: 'text-center'
                    },
                    {
                        data: 'created_at',
                        name: 'created_at',
                        className: 'text-center'
                    },
                    {
                        data: 'amount_topup',
                        name: 'amount_topup',
                        className: 'text-right',
                        render: function(data, type, row) {
                            return new Intl.NumberFormat('en-US', {
                                minimumFractionDigits: 0,
                                maximumFractionDigits: 0
                            }).format(data);
                        }
                    },
                    {
                        data: 'payment_name',
                        name: 'payment_name',
                        className: 'text-center'
                    },
                    {
                        data: 'discount_amount',
                        name: 'discounts.amount',
                        className: 'text-center'
                    },
                    {
                        data: 'status',
                        name: 'status',
                        className: 'text-center'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false,
                        className: 'text-center'
                    },
                ]
            });
            $.ajax({
                type: "GET",
                url: "{{ route('payment.channel') }}",
                dataType: "JSON"
            }).done(function(result) {
                $("#payment_channel").empty();
                $("#payment_channel_list").empty();
                $("#payment_channel").append(new Option('-- Select Payment Channel --', ''));
                $.each(result.response, function(key, value) {
                    $("#payment_channel_list").append(`
                        <li><img src="${value.icon_url}" class="img-fluid p-1"
                                height="32px" width="50" alt="${value.name} - Payment LingVPN"
                                title="${value.name} - Payment LingVPN">
                        </li>`);
                    $("#payment_channel").append(
                        `<option value="${value.code}" data-min="${value.minimum_amount}"  data-max="${value.maximum_amount}" data-fee="${value.fee_customer.flat}" data-percent="${value.fee_customer.percent}">${value.name}</option>`
                    );
                })
            });

            $('form#dataForm').submit(async function(e) {
                e.preventDefault();
                var formData = new FormData(this);
                var min_amount = '{{ $setting->min_amount }}';
                var amount = $('#amount').val().replace(/,/g, '');
                if (parseInt(amount) < parseInt(min_amount)) {
                    toastr.error('Minimum Topup is IDR ' + formatAmount(min_amount));
                    return false;
                }
                $('#btnPayNow').html('Wait...');
                $('#btnPayNow').attr('disabled', true);
                let fee = $(this).find(':selected').data('fee');
                let percent = $(this).find(':selected').data('percent');
                let fee_percent = fee + ((parseInt(amount) * percent) / 100);
                let total = parseInt(amount) + parseInt(fee_percent);
                let discount_info = '-';
                let isError = false;
                if ($('#discount_code').val() != '') {
                    await $.ajax({
                        type: 'GET',
                        url: "{{ route('payment.discount', '') }}/" + $('#discount_code').val(),
                        dataType: "JSON",
                        success: (res) => {
                            let item = res.response;
                            if (item) {
                                total = parseInt(amount) - item.amount;
                                fee_percent = fee + ((parseInt(total) * percent) /
                                    100);
                                total = parseInt(total) + parseInt(fee_percent);
                                discount_info =
                                    `IDR ${formatAmount(item.amount)} [${item.code}-${item.name}]`;
                                if (item.amount_min > amount) {
                                    toastr.error('Minimum Topup for this discount is IDR ' +
                                        formatAmount(item.amount_min));
                                    $('#btnPayNow').html('Pay Now');
                                    $('#btnPayNow').removeAttr('disabled');
                                    isError = true;
                                }
                            }
                        },
                        error: function(err) {
                            toastr.error(err.responseJSON.metadata.message);
                            isError = true;
                            $('#btnPayNow').html('Pay Now');
                            $('#btnPayNow').removeAttr('disabled');
                            isError = true;
                        }
                    });
                }
                if (isError) {
                    return false;
                }
                await Swal.fire({
                    html: `
                        <div>
                            <h5>Confirmation Payment</h5>
                            <table class="table table-sm text-sm">
                                <tr>
                                    <td class="text-left">Payment</td>
                                    <td>:</td>
                                    <td>${$('#payment_channel option:selected').text()}</td>
                                </tr>
                                <tr>
                                    <td class="text-left">Amount</td>
                                    <td>:</td>
                                    <td class="text-right">IDR ${formatAmount(amount)}</td>
                                </tr>
                                <tr>
                                    <td class="text-left">Discount</td>
                                    <td>:</td>
                                    <td class="text-right">${discount_info}</td>
                                </tr>
                                <tr>
                                    <td class="text-left">Fee</td>
                                    <td>:</td>
                                    <td class="text-right">IDR ${formatAmount(fee_percent)}</td>
                                </tr>
                                <tr>
                                    <td class="text-left">Total</td>
                                    <td>:</td>
                                    <td class="text-right">IDR ${formatAmount(total)}</td>
                                </tr>
                                <tr>
                                    <td colspan="3">By clicking "Pay Now" you agree to the <a href="{{ route('term-of-service') }}" target="_blank">Terms and Conditions</a> of LingVPN</td>
                                </tr>
                                </table>
                        </div>
                    `,
                    showCancelButton: true,
                    confirmButtonText: "Pay Now",
                    cancelButtonText: "Back",
                    confirmButtonColor: "#28a745",
                    cancelButtonColor: "#d33",
                }).then((result) => {
                    if (result.isConfirmed) {
                        Swal.fire({
                            html: `
                        <div>
                            <div class="swal2-loading-icon"></div>
                            <h3>Please wait...</h3>
                        </div>
                    `,
                            showConfirmButton: false,
                            allowOutsideClick: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        setTimeout(() => {
                            $.ajax({
                                type: 'POST',
                                url: "{{ route('member.balance-topup') }}",
                                data: formData,
                                contentType: false,
                                processData: false,
                                success: (res) => {
                                    Swal.close();
                                    $('#btnPayNow').html('Pay Now');
                                    $('#btnPayNow').removeAttr(
                                        'disabled');
                                    $('#dataForm').trigger("reset");
                                    table.draw();
                                    window.open(res.response,
                                        '_blank');
                                },
                                error: function(err) {
                                    Swal.close();
                                    $('#btnPayNow').html('Pay Now');
                                    $('#btnPayNow').removeAttr(
                                        'disabled');
                                    toastr.error(err.responseJSON
                                        .metadata.message);
                                }
                            });
                        }, 3000);
                    } else {
                        $('#btnPayNow').html('Pay Now');
                        $('#btnPayNow').removeAttr('disabled');
                    }
                });
            });

            $(document).off('click', '.btn-clear').on('click', '.btn-clear', function() {
                let target = $(this).data('target');
                $(target).val('');
            });
        });
    </script>
@endsection
