<?php

namespace Drupal\restaurant_menus\Form;

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

class Additem 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 'menu_item_add';
  }

  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $takeaway = $this->conn->query("SELECT value FROM restaurant_settings WHERE name = ?", array('menutakeawayprice'))->fetchField();

    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#description' => $this->t('Please enter a name for your menu item'),
      '#required' => true
    ];

    $form['markup'] = array(
      '#markup' => '<br>'
    );

    $form['price'] = [
      "#type" => 'textfield',
      '#title' => $this->t('Price'),
      '#size' => 5,
      '#required' => true,
      '#description' => $this->t('Please enter a price for your menu item')
    ];

    if ($takeaway) {

      $form['markup2'] = array(
        '#markup' => '<br>'
      );

      $form['takewaway'] = [
        "#type" => 'textfield',
        '#title' => $this->t('Take Away Price'),
        '#size' => 5,
        '#description' => $this->t('Please enter a takeaway price for your menu item')
      ];
    }

    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Description'),
      '#description' => $this->t('Please enter a description for your menu item')
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add')
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $takeaway = $this->conn->query("SELECT value FROM restaurant_settings WHERE name = ?", array('menutakeawayprice'))->fetchField();
    $date = date('Y-m-d H:i:s');
    $item = array(
      'name' => $form_state->getValue('name'),
      'price' => number_format($form_state->getValue('price'), 2),
      'description' => $form_state->getValue('description'),
      'created' => $date,
      'modified' => $date,
      'section_id' => $this->getParam('sectionid')
    );
    if ($takeaway) {
      $item['price_takeaway'] = number_format($form_state->getValue('price_takeaway'), 2);
    }
    $this->conn->insert('restaurant_menu_items')->fields($item)->execute();

    $this->addMessage($this->t("Added menu item " . $form_state->getValue('name')))->http_redirect('/admin/restaurant/menu/' . $this->getParam('menuid'));
  }




}
