<?php

namespace Drupal\restaurant_menus\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\restaurant\Form\AppForm;

class Showmenu extends AppForm {

  /**
   * Returns a unique string identifying the form.
   *
   * The returned ID should be a unique string that can be a valid PHP function
   * name, since it's used in hook implementation names such as
   * hook_form_FORM_ID_alter().
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'get_menu_item';
  }

  public function buildForm(array $form, FormStateInterface $form_state)
  {

    $sql = "SELECT * FROM restaurant_menus WHERE active = ?";

    $options = $this->conn->query("SELECT id, name FROM restaurant_menus WHERE active = ?", array(1))->fetchAllKeyed();

    if (sizeof ($options) > 1) {

      $default = (isset ($_GET['menuid'])) ? $_GET['menuid'] : 0;

      $form['options'] = array(
        '#type' => 'select',
        '#options' => $options,
        '#attributes' => array('class' => array('menuselect')),
        '#default_value' => $default
      );


    }

    $sql = "SELECT * FROM restaurant_menus WHERE active = ?";

    if (isset ($_GET['menuid'])) {
      $sql .= " AND id = ?";
      $menu = $this->conn->query($sql, array(1, $_GET['menuid']))->fetch();


    } else {

      $sql .= " LIMIT 1";
      $menu = $this->conn->query($sql, array(1))->fetch();

    }

    if (empty ($menu)) {

      $form['html'] = array(
      '#type' => 'markup',
      '#markup' => t('<p>No active menus found</p>')
      );

      return $form;
    }


    $html = '<div id="menu">';

      $html .= '<h1>' . $menu->name . '</h1>';


      $sections = $this->conn->query("SELECT * FROM restaurant_menu_sections WHERE menu_id = ?", array($menu->id))->fetchAll();

      foreach ($sections as $section) {


        $html .= '<h2>' . $section->name . '</h2>';

        $items = $this->conn->query("SELECT * FROM restaurant_menu_items WHERE section_id = ?", array($section->id))->fetchAll();

        foreach ($items as $item) {


          $html .= '<table class="itemtable">';

            $html .= '<tr>';

              $html .= '<td class="itemname"><h3>' . $item->name . '</h3></td>';

              $html .= '<td class="itemprice">$ ' . number_format($item->price, 2) . '</td>';

            $html .= '</tr>';

            $html .= '<tr>';

              $html .= '<td colspan="2" class="item-description"><p>' . $item->description . '</p></td>';

            $html .= '</tr>';

          $html .= '</table>';

        }


      }

    $html .= '</div>';


    $form['html'] = array(
      '#type' => 'markup',
      '#markup' => t($html)
    );

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
  }




}
