<?php

namespace Drupal\erable_mod\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\Attribute\Block;
// use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\paragraphs\Entity\Paragraph;

/**
 * Provides a 'Sites Map' Block.
 * @Block(
 *   id = "sitesmap_block",
 *   admin_label = @Translation("Sites map Block"),
 * )
 */
class SitesMap extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $return = null;

    $allSites = \Drupal::entityTypeManager()->getStorage('node')
          ->loadByProperties(['type' => 'projet', 'status' => 1]);

    $intro_text = \Drupal::entityTypeManager()->getStorage('config_pages')
          ->load('2')->get('field_intro')-> value;

    $sites_paths = "";

    foreach($allSites as $index => $site){
      
      // Check if the node has the paragraph field and it's not empty.
      if ($site->hasField('field_carte') && !$site->get('field_carte')->isEmpty()) {
        // Iterate through the referenced paragraph entities.
        foreach ($site->get('field_carte')->referencedEntities() as $carte_paragraph) {
          if ($carte_paragraph instanceof Paragraph) {
            $geofield = $carte_paragraph->get('field_carte');
            $principal = $carte_paragraph->get('field_principal')->value;

            if ($geofield && $principal) {

              $title = $site->get('title')->getString();
              $subtitle = $site->get('field_sous_titre')->getString();
              $place = $site->get('field_localisation_textuel')->getString();
      
              $link_options = ['absolute' => FALSE, 'attributes' => ['class' => 'site-link']];
              $site_link_object = Link::createFromRoute("voir le site", 'entity.node.canonical', ['node' => $site->id()], $link_options);
              $href = $site_link_object->getUrl()->toString();
      
              $lon = $geofield->lon;
              $lat = $geofield->lat;
      
              $svg_template_path = DRUPAL_ROOT . '/modules/custom/erable_mod/assets/svg/feuille.svg';
              $svg_template= file_get_contents($svg_template_path);
              $sites_paths .= str_replace(
                ['$index', '$lon', '$lat', '$href', '$title', '$place'],
                [$index, $lon, $lat, $href, $title, $place],
                $svg_template
              );

              break;
            }
          }
        }
      }

        


      
    }

    $return = [
      '#cache' => [
        'max-age' => 0,
      ],
      'svg_mapsites' => [
        '#theme' => 'svg_mapsites',
        '#sites' => $sites_paths,
        '#intro' => $intro_text,
        '#attached' => [
          'library' => [
            'erable_mod/sites_map_block',
          ],
        ],
      ]
    ];

    return $return;
  }
  public function getCacheMaxAge() {
    return 0;
  }
}
