<?php

namespace Drupal\q2d_mod\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\Attribute\Block;
// use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;

/**
 * Provides a 'Sites Map' Block.
 * @Block(
 *   id = "galeriephotomap_block",
 *   admin_label = @Translation("Galerie Photo map Block"),
 * )
 */
class GaleriePhotoMap extends BlockBase {
 
  /**
   * {@inheritdoc}
   */
  public function build() {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

    $return = null;

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

    $vp_w = 600;
    $vp_h = 600;

    // Charger toutes les ressources de type "Mission photo" (type de ressource = 17)
    $all_mission_photos = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'type' => 'ressource',         // adapte si ton type machine est différent
        'status' => 1,
        'field_type_de_ressource' => 17, // même ID que dans la query de la vue
      ]);

      // Indexer les missions photo par ID de site
      $mission_by_site = [];

      foreach ($all_mission_photos as $mission) {
      if (!$mission->hasField('field_site') || $mission->get('field_site')->isEmpty()) {
        continue;
      }

      // Un même node peut être lié à plusieurs sites : on en prend un par site
      foreach ($mission->get('field_site') as $ref) {
        $site_id = $ref->target_id;

        if (!isset($mission_by_site[$site_id])) {
          $mission_by_site[$site_id] = $mission;
        }
      }
    }


    // Coordonnées géographiques des coins de la carte (France)
    $latTop = 52.0; // Nord-Ouest (coin supérieur gauche)
    $lonLeft = -6.0;
    $latBottom = 40.0; // Sud-Est (coin inférieur droit)
    $lonRight = 11.0;
    
    
    foreach($allSites as $index => $site){
      $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
      
      
      // /ressources?field_type_de_ressource_target_id[]=17&combine=&field_tous_les_sites_value=All&field_site_target_id_verf[]=37
      $query = [
        'field_type_de_ressource_target_id[]' => 17, # fixed to galeries_photos
        'combine' => '',
        'field_tous_les_sites_value' => 'All',
        'field_site_target_id_verf[]' => $site->id(),
      ];
      $url = Url::fromRoute('view.ressources.page_1', [], ['query' => $query])->toString();
      

      // $title = $site->get('title')->getString();
      $title = $site->hasTranslation($language) ? $site->getTranslation($language)->get('title')->getString() : $site->get('title')->getString();
      // $subtitle = $site->get('field_sous_titre')->getString();
      $subtitle = $site->hasTranslation($language) ? $site->getTranslation($language)->get('field_sous_titre')->getString() : $site->get('field_sous_titre')->getString();

      // URL directe de la mission photo liée à ce site (si trouvée)
      $mission_photo_url = '';

      if (isset($mission_by_site[$site->id()])) {
        $mission_node = $mission_by_site[$site->id()];

        // Respecter la langue courante si traduction existe
        if ($mission_node->hasTranslation($language)) {
          $mission_node = $mission_node->getTranslation($language);
        }

        $mission_photo_url = $mission_node->toUrl('canonical', [
          'absolute' => TRUE,
          'language' => \Drupal::languageManager()->getLanguage($langcode),
        ])->toString();
      }


      $link_options = ['absolute' => TRUE, 'attributes' => ['class' => 'ressource-link'], 'language' => \Drupal::languageManager()->getLanguage($langcode)]; // Passer 'absolute' à TRUE
      // $site_url = $site->toUrl('canonical', $link_options)->toString(); // URL absolue pour le data-url
      $site_link_object = Link::createFromRoute(t("Voir le site"), 'entity.node.canonical', ['node' => $site->id()], $link_options);
      $link = $site_link_object->toString()->getGeneratedLink();

      $datacontent = htmlspecialchars("<strong>$title</strong><br>$subtitle<br>$link");      

      $geofield = $site->get('field_geofield')->get(0);
      $lon = $geofield->lon;
      $lat = $geofield->lat;
      $geofieldData = "$lon,$lat"; // Utiliser une chaîne pour stocker la position

      $x = round(($lon - $lonLeft) / ($lonRight - $lonLeft) * $vp_w);
      $y = round(($latTop - $lat) / ($latTop - $latBottom) * $vp_h);

      $r = 12;
      $m = -$r/1.5+3;
      $l = $r/1.5 +2.5;
      $sites_paths .= <<<SVGSITEPATH
      <g 
        id="site-$index"
        data-geofield="$geofieldData"
        transform="translate($x,$y)"
        style="cursor: pointer;"  <!-- Change le curseur pour indiquer l'interaction -->
      >
          <a href="$url">
            <rect width="10" height="10" transform="translate($x,$y)" fill="none" onclick="handleCircleClick('$datacontent')"></rect>
           <!-- Zone d'interaction invisible -->
         
            <circle
            class="site-link"
            data-content="$datacontent" 
            data-url="$url"
            data-mission-photo-url="$mission_photo_url"
            cx="0" cy="0" r="$r"
            style="fill-opacity:1;fill-rule:nonzero;" />
          <path
            id="path84"
            d="m 0,$m v $l"
            style="pointer-events: none;fill:none;stroke:#ffffff;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" />
          <path
            id="path85"
            d="m $m,0 h $l"
            style="pointer-events: none;fill:none;stroke:#ffffff;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1" />
          </a> 
      </g>
      SVGSITEPATH;
    }
    

    $return = [
      '#cache' => [
        'max-age' => 0,
      ],
      'svg_mapsites' => [
        '#theme' => 'svg_mapgaleries',
        '#label' => "Voir les autres galeries photos",
        '#sites' => $sites_paths,
        '#vpw' => $vp_w,
        '#vph' => $vp_h,
        '#attached' => [
          'library' => [
            'q2d_mod/sites_map_block',
          ],
        ],
      ]
    ];

    return $return;
    // return [
    //   '#markup' => $this->t('Hello, Sites Map!'),
    // ];
  }
  
  public function getCacheMaxAge() {
    return 0;
  }
}