<div>
    <div class="row">
        <div class="col-md-12 mb-3">
            @if(!session()->has('coupon'))
                <p>{{__("Have a coupon?")}}</p>
                <form wire:submit.prevent="applyDiscount()">
                    <p class="checkout-coupon">
                        <input wire:model="couponCode" type="text" placeholder="{{__("Coupon code")}}" required/>
                        <button type="submit" class="btn btn-default">
                            {{__("Apply Coupon")}}
                        </button>
                    </p>
                </form>
            @endif
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-md-12 col-12">
            <h2 class="h5 text-uppercase mb-4">{{__("Shipping addresses")}}</h2>
            <div class="row">
                @forelse($addresses as $address)
                    <div class="col-6 form-group">
                        <div class="custom-control custom-radio">
                            <input
                                type="radio"
                                id="address-{{ $address->id }}"
                                class="custom-control-input"
                                wire:model="userAddressId"
                                wire:click="getShippingCompanies()"
                                {{ intval($userAddressId) == $address->id ? 'checked' : '' }}
                                value="{{ $address->id }}">

                            <label for="address-{{ $address->id }}" class="custom-control-label text-small">
                                <b>{{ $address->title }}</b>
                                <small>
                                    {{ $address->address }}<br>
                                    {{ $address->country->name }} - {{ $address->state->name }}- {{ $address->city->name }}
                                </small>
                            </label>
                        </div>
                    </div>
                @empty
                    <div class="col-6 form-group">
                        <p class="text-danger">{{__("No addresses found")}}</p>
                        <a class="btn btn-dark" href="{{ route('user.addresses') }}">
                            {{__("Add Your Address")}}
                        </a>
                    </div>
                @endforelse
            </div>

            @if($productsIsAvailable )

                 @if($userAddressId)
                <h2 class="h5 text-uppercase mb-4">{{__("Shipping options")}}</h2>
                <div class="row">
                    @forelse($shippingCompanies as $shippingCompany)
                        <div class="col-6 form-group">
                            <div class="custom-control custom-radio">
                                <input
                                    type="radio"
                                    id="shipping-company-{{ $shippingCompany->id }}"
                                    class="custom-control-input"
                                    wire:model="shippingCompanyId"
                                    wire:click="storeShippingCost()"
                                    {{ intval($shippingCompanyId) == $shippingCompany->id ? 'checked' : '' }}
                                    value="{{ $shippingCompany->id }}">
                                <label for="shipping-company-{{ $shippingCompany->id }}"
                                       class="custom-control-label text-small">
                                    <b>{{ $shippingCompany->name }}</b>
                                    <small>
                                        {{ $shippingCompany->description }} ({{ format_amount($shippingCompany->cost,true) }})
                                    </small>
                                </label>
                            </div>
                        </div>
                    @empty
                        <p>{{__("No shipping options found.")}}</p>
                    @endforelse
                </div>

                @if($paymentIsRequired)
                    @if($userAddressId && $shippingCompanyId)
                        <h2 class="h5 text-uppercase mb-4">{{__("Payment Method")}}</h2>
                        <div class="row">
                            @forelse($paymentMethods as $paymentMethod)
                                <div class="col-6 form-group">
                                    <div class="custom-control custom-radio">
                                        <input type="radio"
                                            id="payment-method-{{ $paymentMethod->id }}"
                                            class="custom-control-input"
                                            wire:model="paymentMethodId"
                                            wire:click="getPaymentMethod()"
                                            {{ intval($paymentMethodId) == $paymentMethod->id ? 'checked' : '' }}
                                            value="{{ $paymentMethod->id }}">
                                        <label for="payment-method-{{ $paymentMethod->id }}"
                                               class="custom-control-label text-small">
                                            <b>{{ $paymentMethod->name }}</b>
                                        </label>
                                    </div>
                                </div>
                                @if($loop->last and getSettingsOf("submit_order_with_payment_frontend"))

                                    <div class="col-6 form-group">
                                        <div class="custom-control custom-radio">
                                            <input type="radio"
                                                id="no-payment-method"
                                                class="custom-control-input"
                                                wire:model="paymentMethodId"
                                                wire:click="getPaymentMethod()"
                                                {{ intval($paymentMethodId) == -1 ? 'checked' : '' }}
                                                value="-1">
                                            <label for="no-payment-method"
                                                   class="custom-control-label text-small">
                                                <b>{{ __("No payment") }}</b>
                                            </label>
                                        </div>
                                    </div>
                                @endif
                            @empty
                                <p>{{__("No payment way found")}}</p>
                            @endforelse
                        </div>
                    @endif
                    @if( ($userAddressId && $shippingCompanyId && $paymentMethodId > 0))

