<? global $settings; ?>
<div id="basket-container">
  <div id="content">
    <?= $this->basket_details; ?>
  </div>
  <div id="paypo-promo">
    Chcesz skorzystać z odroczonych płatności <img src="/layout/images/paypo-logo.svg">? Wybierz jedną z form dostawy: <strong>odbiór osobisty, Paczkomaty InPost - przedpłata lub Kurier - przedpłata</strong>.<br />
    Wartość zamówienia musi mieścić się w przedziale od 40 zł do 1000 zł.
  </div>
  <? if (is_array($this->basket) and count($this->basket)): ?>
    <div class="basket-options">
      <div class="content">
        <div class="left">
          <div class="box-title"><?= ucfirst(\Shared\Helpers\Helpers::lang('dostawa')); ?>:</div>
          <div id="transport-methods">
            <?= $this->transport_methods; ?>
          </div>
          <div class="inpost-map-container">
            <a href="#" onclick="inpost_check(); return false;" class="inpost-hide"><?= \Shared\Helpers\Helpers::lang('zamknij'); ?></a>
            <div id="inpost-map"></div>
          </div>
        </div>
        <div class="right">
          <div class="box-title"><?= ucfirst(\Shared\Helpers\Helpers::lang('platnosc')); ?>:</div>
          <div id="payment-methods"></div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-12">
        <a href="/koszyk-podsumowanie" id="btn-basket-summary" class="btn btn-success disabled float-right"><span class="text"><?= ucfirst(\Shared\Helpers\Helpers::lang('przejdz-do-podsumowania')); ?></span></a>
      </div>
    </div>
  <? endif; ?>
  <div class="orlen-banner">
    <img src="/layout/images/orlen-banner.jpg" alt="Orlen" />
  </div>
</div>
<script>
  (function(o, r, l, e, n) {
    o[l] = o[l] || [];
    var f = r.getElementsByTagName('head')[0];
    var j = r.createElement('script');
    j.async = true;
    j.src = e + 'widget.js?token=' + n + '&v=1.0.0&t=' + Math.floor(new Date().getTime() / 1000);
    f.insertBefore(j, f.firstChild);
  })(window, document, 'orlenpaczka', 'https://mapa.orlenpaczka.pl/', '<?= $settings['orlen_paczka_map_token'];?>');
