<?php

namespace Drupal\edlp_home\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Symfony\Component\HttpFoundation\JsonResponse;


class HomeController extends ControllerBase {

  /**
   * Display agenda as a page.
   *
   * @return renderable array
   */
  public function home() {

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

    $contents = array("#theme"=>'edlp_home');

    // presentation
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('nid', 12242);
    // TODO: présentation nid should be a setting

    $pres_nid = $query->execute();
    $contents["#presentation_node"] = entity_load('node', array_pop($pres_nid));

    // last fil
    // $query = \Drupal::entityQuery('node')
    //   ->condition('status', 1)
    //   ->condition('type', 'fil')
    //   ->sort('created', 'DESC')
    //   ->range(0,1);
    //
    // $fil = $query->execute();
    // $contents["#last_fil_node"] = entity_load('node', array_pop($fil));
    $contents["#last_fil_node"] = array('#markup'=>'En développement.');


    // last production
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'page')
      ->condition('field_page_type', array('1168'), 'NOT IN')
      ->sort('created', 'DESC')
      ->range(0,1);

    $prod = $query->execute();
    $contents["#last_production_node"] = entity_load('node', array_pop($prod));

    // agenda
    $now = new DrupalDateTime('now');
    $now->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'evenement')
      ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
      ->range(0,3)
      ->sort('field_date');

    $events = $query->execute();
    $contents['#agenda_items'] = entity_load_multiple('node', $events);

    return $contents;
  }

}