{{--                        @if(in_array($paymentMethodCode,['mtn-momo-cmr','orange-momo-cmr']))--}}
                            <button type="button" class="btn btn-default btn-block uppercase button-box default-btn"
                                    wire:click="showPopupMakePayment"  >
                                {{__("Pay :amount With :method",["method" => $selectedPaymentMethod->name,"amount" => format_amount($netPayable,true)])}}
                            </button>
{{--                        @endif--}}
{{--                        @if(in_array($paymentMethodCode,['paypal-rest']))--}}
{{--                            <div class="col-lg-12">--}}
{{--                                <div id="paypal-button-container"></div>--}}
{{--                            </div>--}}
{{--                        @endif--}}

                    @endif

                    @if($paymentMethodId == -1)
                        <button type="button" class="btn btn-success btn-block uppercase"
                                wire:click="submitOrderWithoutPaymentMethod()"  >
                            {{__("Submit order without payment")}}
                        </button>
                    @endif
                @else
                    @if($shippingCompanyId)
                        <button type="button" class="btn btn-dark btn-block uppercase"
                                wire:click="submitOrder"  >
                            {{__("Send Order")}}
                        </button>
                    @endif
                @endif
            @endif

            @endif

        </div>
        <div class="col-lg-6 col-md-12 col-12">
            <div class="your-order">
                <h4 class="mx-5 text-white"><strong>{{__("Your order")}}</strong></h4>
                <div class="your-order-table table-responsive">
                    <table>
                        <tbody>
                        <tr>
                            <th class="product-name"><strong>{{__("Subtotal")}}</strong></th>
                            <th class="product-total">{{ format_amount($cartSubTotal,true) }}</th>
                        </tr>
                        @if(session()->has('coupon'))
                            <tr>
                                <th class="product-name">
                                    <strong>{{__("Discount")}}</strong>
                                    <small>({{ getNumbersOfCart()->get('discountCode') }})</small><br>
                                    <a wire:click.prevent="removeCoupon()"
                                          class="btn btn-link btn-sm text-decoration-none text-danger">
                                        <small>{{__("Remove coupon")}}</small>
                                    </a>
                                </th>
                                <th class="product-total">- {{ format_amount($cartDiscount,true) }}</th>
                            </tr>
                        @endif
                        @if(session()->has('shipping'))
                            <tr>
                                <th class="product-name">
                                    <strong>{{__("Shipping")}}</strong>
                                    <small>({{ getNumbersOfCart()->get('shippingCode') }})</small>
                                </th>
                                <th class="product-total">{{ format_amount($cartShipping,true) }}</th>
                            </tr>
                        @endif
                        <tr>
                            <th class="product-name"><strong>{{__("Tax")}}</strong></th>
                            <th class="product-total">{{ format_amount($cartTax,true) }}</th>
                        </tr>
                        @if(auth(activeGuard())->user()->balance > 0)
                            <tr>
                                <th class="product-name"><strong>{{__("Balance")}}</strong></th>
                                <th class="product-total">{{ format_amount(auth(activeGuard())->user()->balance,true) }}</th>
                            </tr>
                            <tr>
                                <th class="product-name"><strong>{{__("Total")}}</strong></th>
                                <th class="product-total">{{ format_amount($cartTotal,true) }}</th>
                            </tr>
                            <tr class="order-total">
                                <th><strong>{{__("Remaining")}}</strong></th>
                                <td><strong><span>{{ format_amount($netPayable,true) }}</span></strong></td>
                            </tr>

                        @else
                            <tr class="order-total">
                                <th><strong>{{__("Total")}}</strong></th>
                                <td><strong><span>{{ format_amount($netPayable,true) }}</span></strong></td>
                            </tr>
                        @endif

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

