<?php

namespace Drupal\restaurant_settings\Form;

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

class Addtable 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 'add_table';
  }

  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $num = (int)$this->conn->query("SELECT MAX(increment) FROM restaurant_tables")->fetchField();
    $num++;

    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Table name'),
      '#description' => $this->t('Please enter a name for the table'),
      '#required' => true,
      '#placeholder' => 'eg Table 1',
      '#size' => 30,
      '#default_value' => 'Table ' . $num
    );

    $form['guests'] = array(
      '#type' => 'number',
      '#title' => $this->t('guests'),
      '#required' => true,
      '#description' => 'Maximum number of guests at the table',
      '#default_value' => 2
    );

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

    return $form;
  }


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

    $num = (int)$this->conn->query("SELECT MAX(increment) FROM restaurant_tables")->fetchField();
    $num++;

    $data = array(
      'increment' => $num,
      'name' => $_POST['name'],
      'number' => $_POST['guests'],
      'diningarea_id' => 1
    );

    $this->conn->insert('restaurant_tables')->fields($data)->execute();
    $this->addMessage("Saved table")->http_redirect('/admin/restaurant/settings/tables');
  }

}
