@extends('Template::layouts.master')
@section('content')
    <form action="{{ route('user.deposit.insert') }}" method="post" class="deposit-form">
        @csrf
        <input type="hidden" name="currency">
        <div class="gateway-card">
            <div class="row justify-content-center gy-sm-4 gy-3">
                <div class="col-lg-6">
                    <div class="payment-system-list is-scrollable gateway-option-list">
                        @if (gs('balance_payment'))
                            <label for="balance_payment" class="payment-item fw-bold">
                                <div class="payment-item__info">
                                    <span class="payment-item__check"></span>
                                    <span class="payment-item__name">@lang('Balance - ') {{ showAmount(auth()->user()->balance) }}</span>
                                </div>
                                <input class="payment-item__radio gateway-input" id="balance_payment" value="balance_payment" hidden type="radio" name="gateway" data-balance = "{{ auth()->user()->balance }}">
                            </label>
                        @endif

                        @foreach ($gatewayCurrency as $data)
                            <label for="{{ titleToKey($data->name) }}" class="payment-item @if ($loop->index > 4) d-none @endif gateway-option">
                                <div class="payment-item__info">
                                    <span class="payment-item__check"></span>
                                    <span class="payment-item__name">{{ __($data->name) }}</span>
                                </div>
                                <div class="payment-item__thumb">
                                    <img class="payment-item__thumb-img" src="{{ getImage(getFilePath('gateway') . '/' . $data->method->image) }}" alt="@lang('payment-thumb')">
                                </div>
                                <input class="payment-item__radio gateway-input" id="{{ titleToKey($data->name) }}" hidden data-gateway='@php echo json_encode($data) @endphp' type="radio" name="gateway" value="{{ $data->method_code }}" @checked(old('gateway', $loop->first) == $data->method_code) data-min-amount="{{ showAmount($data->min_amount) }}" data-max-amount="{{ showAmount($data->max_amount) }}">
                            </label>
                        @endforeach

                        @if ($gatewayCurrency->count() > 4)
                            <button type="button" class="payment-item__btn more-gateway-option">
                                <p class="payment-item__btn-text">@lang('Show All Payment Options')</p>
                                <span class="payment-item__btn__icon"><i class="fas fa-chevron-down"></i></span>
                            </button>
                        @endif
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="payment-system-list p-3">
                        <div class="deposit-info">
                            <div class="deposit-info__title">
                                <p class="text mb-0">@lang('Amount')</p>
                            </div>
                            <div class="deposit-info__input">
                                <p class="text has-icon">{{ getAmount($amount) }}
                                    <span>{{ gs('cur_text') }}</span>
                                </p>
                            </div>
                        </div>
                        <input type="hidden" class="form-control form--control amount" name="amount" placeholder="@lang('00.00')" value="{{ getAmount($amount) }}" autocomplete="off">
                        <hr>

                        @if (gs('is_coupon'))
                            <div class="deposit-info">
                                <div class="deposit-info__title">
                                    <p class="text has-icon"> @lang('Discount')
                                        <span></span>
                                    </p>
                                </div>
                                <div class="deposit-info__input">
                                    <p class="text"><span class="discount">{{ getAmount(session('coupon')['couponAmount'] ?? 0) ?? '0.00' }}</span>
                                        <span>{{ gs('cur_text') }}</span>
                                    </p>
                                </div>
                            </div>
                            <div class="deposit-info">
                                <div class="deposit-info__title">
                                    <p class="text has-icon"> @lang('After Discount')
                                        <span></span>
                                    </p>
                                </div>
                                <div class="deposit-info__input">
                                    <p class="text has-icon"> <span class="after_discount">{{ session('coupon')['amount'] ?? getAmount($amount) }}</span>
                                        <span>{{ gs('cur_text') }}</span>
                                    </p>
                                </div>
                            </div>
                        @endif
                        <div class="process_wrap">
                            <div class="deposit-info">
                                <div class="deposit-info__title">
                                    <p class="text has-icon"> @lang('Limit')
                                        <span></span>
                                    </p>
                                </div>
                                <div class="deposit-info__input">
                                    <p class="text"><span class="gateway-limit">@lang('0.00')</span>
                                    </p>
                                </div>
                            </div>
                            <div class="deposit-info">
                                <div class="deposit-info__title">
                                    <p class="text has-icon">@lang('Processing Charge')
                                        <span data-bs-toggle="tooltip" title="@lang('Processing charge for payment gateways')" class="proccessing-fee-info"><i class="las la-info-circle"></i> </span>
                                    </p>
                                </div>
                                <div class="deposit-info__input">
                                    <p class="text"><span class="processing-fee">@lang('0.00')</span>
                                        {{ __(gs('cur_text')) }}
                                    </p>
                                </div>
                            </div>

                        </div>

                        <div class="deposit-info total-amount pt-3">
                            <div class="deposit-info__title">
                                <p class="text">@lang('Total')</p>
                            </div>
                            <div class="deposit-info__input">
                                <p class="text"><span class="final-amount">@lang('0.00')</span>
                                    {{ __(gs('cur_text')) }}</p>
                            </div>
                        </div>

                        <div class="deposit-info gateway-conversion d-none total-amount pt-2">
                            <div class="deposit-info__title">
                                <p class="text">@lang('Conversion')
                                </p>
                            </div>
                            <div class="deposit-info__input">
                                <p class="text"></p>
                            </div>
                        </div>
                        <div class="deposit-info conversion-currency d-none total-amount pt-2">
                            <div class="deposit-info__title">
                                <p class="text">
                                    @lang('In') <span class="gateway-currency"></span>
                                </p>
                            </div>
                            <div class="deposit-info__input">
                                <p class="text">
                                    <span class="in-currency"></span>
                                </p>

                            </div>
                        </div>
                        <div class="d-none crypto-message mb-3">
                            @lang('Conversion with') <span class="gateway-currency"></span> @lang('and final value will Show on next step')
                        </div>

                        @if (gs('is_coupon'))
                            <div class="coupon_wrap pb-3">
                                <div class="input-group">
                                    <input type="text" name="coupon_code" class="form--control form-control coupon" value="{{ session('coupon')['code'] ?? '' }}" placeholder="@lang('Enter Coupon Code')" @disabled(session()->has('coupon'))>
                                    <button id="applyCoupon" class="input-group-text border-0 btn btn--base " type="button" @disabled(session()->has('coupon'))>
                                        @lang('Apply')
                                    </button>
                                </div>
                                @if (session()->has('coupon'))
                                    <div class="text-end mt-1">
                                        <a href="javascript:void(0)" type="button" class="text-danger text-bold remove-coupon"><i class="las la-times"></i>@lang('Remove Coupon')</a>
                                    </div>
                                @endif
                            </div>
                        @endif

                        <button type="submit" class="btn btn--base w-100" disabled>
                            @lang('Confirm Payment')
                        </button>
                        <div class="info-text pt-3">
                            <p class="text">@lang('Ensuring your funds grow safely through our secure deposit process with world-class payment options.')</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
