<?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\Link;
use Drupal\Core\Render\Markup;

/**
 * Provides a 'Prevnext' Block.
 * @Block(
 *   id = "prevnext_block",
 *   admin_label = @Translation("PrevNext Block"),
 * )
 */
class PrevNext extends BlockBase {
 
  /**
   * {@inheritdoc}
   */
  public function build() {
    $return = null;
    /** @var Drupal\node\Entity\Node */
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node) {
      $nodetype = $node->getType();
      if($nodetype === "actualite"){
        $date = $node->get('field_date')->getString();
        $allActus = \Drupal::entityTypeManager()->getStorage('node')
          ->loadByProperties(['type' => 'actualite', 'status' => 1]);
  
        
  
        usort($allActus, function($a, $b){
          $dateA = $a->get('field_date')->getString();
          $dateB = $b->get('field_date')->getString();
          if ($dateA == $dateB) {
              return 0;
          }
          return ($dateA < $dateB) ? -1 : 1;
        });
        $prevnode = null;
        $nextnode = null;
        foreach($allActus as $index => $actu){
          $n = $actu->get('field_date')->getString();
          if($n === $date){
            $prevnode = $index - 1 >= 0 ? $allActus[$index - 1] : null;
            $nextnode = $index + 1 < count($allActus) ? $allActus[$index + 1] : null;
            break;
          }
        }
  
        $return = [
          '#cache' => [
            'max-age' => 0,
          ]
        ];
    
        if (isset($prevnode)) {
          $prev_link_title = Markup::create('<span>Précédent</span>');
          $prev_options = ['absolute' => FALSE, 'attributes' => ['class' => 'prev-actu']];
          $prev_link_object = Link::createFromRoute($prev_link_title, 'entity.node.canonical', ['node' => $prevnode->id()], $prev_options);
          $return[] = $prev_link_object->toRenderable();
        }
    
        if (isset($nextnode)) {
          $next_link_title = Markup::create('<span>Suivant</span>');
          $next_options = ['absolute' => FALSE, 'attributes' => ['class' => 'next-actu']];
          $next_link_object = Link::createFromRoute($next_link_title, 'entity.node.canonical', ['node' => $nextnode->id()], $next_options);
          $return[] = $next_link_object->toRenderable();
        }
      }
    }
    
    return $return;
    // return [
    //   '#markup' => $this->t('Hello, World!'),
    // ];
  }
  public function getCacheMaxAge() {
    return 0;
  }
}