</script>
<link class="footer" rel="stylesheet" type="text/css" href="/libraries/grid/plugins/icheck/skins/square/_all.css">
<link class="footer" rel="stylesheet" type="text/css" href="https://geowidget.easypack24.net/css/easypack.css">
<script class="footer" type="text/javascript" src="/libraries/grid/plugins/icheck/icheck.min.js"></script>
<script class="footer" type="text/javascript" src="https://geowidget.easypack24.net/js/sdk-for-javascript.js"></script>
<script class="footer" type="text/javascript">
  var inpost_transport_method_id = '';

  function inpost_check() {

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/shopBasket/inpost_check',
      beforeSend: function() {

      },
      success: function(response) {
        data = jQuery.parseJSON(response);
        if (data.result == 'bad') {
          $('.inpost-info-' + inpost_transport_method_id).html('<a href="#" onclick="inpost_map( ' + inpost_transport_method_id + ' ); return false;">wybierz</a>');
        }

        $('.inpost-map-container').hide();
      }
    });
    return false;
  }

  function payment_checked(payment_method_id) {
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/shopBasket/basket_payment_method_set',
      data: {
        payment_method_id: payment_method_id
      },
      beforeSend: function() {
        $('#basket-container *').addClass('disabled');
        $('#payment-methods .icheck, #transport-methods .icheck').iCheck('disable');
      },
      success: function(response) {
        response = jQuery.parseJSON(response);
        $('#basket-container *').removeClass('disabled');
        $('#payment-methods .icheck, #transport-methods .icheck').iCheck('enable');
        $('#btn-basket-summary').removeClass('disabled');
      }
    });
    return false;
  }

  function inpost_map(transport_method_id) {
    inpost_transport_method_id = transport_method_id;

    window.easyPackAsyncInit = function() {
      easyPack.init({
        mapType: 'osm',
        searchType: 'osm',
      });

      var map = easyPack.mapWidget('inpost-map', function(point) {
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/shopBasket/inpost_save',
          data: {
            paczkomat: point.name + ' | ' + point.address.line1 + ', ' + point.address.line2
          },
          beforeSend: function() {},
          success: function(response) {
            $('.inpost-info-' + transport_method_id).html(point.name + ' | ' + point.address.line1 + ', ' + point.address.line2 + '<a href="#" onclick="inpost_map( ' + transport_method_id + ' ); return false;">zmień</a>');
            $('.inpost-map-container').hide();
          }
        });
      });
    };
    $('.inpost-map-container').show();
  }

  function transport_checked(transport_method_id, payment_method_id, event_click) {
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/shopBasket/basket_payments_methods',
      data: {
        payment_method_id: payment_method_id,
        transport_method_id: transport_method_id
      },
      beforeSend: function() {
        $('#basket-container *').addClass('disabled');
        $('#transport-methods .icheck, #transport-methods .icheck').iCheck('disable');
      },
      success: function(response) {
        response = jQuery.parseJSON(response);
        $('#basket-container *').removeClass('disabled');
        $('#transport-methods .icheck, #transport-methods .icheck').iCheck('enable');
        $('#payment-methods').html(response.payment_methods);
        $('#payment-methods .icheck').iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_square-blue'
        });

        if (payment_method_id)
          $('#btn-basket-summary').removeClass('disabled');

        $('#payment-methods .icheck').on('ifChecked', function(event) {
          var payment_method_id = $(this).val();
          payment_checked(payment_method_id);
        });

        if ( event_click && ( transport_method_id == '1' || transport_method_id == '2' ) )
        {
          $.ajax({
            type: 'POST',
            cache: false,
            url: '/shopBasket/inpost_save',
            data: {
              paczkomat: null
            },
            beforeSend: function() {},
            success: function(response) {}
          });
          $( '#orlen_point_id' ).val( '' );
          $( '#orlen_point_info' ).addClass( 'hidden' );
          $( '.orlen-widget' ).addClass( 'hidden' );
          inpost_map( transport_method_id )
        }

        if ( event_click && transport_method_id == '9' )
        {
          $( '.inpost-info' ).html( '' );
          $( '#orlen_point_info' ).removeClass( 'hidden' );
          $( '.orlen-widget' ).removeClass( 'hidden' );
          document.querySelectorAll('.orlen-widget').forEach(function(element) {
            element.click();  // Wywołuje kliknięcie na elemencie
          });
        }

        if ( event_click && transport_method_id != 1 )
        {
          $.ajax({
            type: 'POST',
            cache: false,
            url: '/shopBasket/inpost_save',
            data: {
              paczkomat: null
            },
            beforeSend: function() {},
            success: function(response) {}
          });
          $( '.inpost-info' ).html( '' );
        }

        if ( event_click && transport_method_id != 9 )
        {
          $( '#orlen_point_id' ).val( '' );
          $( '#orlen_point_info' ).html( '' );
          $( '.orlen-widget' ).addClass( 'hidden' );
        }
      }
    });
    return false;
  }

  $(function() {
    $('body').on('change', '#basket .basket-product-message textarea', function() {
      var _this = $(this);

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/product_message_change',
        data: {
          product_message: _this.val(),
          position_code: _this.attr('position')
        },
        beforeSend: function() {},
        success: function() {}
      });
    });

    $('body').on(click_event, '#btn-basket-summary', function(e) {

      e.preventDefault();
      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/transport_method_inpost_check',
        data: {},
        beforeSend: function() {
          $('#basket-container *').addClass('disabled');
        },
        success: function(response) {

          data = jQuery.parseJSON(response);
          $('#basket-container *').removeClass('disabled');
          if (data.result === 'bad') {

            $.alert({

              title: '<?= ucfirst(\Shared\Helpers\Helpers::lang('uwaga')); ?>',
              content: 'Proszę wybrać punkt odbioru',
              type: 'blue',
              closeIcon: true,
              closeIconClass: 'fa fa-times',
              typeAnimated: true,
              animation: 'opacity',
              useBootstrap: false,
              theme: 'modern',
              autoClose: 'confirm|5000',
              buttons: {
                confirm: {
                  text: '<?= \Shared\Helpers\Helpers::lang('zamknij'); ?>',
                  btnClass: 'btn-blue',
                  keys: ['enter'],
                  action: function() {}
                }
              }
            });
          } else {
            document.location.href = '/koszyk-podsumowanie';
          }
        }
      });
    });

    $('body').on('change', '#basket-message', function() {
      var _this = $(this);
      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/basket_message_save',
        data: {
          basket_message: _this.val()
        },
        beforeSend: function() {
          $('#basket-container *').addClass('disabled');
        },
        success: function(response) {
          data = jQuery.parseJSON(response);

          $('#basket-container *').removeClass('disabled');
        }
      });
    });

    $('body').on('change', '.basket-product .int-format', function() {
      var product_hash = $(this).attr('product-hash');
      var quantity = $(this).val();

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/basket_change_quantity_product',
        data: {
          product_hash: product_hash,
          quantity: quantity
        },
        beforeSend: function() {
          $('#basket-container *').addClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('disable');
        },
        success: function(response) {
          data = jQuery.parseJSON(response);

          if (data.products_count === 0) {
            document.location.href = '/koszyk';
            $('.mini-box').hide();
            return false;
          }

          $('#basket-container *').removeClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('enable');
          $('#basket-container #content').html(data.basket);

          $('#basket-mini #products-count').html(data.basket_mini_count);
          $('#basket-mini #basket-value').html(data.basket_mini_value);

          $('#basket-container #transport-methods').html(data.transport_methods);
        }
      });
      return false;
    });

    $('body').on(click_event, '.basket-product .btn-minus', function() {
      var product_hash = $(this).attr('product-hash');

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/basket_decrease_quantity_product',
        data: {
          product_hash: product_hash
        },
        beforeSend: function() {
          $('#basket-container *').addClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('disable');
        },
        success: function(response) {

          data = jQuery.parseJSON(response);

          if (data.products_count === 0) {
            document.location.href = '/koszyk';
            $('.mini-box').hide();
            return false;
          }

          $('#basket-container *').removeClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('enable');
          $('#basket-container #content').html(data.basket);

          $('#basket-mini #products-count').html(data.basket_mini_count);
          $('#basket-mini #basket-value').html(data.basket_mini_value);

          $('#basket-container #transport-methods').html(data.transport_methods);
        }
      });
      return false;
    });

    $('body').on(click_event, '.basket-product .btn-plus', function() {
      var product_hash = $(this).attr('product-hash');

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/shopBasket/basket_increase_quantity_product',
        data: {
          product_hash: product_hash
        },
        beforeSend: function() {
          $('#basket-container *').addClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('disable');
        },
        success: function(response) {
          data = jQuery.parseJSON(response);

          if (data.products_count === 0) {
            document.location.href = '/koszyk';
            $('.mini-box').hide();
            return false;
          }

          $('#basket-container *').removeClass('disabled');
          $('#payment-methods .icheck, #transport-methods .icheck').iCheck('enable');
          $('#basket-container #content').html(data.basket);

          $('#basket-mini #products-count').html(data.basket_mini_count);
          $('#basket-mini #basket-value').html(data.basket_mini_value);

          $('#basket-container #transport-methods').html(data.transport_methods);
        }
      });
      return false;
    });

    $('body').on(click_event, '.basket-product .btn-delete', function() {
      var product_hash = $(this).attr('product-hash');

      $.alert({
        title: '<?= ucfirst(\Shared\Helpers\Helpers::lang('potwierdz')); ?>',
        content: '<?= \Shared\Helpers\Helpers::lang('potwierdz-usuniecie-produktu-z-koszyka'); ?>',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        useBootstrap: false,
        theme: 'modern',
        autoClose: 'cancel|10000',
        buttons: {
          confirm: {
            text: '<?= \Shared\Helpers\Helpers::lang('usun'); ?>',
            btnClass: 'btn-orange',
            keys: ['enter'],
            action: function() {
              $.ajax({
                type: 'POST',
                cache: false,
                url: '/shopBasket/basket_remove_product',
                data: {
                  product_hash: product_hash
                },
                beforeSend: function() {
                  $('#basket-container *').addClass('disabled');
                  $('#payment-methods .icheck, #transport-methods .icheck').iCheck('disable');
                },
                success: function(response) {
                  data = jQuery.parseJSON(response);

                  if (data.products_count === 0) {
                    document.location.href = '/koszyk';
                    $('.mini-box').hide();
                    return false;
                  }

                  $('#basket-container *').removeClass('disabled');
                  $('#payment-methods .icheck, #transport-methods .icheck').iCheck('enable');
                  $('#basket-container #content').html(data.basket);

                  $('#basket-mini #products-count').html(data.basket_mini_count);
                  $('#basket-mini #basket-value').html(data.basket_mini_value);

                  $('#basket-container #transport-methods').html(data.transport_methods);
                }
              });
            }
          },
          cancel: {
            text: '<?= \Shared\Helpers\Helpers::lang('zamknij'); ?>',
            btnClass: 'btn-blue',
            action: function() {}
          }
        }
      });
      return false;
    });
  });

  // zapisywanie wybranego orlen punktu
  document.addEventListener('DOMContentLoaded', function() {
    // Znajdź element #orlen_point_id
    var orlenPointElement = document.querySelector('#transport-methods #orlen_point_id');

    if (orlenPointElement) {
      // Utwórz observer, który będzie reagował na zmiany w atrybucie value
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
            var orlen_point_id = orlenPointElement.value;
            var orlen_point_name = document.querySelector('#orlen_point_info').textContent;

            // Przygotuj dane jako form-urlencoded
            var formData = new URLSearchParams();
            formData.append('orlen_point_id', orlen_point_id);
            formData.append('orlen_point_name', orlen_point_name);

            // Wykonaj żądanie AJAX
            fetch('/shopBasket/orlen_save', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData,
                cache: 'no-cache'
              })
              .then(response => response.text())
              .then(data => {
                // Obsługa odpowiedzi
                console.log('Odpowiedź serwera:', data);
              })
              .catch(error => {
                console.error('Błąd podczas wykonywania żądania:', error);
              });
          }
        });
      });

      // Konfiguracja observera do śledzenia zmian atrybutów
      observer.observe(orlenPointElement, {
        attributes: true
      });
    } else {
      console.warn('#orlen_point_id nie został znaleziony.');
    }
  });
</script>