<?php

/**
 * Map Block Template.
 *
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during backend preview render.
 * @param   int $post_id The post ID the block is rendering content against.
 *          This is either the post ID currently being displayed inside a query loop,
 *          or the post ID of the post hosting this block.
 * @param   array $context The context provided to the block by the post or it's parent block.
 */

// Support custom "anchor" values.
$anchor = '';
if (! empty($block['anchor'])) {
  $anchor = 'id="' . esc_attr($block['anchor']) . '" ';
}

// Load values and assign defaults.
$class_name = 'olympus-map';
$style = '';

$wrapper_attributes = get_block_wrapper_attributes(
  [
    'class' => $class_name,
    'style' => $style
  ]
);
$zoom = get_field('zoom');

// TODO: validate this block
// TODO: make sure API key used is OK
?>
<div <?php echo $anchor ?><?php echo $wrapper_attributes; ?>>
  <?php if (is_admin()): ?>
    <h4 style="color:orange;font-weight:300;">Note : the Google Map cannot be loaded in the backend. This is not an error.</h4>
  <?php else: ?>
    <div id="podio-map" style="height:100%;min-height:400px;"></div>
  <?php endif; ?>
</div>
<script>
  function initMap() {
    <?php
    $counter = 0;
    if (have_rows('markers')):
      while (have_rows('markers')) : the_row();
        $lat = get_sub_field('latitude');
        $long = get_sub_field('longitude');
        $marker_url = get_sub_field('marker_url');
    ?>
        <?php if ($counter == 0): ?>
          var map = new google.maps.Map(document.getElementById('podio-map'), {
            zoom: <?php echo $zoom ?>,
            center: {
              lat: <?php echo $lat ?>,
              lng: <?php echo $long ?>
            }
          });
        <?php endif; ?>
        let marker<?php echo '_' . $counter ?> = new google.maps.Marker({
          position: {
            lat: <?php echo $lat ?>,
            lng: <?php echo $long ?>
          },
          map: map,
          url: <?php echo ($marker_url) ? "'" . $marker_url . "'" : 'false' ?>
        });

        google.maps.event.addListener(marker<?php echo '_' . $counter ?>, 'click', function() {
          if (marker<?php echo '_' . $counter ?>.url) {
            window.open(marker<?php echo '_' . $counter ?>.url, "_blank");
          }
        });
    <?php
        $counter++;
      endwhile;
    endif;
    ?>
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCNS1LkP-U6Tngb9oArlJMzwgEiE5frMv4&callback=initMap">
</script>