<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<script>
	document.addEventListener('DOMContentLoaded', function() {
  // Loop through all the tables on the page
  const tables = document.querySelectorAll('.woocommerce-product-attributes');
  tables.forEach(table => {
    const placeIdElement = table.querySelector('.woocommerce-product-attributes-item--attribute_place-id .woocommerce-product-attributes-item__value p');
    const placeId = placeIdElement.textContent;

    getPlaceIdContent(placeId, table);
  });
	});

  function getPlaceIdContent(placeId, table) {
    const service = new google.maps.places.PlacesService(document.createElement('div'));
    service.getDetails({ placeId, fields: ['name', 'rating', 'user_ratings_total'] }, (place, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        const rating = place.rating;
        const numReviews = place.user_ratings_total;

        const ratingContainer = table.querySelector('.woocommerce-product-attributes-item--attribute_recensioner .woocommerce-product-attributes-item__value p');
        ratingContainer.innerHTML = `
          <div style="float:left;margin-right:10px;line-height:25px;padding:9px 4px;width:46px;height:46px;border:3px solid orange;border-radius:50%;color:orange;font-weight:bold;font-size:21px;">${(Math.round(rating * 10) / 10).toFixed(1)}</div> 
          <div style="line-height:19px;text-align:left;font-size: 24px;color: #FFC107;">${getStars(rating)}<br/>
            <img style="margin-right:5px;float:left;height:18px;" src="https://www.xn--jmfrflytt-v2a4r.se/wp-content/uploads/2017/11/google-1.png"> <span style="font-size: 18px;color: #444;">${numReviews} recensioner</span></div>
        `;
      }
    });
  }

  function getStars(rating) {
    const starTotal = 5;
    const roundedRating = Math.round(rating * 2) / 2;
    const stars = [];
    for (let i = 0; i < starTotal; i++) {
      if (i < Math.floor(roundedRating)) {
        stars.push('<i class="fa fa-star"></i>');
      } else if (i === Math.floor(roundedRating) && roundedRating % 1 !== 0) {
        stars.push('<i class="fa fa-star-half-o"></i>');
      } else {
        stars.push('<i class="fa fa-star-o"></i>');
      }
    }
    return stars.join('');
  }
</script>
