<div class="table-responsive">
  <table id="tableCart" class="table table-striped table-hover">
   	<thead>
     	<tr class="colored">
        <th></th>
        <th>@lang('frontend.image')</th>
       	<th>@lang('frontend.name')</th>
        <th>@lang('frontend.notes')</th>
       	<th>@lang('frontend.qty')</th>
       	<th>@lang('frontend.price')</th>
       	<th>@lang('frontend.subtotal')</th>
     	</tr>
   	</thead>

   	<tbody>
      @if (Cart::content()->count() != 0)
        @foreach(Cart::content() as $row)

         		<tr>
                <td>
                  <a href="#" title="remove item" class="remove-item" data-rowid="{{ $row->rowId }}"><i class="fa fa-minus-square-o fa-lg" aria-hidden="true"></i></a>
                </td>
                @php
                  $img = App\Product::where(['product_code'=>$row->id])->first();
                @endphp
                <td width="10%">
                  <img class="img img-responsive" alt="image" src="{{ asset($storage_url.'img/products/'.$img->product_code.'/'.$img->product_image) }}" style="max-height:125px;margin: 0 auto">
                </td>
             		<td width="20%">
                 		<p><strong>{{ $row->name }}</strong></p>
             		</td>
                <td width="25%">
                  <textarea class="form-control input-notes" data-id="{{ $row->id }}" data-rowid="{{ $row->rowId }}" style="min-width:200px">{{ ($row->options->notes!="") ? $row->options->notes : '-' }}</textarea>
                </td>
             		<td width="10%"><input class="form-control input-qty" type="number" value="{{ $row->qty }}" data-id="{{ $row->id }}" min="1" data-rowid="{{ $row->rowId }}"></td>
             		<td width="20%">@currency($row->price)</td>
             		<td width="20%">@currency($row->total)</td>
         		</tr>

  	   	@endforeach
      @else
        <tr><td class="text-center" colspan="7">
          <h3><i class="fa fa-shopping-bag fa-lg" aria-hidden="true"></i></h3>
        </td></tr>
      @endif

   	</tbody>

    @php
      $shipmentCost = 0;
      $shipmentDestination = '';
      if (Cart::content()->count()) {
        $shipmentCost = Cart::content()->first()->options->shipment_cost ? Cart::content()->first()->options->shipment_cost : 0;
        $shipmentDestination = Cart::content()->first()->options->shipment_destination ? Cart::content()->first()->options->shipment_destination : '';
      }
      $shipmentCost = str_replace([',', '.'], "", $shipmentCost);
      $cartTotal = str_replace([',', '.'], "", Cart::total());
    @endphp

   	<tfoot>
   		<tr class="colored">
   			<td colspan="5">&nbsp;</td>
   			<td><strong>@lang('frontend.subtotal')</strong></td>
   			<td>{{ $masterCurrency }} {{ Cart::subtotal() }}</td>
   		</tr>
      <tr>
        @if ($shipment->option == 'delivery')
          <td colspan="3">@lang('frontend.shipment-choose-a-city-of-destination')</td>
          <td colspan="2">
            <input type="text" placeholder="Isi Tujuan" class="form-control js-map-auto" name="shipment_destination"
              value="{{ $shipmentDestination or '' }}">
          </td>
          <td>
            <a href="#" class="btn btn-sm btn-default js-toggle-map"><i class="fa fa-map-marker"></i></a> <a href="#" class="btn btn-sm btn-primary js-calculate">Calculate</a>
          </td>
          <td>
            {{ $masterCurrency }}
            <text id="cart-shipment">
              {{ number_format($shipmentCost, 0, ".", ".") }}
            </text>
          </td>
        @elseif($shipment->option == 'flat')
          @php
            $shipmentCost = $shipment->amount;
          @endphp
          <td colspan="6" style="text-align: right;">Shipment(Flat)</td>
          <td>
            {{ $masterCurrency }}
            <text id="cart-shipment">
              {{ number_format($shipment->amount, 0, ".", ".") }}
            </text>
          </td>
        @else
          <td colspan="6" style="text-align: right;">Shipment(Free)</td>
          <td>
            {{ $masterCurrency }}
            <text id="cart-shipment">
              {{ number_format(0, 0, ".", ".") }}
            </text>
          </td>
        @endif

      </tr>
      <tr class="js-google-map display-none">
        <td colspan="7">
          <div id="g-map" style="height: 350px;"></div>
        </td>
      </tr>
   		<tr class="colored">
   			<td colspan="5">&nbsp;</td>
   			<td><strong>@lang('frontend.total')</strong></td>
   			<td>{{ $masterCurrency }}
          <text id="cart-total">{{ number_format(($shipmentCost + $cartTotal), 0, ".", ".") }}
          </text>
        </td>
   		</tr>
   	</tfoot>
  </table>
  @if (Cart::content()->count() != 0)
    <button id="clearCart" class="btn btn-default"><i class="fa fa-trash" aria-hidden="true"></i> @lang('frontend.clear_cart')</button>
  @endif
</div>