@endsection

@push('script')
    <script>
        "use strict";
        (function($) {

            var couponAmount = `{{ session('coupon')['amount'] ?? null }}`;
            var amount = couponAmount ? parseFloat(couponAmount) : parseFloat($('.amount').val());

            var gateway, minAmount, maxAmount, charge = 0.00,
                mainAmount = `{{ $amount }}`,
                balancePayment = false;

            $('.amount').on('input', function(e) {
                amount = parseFloat($(this).val());
                if (!amount) {
                    amount = 0;
                }
                calculation();
            });

            $('.gateway-input').on('change', function(e) {
                gatewayChange();
            });

            function gatewayChange() {
                let gatewayElement = $('.gateway-input:checked');
                let methodCode = gatewayElement.val();

                if (methodCode == 'balance_payment') {
                    $('.process_wrap').addClass('d-none');
                    $('.final-amount').text(amount);

                    let balance = parseFloat($('#balance_payment').data('balance'));
                    if (balance < amount) {
                        $(".deposit-form button[type=submit]").attr('disabled', true);
                    }else{
                        $(".deposit-form button[type=submit]").removeAttr('disabled');
                    }

                    balancePayment = true;
                    return;
                } else {
                    $('.process_wrap').removeClass('d-none');
                    balancePayment = false;
                }

                gateway = gatewayElement.data('gateway');
                minAmount = gatewayElement.data('min-amount');
                maxAmount = gatewayElement.data('max-amount');

                let processingFeeInfo =
                    `${parseFloat(gateway.percent_charge).toFixed(2)}% with ${parseFloat(gateway.fixed_charge).toFixed(2)} {{ __(gs('cur_text')) }} charge for payment gateway processing fees`
                $(".proccessing-fee-info").attr("data-bs-original-title", processingFeeInfo);
                calculation();
            }

            gatewayChange();

            $(".more-gateway-option").on("click", function(e) {
                let paymentList = $(".gateway-option-list");
                paymentList.find(".gateway-option").removeClass("d-none");
                $(this).addClass('d-none');
                paymentList.animate({
                    scrollTop: (paymentList.height() - 60)
                }, 'slow');
            });

            function calculation() {
                if (!gateway) return;
                $(".gateway-limit").text(minAmount + " - " + maxAmount);

                let percentCharge = 0;
                let fixedCharge = 0;
                let totalPercentCharge = 0;

                if (amount) {
                    percentCharge = parseFloat(gateway.percent_charge);
                    fixedCharge = parseFloat(gateway.fixed_charge);

                }

                let totalCharge = parseFloat(totalPercentCharge + fixedCharge);

                charge = totalCharge;

                let totalAmount = parseFloat((amount || 0) + totalPercentCharge + fixedCharge);

                $(".final-amount").text(totalAmount.toFixed(2));
                $(".processing-fee").text(totalCharge.toFixed(2));
                $("input[name=currency]").val(gateway.currency);
                $(".gateway-currency").text(gateway.currency);

                if (amount < Number(gateway.min_amount) || amount > Number(gateway.max_amount)) {
                    $(".deposit-form button[type=submit]").attr('disabled', true);
                } else {
                    $(".deposit-form button[type=submit]").removeAttr('disabled');
                }

                if (gateway.currency != "{{ gs('cur_text') }}" && gateway.method.crypto != 1) {
                    $('.deposit-form').addClass('adjust-height')

                    $(".gateway-conversion, .conversion-currency").removeClass('d-none');
                    $(".gateway-conversion").find('.deposit-info__input .text').html(
                        `1 {{ __(gs('cur_text')) }} = <span class="rate">${parseFloat(gateway.rate).toFixed(2)}</span>  <span class="method_currency">${gateway.currency}</span>`
                    );
                    $('.in-currency').text(parseFloat(totalAmount * gateway.rate).toFixed(gateway.method.crypto == 1 ?
                        8 : 2))
                } else {
                    $(".gateway-conversion, .conversion-currency").addClass('d-none');
                    $('.deposit-form').removeClass('adjust-height')
                }

                if (gateway.method.crypto == 1) {
                    $('.crypto-message').removeClass('d-none');
                } else {
                    $('.crypto-message').addClass('d-none');
                }
            }

            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            })
            $('.gateway-input').change();


            const applyCouponClickHandler = () => {
                var code = $('input[name=coupon_code]').val();
                var subscriptionId = `{{ $subscription->id }}`;
                var gatewayCode = $('.gateway-input:checked').val();
                var currency = $('input[name=currency]').val();

                if (!code) {
                    notify('error', 'Coupon field is required');
                    return false;
                }

                const data = {
                    _token: `{{ csrf_token() }}`,
                    code: code
                }

                $.post("{{ route('user.deposit.coupon.apply') }}", data).done((response) => {
                    notify(response.status, response.message);
                    if (response.status == 'success') {
                        amount = parseFloat((response.payableAmount).toFixed(2));
                        $('.after_discount').text(response.payableAmount);
                        $('.discount').text(response.couponAmount);
                        $('#applyCoupon').attr('disabled', true);

                        let html = `
                            <div class="text-end mt-1">
                                <a href="javascript:void(0)" type="button" class="text-danger text-bold remove-coupon"><i class="las la-times"></i>@lang('Remove Coupon')</a>
                            </div>
                        `;
                        $('.coupon_wrap').append(html);
                        $('.coupon').attr('disabled', true);

                        if (balancePayment) {
                            $('.final-amount').text(amount);
                        } else {
                            calculation();
                        }
                    }
                });
            }

            const removeCoupon = () => {
                $.get("{{ route('user.deposit.coupon.remove') }}").done((response) => {
                    notify(response.status, response.message);
                    if (response.status == 'success') {
                        amount = parseFloat(mainAmount);
                        $('.discount').text(0);
                        $('.after_discount').text(mainAmount);
                        $('.remove-coupon').remove()
                        $('#applyCoupon').attr('disabled', false);
                        $('.coupon').attr('disabled', false);

                        if (balancePayment) {
                            $('.final-amount').text(amount);
                        } else {
                            calculation();
                        }
                    }
                });
            };

            $(document).on('click', ' #applyCoupon', applyCouponClickHandler);
            $(document).on('click', ' .remove-coupon', removeCoupon);
        })(jQuery);
    </script>
@endpush
