<div class="table-responsive">
  <table id="tableCart" class="table table-striped table-hover">
   	<thead>
     	<tr class="colored">
        <th></th>
        <th><?php echo app('translator')->getFromJson('frontend.image'); ?></th>
       	<th><?php echo app('translator')->getFromJson('frontend.name'); ?></th>
        <th><?php echo app('translator')->getFromJson('frontend.notes'); ?></th>
       	<th><?php echo app('translator')->getFromJson('frontend.qty'); ?></th>
       	<th><?php echo app('translator')->getFromJson('frontend.price'); ?></th>
       	<th><?php echo app('translator')->getFromJson('frontend.subtotal'); ?></th>
     	</tr>
   	</thead>

   	<tbody>
      <?php if(Cart::content()->count() != 0): ?>
        <?php $__currentLoopData = Cart::content(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

         		<tr>
                <td>
                  <a href="#" title="remove item" class="remove-item" data-rowid="<?php echo e($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();
                 ?>
                <td width="10%">
                  <img class="img img-responsive" alt="image" src="<?php echo e(asset($storage_url.'img/products/'.$img->product_code.'/'.$img->product_image)); ?>" style="max-height:125px;margin: 0 auto">
                </td>
             		<td width="20%">
                 		<p><strong><?php echo e($row->name); ?></strong></p>
             		</td>
                <td width="25%">
                  <textarea class="form-control input-notes" data-id="<?php echo e($row->id); ?>" data-rowid="<?php echo e($row->rowId); ?>" style="min-width:200px"><?php echo e(($row->options->notes!="") ? $row->options->notes : '-'); ?></textarea>
                </td>
             		<td width="10%"><input class="form-control input-qty" type="number" value="<?php echo e($row->qty); ?>" data-id="<?php echo e($row->id); ?>" min="1" data-rowid="<?php echo e($row->rowId); ?>"></td>
             		<td width="20%"><?php 
                
                if($masterCurrency === 'USD' ){
                  echo ($masterCurrency.' '.number_format($row->price,2,'.',','));
                }elseif($masterCurrency === 'EUR' ){
                  echo ($masterCurrency.' '.number_format($row->price,2,',','.'));
                }else{
                  echo ($masterCurrency.' '.number_format($row->price,0,',','.'));
                } 
              
              ?></td>
             		<td width="20%"><?php 
                
                if($masterCurrency === 'USD' ){
                  echo ($masterCurrency.' '.number_format($row->total,2,'.',','));
                }elseif($masterCurrency === 'EUR' ){
                  echo ($masterCurrency.' '.number_format($row->total,2,',','.'));
                }else{
                  echo ($masterCurrency.' '.number_format($row->total,0,',','.'));
                } 
              
              ?></td>
         		</tr>

  	   	<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      <?php else: ?>
        <tr><td class="text-center" colspan="7">
          <h3><i class="fa fa-shopping-bag fa-lg" aria-hidden="true"></i></h3>
        </td></tr>
      <?php 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());
     ?>

   	<tfoot>
   		<tr class="colored">
   			<td colspan="5">&nbsp;</td>
   			<td><strong><?php echo app('translator')->getFromJson('frontend.subtotal'); ?></strong></td>
   			<td><?php echo e($masterCurrency); ?> <?php echo e(Cart::subtotal()); ?></td>
   		</tr>
      <tr>
        <?php if($shipment->option == 'delivery'): ?>
          <td colspan="3"><?php echo app('translator')->getFromJson('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="<?php echo e(isset($shipmentDestination) ? $shipmentDestination : ''); ?>">
          </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>
            <?php echo e($masterCurrency); ?>

            <text id="cart-shipment">
              <?php echo e(number_format($shipmentCost, 0, ".", ".")); ?>

            </text>
          </td>
        <?php elseif($shipment->option == 'flat'): ?>
          <?php 
            $shipmentCost = $shipment->amount;
           ?>
          <td colspan="6" style="text-align: right;">Shipment(Flat)</td>
          <td>
            <?php echo e($masterCurrency); ?>

            <text id="cart-shipment">
              <?php echo e(number_format($shipment->amount, 0, ".", ".")); ?>

            </text>
          </td>
        <?php else: ?>
          <td colspan="6" style="text-align: right;">Shipment(Free)</td>
          <td>
            <?php echo e($masterCurrency); ?>

            <text id="cart-shipment">
              <?php echo e(number_format(0, 0, ".", ".")); ?>

            </text>
          </td>
        <?php 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><?php echo app('translator')->getFromJson('frontend.total'); ?></strong></td>
   			<td><?php echo e($masterCurrency); ?>

          <text id="cart-total"><?php echo e(number_format(($shipmentCost + $cartTotal), 0, ".", ".")); ?>

          </text>
        </td>
   		</tr>
   	</tfoot>
  </table>
  <?php if(Cart::content()->count() != 0): ?>
    <button id="clearCart" class="btn btn-default"><i class="fa fa-trash" aria-hidden="true"></i> <?php echo app('translator')->getFromJson('frontend.clear_cart'); ?></button>
  <?php endif; ?>
</div>

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

  var map;
  var geocoder;
  var bounds = new google.maps.LatLngBounds();
  var markersArray = [];
  var origin = "<?php echo e(isset($shipment->city) ? $shipment->city : ''); ?>"
  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);
        }
       ?>


      var cartDistance = Math.round(results[0].distance.value/1000);
      var cartWeight = Math.round(<?php echo e($weight); ?>)
      var cartShipmentCost = <?php echo e($shipment->amount); ?>

      var cartSubtotal = <?php echo e($subtotal); ?>


      if (cartDistance < 1) {
        cartDistance = 1
      }

      if (cartWeight < 1) {
        cartWeight = 1
      }

      var shipmentCost = formatNumber(cartDistance * cartWeight * cartShipmentCost)

      <?php if($shipment->option == 'delivery'): ?>
        $.ajax({
          type: 'post',
          url: '<?php echo e(route('updateItem')); ?>',
          data: {
              '_token': '<?php echo e(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))
          },
        });
      <?php else: ?>
        $("#cart-shipment").html(shipmentCost)
        $("#cart-total").html(formatNumber(cartDistance * cartWeight * cartShipmentCost + cartSubtotal))
      <?php 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: '<?php echo e(route('updateItem')); ?>',
        data: {
            '_token': '<?php echo e(csrf_token()); ?>',
            'row_id': $row_id,
            'qty': $qty,
        },
        success: function(data) {
          $.get( '<?php echo e(route('updateBubble')); ?>', function( data ) {
            if(data == 0){
              $("#show_cart span.label").hide();
            }else{
              $("#show_cart span.label").show().html(data);
            }
          });
          $("#cart_content").load("<?php echo e(route('cart')); ?>");
        },
    });
  });

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

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

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

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

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