</style>
<script src="{{ asset('frontend/js/vendor/jquery-1.12.0.min.js') }}"></script>
    <script src="https://www.paypal.com/sdk/js?client-id={{config('paypal-rest.client_id')}}&components=buttons,marks"></script>
    <script >

        window.addEventListener('init-paypal-button',function(e){
            //console.log(paypal)
            paypal.Buttons({

                // onInit is called when the button first renders
                onInit: function (data, actions) {

                    // Disable the buttons
                    // actions.disable();

                    // Listen for changes to the checkbox
                    // document.querySelector('#check')
                    //     .addEventListener('change', function(event) {

                    // Enable or disable the button when it is checked or unchecked
                    // if (event.target.checked)  {
                    //     actions.enable();
                    // } else  {
                    //     actions.disable();
                    // }
                    // });
                },

                // onClick is called when the button is clicked
                onClick: function () {

                    // Show a validation error if the checkbox is not checked
                    // if (!document.querySelector('#check').checked) {
                    //     document.querySelector('#error').classList.remove('hidden');
                    // }
                },

                style: {
                    layout: 'vertical',
                    color: 'blue',
                    shape: 'rect',
                    label: 'paypal'
                },
                createOrder: function (data, actions) {
                    // Set up the transaction
                    return actions.order.create({
                        purchase_units: [{
                            amount: {
                                value: '{{$netPayable}}',
                                {{--currency_code: '{{getSettingsOf("currency")}}',--}}
                            }
                        }],

                        // payment_source: {
                        //     paypal: {
                        //         experience_context: {
                        //             "payment_method_preference": "IMMEDIATE_PAYMENT_REQUIRED",
                        //             "payment_method_selected": "PAYPAL",
                        //             "brand_name": "EXAMPLE INC",
                        //             "locale": "en-US",
                        //             "landing_page": "LOGIN",
                        //             "shipping_preference": "SET_PROVIDED_ADDRESS",
                        //             "user_action": "PAY_NOW",
                        //             "return_url": "https://example.com/returnUrl",
                        //             "cancel_url": "https://example.com/cancelUrl"
                        //         }
                        //     }
                        // }
                    });
                },

                onApprove: function (data, actions) {
                    // This function captures the funds from the transaction.
                    return actions.order.capture()
                        .then(function (details) {
                            console.log(details)
                            // This function shows a transaction success message to your buyer.
                            alert('Transaction completed by ' + details.payer.name.given_name);
                        });
                },
                onCancel: function (data) {
                    // Show a cancel page, or return to cart
                },
                onError: function (err) {
                    // For example, redirect to a specific error page
                    //window.location.href = "/your-error-page-here";
                }
            }).render('#paypal-button-container');
        });
    </script>
{{--@endif--}}

