<?php

namespace Drupal\restaurant\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
* Provides a block with restaurant opening times
*
* @Block(
*   id = "restaurant_opening_times",
*   admin_label = @Translation("Restaurant Opening Times"),
* )
*/
class TimesBlock extends BlockBase
{

  public function build()
  {
    $db = \Drupal::database();

    $str = '<div id="opening-times">';
    $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

    $display = false;
    foreach ($days as $day) {
      $times = $db->query("SELECT * FROM restaurant_opening_times WHERE day = ? ORDER BY open ASC", array($day))->fetchAll();
      if (! empty($times)) {
        $display = true;
        $str .= '<div class="times-div">';
        $str .= '<h3 class="open-heading">' . $day . '</h3>';
        foreach ($times as $time) {
          $open = date('h:ia', strtotime($time->open));
          $close = date('h:ia', strtotime($time->close)) . '<br>';
          $str .= '<span class="times-span">' . $open . ' - ' . $close . '</span>';
        }
        $str .= '</div>';
      }
    }
    $str .= '</div>';

    $str = $display ? $str : '';

    return [
      '#type' => 'markup',
      '#markup' => $this->t($str),
    ];
  }
}