<script>
  $('#body').ready(function() {
    initMap()
  })

  var map;
  var geocoder;
  var bounds = new google.maps.LatLngBounds();
  var markersArray = [];
  var origin = "{{ $shipment->city or '' }}"
  var destinationIcon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000";
  var originIcon = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000";

  $(".js-calculate").on("click", function(e) {
    e.preventDefault()
    var button = $(this)
    var destination = $(".js-map-auto").val()
    calculateDistances(origin, destination)
  })

  $(".js-toggle-map").on("click", function(e) {
    e.preventDefault()
    $(".js-google-map").toggleClass("display-none")
    initMap()
    if($(".js-map-auto").val()) {
      calculateDistances(origin, $(".js-map-auto").val())
    }
  })

  function calculateDistances(origin, destination) {
    var service = new google.maps.DistanceMatrixService()
    service.getDistanceMatrix({
      origins: [origin],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback)
  }

  function initMap() {
    var opts = {
      center: new google.maps.LatLng(-7.25009,112.744331),
      zoom: 5,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('g-map'), opts);
    geocoder = new google.maps.Geocoder();

    var elements = document.getElementsByClassName('js-map-auto')

    for (var element of elements) {
      new google.maps.places.Autocomplete(element,{ types: ['geocode'] });
    }
  }

  function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;

      deleteOverlays();

      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        addMarker(origins[i], false);
        for (var j = 0; j < results.length; j++) {
          addMarker(destinations[j], true);
        }
      }

      @php
        $weight = 0;
        $subtotal = 0;
        foreach(Cart::content() as $content) {
          $weight = $weight + ($content->options->product->product_weight * $content->qty);
          $subtotal = $subtotal + ($content->price * $content->qty);
        }
      @endphp


      var cartDistance = Math.round(results[0].distance.value/1000);
      var cartWeight = Math.round({{ $weight }})
      var cartShipmentCost = {{ $shipment->amount }}
      var cartSubtotal = {{ $subtotal }}

      if (cartDistance < 1) {
        cartDistance = 1
      }

      if (cartWeight < 1) {
        cartWeight = 1
      }

      var shipmentCost = formatNumber(cartDistance * cartWeight * cartShipmentCost)

      @if ($shipment->option == 'delivery')
        $.ajax({
          type: 'post',
          url: '{{ route('updateItem') }}',
          data: {
              '_token': '{{ csrf_token() }}',
              'shipment_cost': shipmentCost,
              'shipment_destination': $(".js-map-auto").val()
          },
          success: function(data) {
            $("#cart-shipment").html(shipmentCost)
            $("#cart-total").html(formatNumber(cartDistance * cartWeight * cartShipmentCost + cartSubtotal))
          },
        });
      @else
        $("#cart-shipment").html(shipmentCost)
        $("#cart-total").html(formatNumber(cartDistance * cartWeight * cartShipmentCost + cartSubtotal))
      @endif

      console.log(`Shipment cost : ${cartDistance} km * ${cartWeight} kg * ${cartShipmentCost} (cost) = ${shipmentCost}`)

    }
  }

  function formatNumber (num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.")
  }

  function addMarker(location, isDestination) {
    var icon;

    if (isDestination) {
      icon = destinationIcon;
    } else {
      icon = originIcon;
    }

    geocoder.geocode({'address': location}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        bounds.extend(results[0].geometry.location);
        map.fitBounds(bounds);

        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          icon: icon
        });

        markersArray.push(marker);
      } else {
        alert("Terjadi kesalahan: " + status);
      }
    })
  }

  function deleteOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }

  $(".input-qty").change(function(){
    var $row_id = $(this).data("rowid");
    var $qty = $(this).val();

    $.ajax({
        type: 'post',
        url: '{{ route('updateItem') }}',
        data: {
            '_token': '{{ csrf_token() }}',
            'row_id': $row_id,
            'qty': $qty,
        },
        success: function(data) {
          $.get( '{{ route('updateBubble') }}', function( data ) {
            if(data == 0){
              $("#show_cart span.label").hide();
            }else{
              $("#show_cart span.label").show().html(data);
            }
          });
          $("#cart_content").load("{{route('cart')}}");
        },
    });
  });

  $(".input-notes").change(function(){
    var $row_id = $(this).data("rowid");
    var $notes = $(this).val();

    $.ajax({
        type: 'post',
        url: '{{ route('updateItem') }}',
        data: {
            '_token': '{{ csrf_token() }}',
            'row_id': $row_id,
            'notes': $notes,
        },
        success: function(data) {
          $("#cart_content").load("{{route('cart')}}");
        },
    });
  });

  $(".remove-item").click(function(e){
    e.preventDefault();
    var $row_id = $(this).data("rowid");

    $.ajax({
        type: 'post',
        url: '{{ route('deleteItem') }}',
        data: {
            '_token': '{{ csrf_token() }}',
            'row_id': $row_id,
        },
        success: function(data) {
          $.get( '{{ route('updateBubble') }}', function( data ) {
            if(data == 0){
              $("#show_cart span.label").hide();
            }else{
              $("#show_cart span.label").show().html(data);
            }
          });
          $("#cart_content").load("{{route('cart')}}");
        },
    });
  });

  $("#clearCart").click(function(){
    $.ajax({
        type: 'post',
        url: '{{ route('clearCart') }}',
        data: {
            '_token': '{{ csrf_token() }}',
        },
        success: function(data) {
          $.get( '{{ route('updateBubble') }}', function( data ) {
            if(data == 0){
              $("#show_cart span.label").hide();
            }else{
              $("#show_cart span.label").show().html(data);
            }
          });
          $("#cart_content").load("{{route('cart')}}");
        },
    });
  });
</script>
