<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($userAddressId)
                <h2 class="h5 text-uppercase mb-4">{{__("Shipping way")}}</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 companies found")}}</p>
                    @endforelse
                </div>

                @if($paymentIsRequired)
                    @if($userAddressId && $shippingCompanyId)
                        <h2 class="h5 text-uppercase mb-4">{{__("Payment way")}}</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 )

                                    <div class="col-12 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>{{ __("I Not have a payment method") }}</b>
                                            </label>
                                        </div>
                                    </div>
                                @endif
                            @empty
                                <p>{{__("No payment way found")}}</p>
                            @endforelse
                        </div>
                    @endif
                    @if( ($userAddressId && $shippingCompanyId && $paymentMethodId > 0))
                        @if(\Str::lower($paymentMethodCode) == 'ppex')
                            <form action="{{ route('payment.store') }}" method="POST">
                                @csrf
                                <input type="hidden" name="userAddressId" value="{{ old('userAddressId', $userAddressId) }}"
                                       class="form-control">
                                <input type="hidden" name="shippingCompanyId"
                                       value="{{ old('shippingCompanyId', $shippingCompanyId) }}" class="form-control">
                                <input type="hidden" name="paymentMethodId" value="{{ old('paymentMethodId', $paymentMethodId) }}"
                                       class="form-control">
                                <button type="submit" name="submit" class="btn btn-default btn-block uppercase">
                                    {{__("Pay :amount With :method",["method" => $selectedPaymentMethod->name,"amount" => format_amount($netPayable,true)])}}
                                </button>
                            </form>
                        @endif
                        @if(\Str::lower($paymentMethodCode) == 'mada')
                            <form action="{{ route('checkout.charge_request') }}">
                                @csrf
                                <input type="hidden" name="userAddressId" value="{{ old('userAddressId', $userAddressId) }}"
                                       class="form-control">
                                <input type="hidden" name="shippingCompanyId"
                                       value="{{ old('shippingCompanyId', $shippingCompanyId) }}" class="form-control">
                                <input type="hidden" name="paymentMethodId" value="{{ old('paymentMethodId', $paymentMethodId) }}"
                                       class="form-control">
                                <button type="submit" name="submit" class="btn btn-default btn-block uppercase">
                                    {{__("Pay :amount With :method",["method" => $selectedPaymentMethod->name,"amount" => format_amount($netPayable,true)])}}
                                </button>
                            </form>
                        @endif
                        @if(in_array(Str::lower($paymentMethodCode),['orange-momo-cmr',"mtn-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

                    @endif
                    @if(blank($paymentMethods) or !$paymentMethodFounded)
                        <button type="button" class="btn btn-success btn-block uppercase"
                                wire:click="submitOrderWithoutPaymentMethod()"  >
                            {{__("Submit order without payment method")}}
                        </button>
                    @endif
                @else
                    @if($shippingCompanyId)
                        <button type="button" class="btn btn-dark btn-block uppercase"
                                wire:click="submitOrder"  >
                            {{__("Send Order")}}
                        </button>
                    @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($cartTotal,true) }}</span></strong></td>
                            </tr>
                        @endif

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


<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,
           input: 'number',
           imageWidth: 200,
           imageHeight: 200,
           inputAttributes: {
               'id': "text-phone-number",
               //   maxlength: 10,
               // autocapitalize: 'off',
               //    autocorrect: 'off',
           },

           allowEnterKey : false,
           inputValidator: (value) => {
               if (!value) {
                   return '{{__("Le Nº de téléphone est obligatoire")}}'
               }
           },

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

               return  request("{{route("shop.payment.init")}}",{ body:data,method:"post"} ,false)
                       .then( response => {
                           if(response.success){
                               console.log("transaction init successfully" );

                               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: 200,
                                           imageHeight: 200,
                                           imageAlt: swalOptions.imageAlt,

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

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

                                           didOpen : () => {
                                              // this.setStateControls();

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

                                                                               request("{{route("shop.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){
                                                                                       // si on arrete de check le statut
                                                                                       if(transaction.stop_check_status){
                                                                                           clearProcessTimer();
                                                                                          // toast(config);
                                                                                           // 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  => {
                           console.log(error)
                           swal.showValidationMessage(`{{__("Echec")}} : ${error}`)
                       });
           },
       };

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

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


</script>