<script >

    var checkTransactInterval = null;
    var countDownInterval = null;

    var clearProcessTimer = function () {
       clearInterval(checkTransactInterval);
       clearInterval(countDownInterval);
    };

   var paymentCountDown = function (time) {
        let $countDowMinute = $("#countdown-minute");
        let $countDowSecond = $("#countdown-second");
        let currentMin = parseInt($countDowMinute.text());
        let currentSec = parseInt($countDowSecond.text());

        console.log("min = "+currentMin,"sec = "+currentSec);
        //debut du chrono
        if (currentSec === 0 && currentMin === 0){
            $countDowMinute.text('00');
            $countDowSecond.text("01");
            return ;
        }

        if(currentSec === 60 ){  // si atteint 60s
            if(currentMin <= 8){
                $countDowMinute.text("0"+(currentMin + 1));  // on ajoute 1 min
            }else{
                $countDowMinute.text(currentMin + 1); // on ajoute 1 min
            }
            $countDowSecond.text('00'); // reset les sec à 00
        }
        else{
            /*puisqu'on veut formater l'affichage(00-09) , on teste si la sec actuelle est <= 8
             à cause du comportement de la fonction setIntervalle() qui lui fonctionne sur le
              principe d'un do-while qui en faite s'execute au moins une fois avant de tester une condition
              logiquement sa devrait etre <= 9 , mais avec ceci , quand le chrono
              arrivera à 09 au lieu de passer directement à 10 il affichera 010*/

            let $countDowSecondText = (currentSec <= 8 )
                                     ? '0'+(currentSec + 1)
                                     : currentSec + 1;
            $countDowSecond.text($countDowSecondText); //on ajoute 1s
        }

        //a la fin du chrono
        if (currentSec === 0 && currentMin === time){
            let $countDowMinuteText = (time >= 10 ) ? time : "0"+time;
            $countDowMinute.text($countDowMinuteText);
            $countDowSecond.text('00');
            $("#timeout-message").css('display','block');
        }

    };

   window.addEventListener('show-popup-mobile-payment',function(e){
      let swalOptions = e.detail.swalOptions;
       //let paymentMethod = e.detail.paymentMethod;
       let options = {
           buttonsStyling: true,
           customClass: {
               input: 'form-control form-control-sm',
               inputLabel: 'text-left',
           },
           // inputValue: 233,

           //showDenyButton:true,
           showCancelButton:true,
           showConfirmButton:true,
           cancelButtonColor: "#f27474",
           confirmButtonColor: "#28a745",
           {{--denyButtonText: "<i class='fa fa-times'></i> {{__('Annuler')}}",--}}
           cancelButtonText: "<i class='fas fa-times'></i> {{__('Cancel')}}",
           confirmButtonText: "{{__('Pay')}} <i class='mdi mdi-cash'></i>",
           reverseButtons: true,
           showLoaderOnConfirm: true,
           allowOutsideClick : false,
           imageWidth: 150,
           imageHeight: 140,
           inputAttributes: {
               'id': "text-phone-number",
               //   maxlength: 10,
               // autocapitalize: 'off',
               //    autocorrect: 'off',
           },

           allowEnterKey : false,
           inputValidator: (value) => {
               if (!value) {
                   return '{{__("The phone number is required")}}'
               }
           },

           preConfirm : (value) => {
               let  data = {
                   "phoneNumber" : value,
                   "amount" : e.detail.amount,
                   "paymentMethodId" : e.detail.paymentMethodId,
               };

               return  request("{{route("gateway.payment.init")}}",{ body:data,method:"post"} ,false)
                       .then( response => {
                           if(response.success){
                               console.log("transaction init successfully" );
                               let payPalWindow = null;
                               if('callback_url' in response){ // PayPal-Rest
                                  let popupWinWidth = 400;
                                  let popupWinHeight = 900;
                                  let  left = (screen.width - popupWinWidth) / 2;
                                  let  top = (screen.height - popupWinHeight) / 4;

                                   payPalWindow = window.open(
                                                           response.callback_url,
                                                           "",
                                                           "left="+left+",top="+top+",width="+popupWinWidth+",height="+popupWinHeight+",toolbar=0,scrollbars=0,status=0,resizable=no"
                                                       );

                                   // payPalWindow.document.write(
                                   //     "<script>window.opener.document.body.innerHTML = 'Test'<\/script>"
                                   // );
                               }


                               if( ('transaction' in response)){
                                   let transaction = response.transaction;
                                   console.log(transaction);
                                   if(!$.isEmptyObject(transaction)){
                                       let minute = 60 * 1000; // 1min
                                       let reference = transaction.reference; // ref de la transaction
                                       let timeout = transaction.timeout; // en min
                                       let time_check_status = transaction.time_check_status; // en s

                                       // le nbre de secondes qui sera programmmé sur le timer de swal (barre de progression)
                                       let timer_value = timeout * minute;
                                       swal.fire({
                                           title: swalOptions.title,
                                           html:  transaction.waiting_alert, // l'alerte d'attente retourné

                                           imageUrl: swalOptions.imageUrl,
                                           imageWidth: swalOptions.imageWidth,
                                           imageHeight: swalOptions.imageHeight,
                                           imageAlt: swalOptions.imageAlt,

                                           showConfirmButton : false,
                                           showCancelButton : false,
                                           reverseButtons : true,
                                           allowOutsideClick : false,

                                           timer: timer_value, // en s
                                           timerProgressBar: true, // affiche la progressBar

                                           didOpen : () => {

                                               /*check le statut de la transaction toute les 2min*/
                                                checkTransactInterval = setInterval(() => {
                                                                               var data = { "reference" : reference,};

                                                                               request("{{route("gateway.payment.check")}}/"+reference,{body:data,method:"post"},false)
                                                                               .then( response => {
                                                                                   let transaction = response.transaction;
                                                                                   let payment = response.payment;
                                                                                   let config = {
                                                                                       title : transaction.message,
                                                                                       icon : "success",
                                                                                       position: (payment.saved) ? 'top-end':'bottom-end',
                                                                                       timer: 5000,
                                                                                       // ok_button: true,
                                                                                   };
                                                                                   if(transaction.success){
                                                                                       try {
                                                                                           if(typeof payPalWindow !== "undefined" && !$.isEmptyObject(payPalWindow) ){
                                                                                               payPalWindow.close();
                                                                                           }
                                                                                       }catch (e) {
                                                                                           console.log(e)
                                                                                       }finally {
                                                                                           // si on arrete de check le statut
                                                                                           if(transaction.stop_check_status){
                                                                                               clearProcessTimer();
                                                                                               // si le payment a été enregistré dans la bd
                                                                                               if (payment.saved){
                                                                                                   toast(config);
                                                                                                   @this.submitOrder()
                                                                                               }else{
                                                                                                   swal.showValidationMessage(`${payment.message}`);
                                                                                               }
                                                                                           }
                                                                                       }

                                                                                   }
                                                                                   else if(transaction.failed){
                                                                                       clearProcessTimer();
                                                                                       swal.showValidationMessage(`${transaction.message}`)
                                                                                   }
                                                                                   else if(transaction.pending){}
                                                                               })
                                                                               .catch (error => {
                                                                                   swal.showValidationMessage(`${error}`)
                                                                               });

                                                                           }, time_check_status);

                                               /*décompteur*/
                                               countDownInterval = setInterval(() => { paymentCountDown(timeout); }, 1000);
                                           },
                                           willClose : () => {
                                               clearProcessTimer();
                                           },
                                       })
                                       .then((result) => {});
                                   }
                               }
                           }
                           else{
                               swal.showValidationMessage(`${response.message}`);
                               console.log("transaction init failed" );
                           }
                       })
                       .catch (error  => {
                           swal.showValidationMessage(`{{__("Error")}} : ${error}`)
                       });
           },
       };

        swalOptions = $.extend(options,e.detail.swalOptions);

       swal.fire(swalOptions)
           .then( result => {
               if (result.isDismissed){
                   //this.select_mode(amount);
               }
           })
   });

window.addEventListener('display-stock-availabity-messages',function(e){
        var data = e.detail;
        swal.fire({
            icon: "error",
            html : data.message,
            showConfirmButton : true,
            willClose :function () {
                if(data.redirect){
                    location.href = "{{route('cart.index')}}";
                }

            }
        })

});


</script>
