<?php

namespace Drupal\restaurant_bookings\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\restaurant\Form\AppForm;
use Drupal\restaurant\Bookings\Booking;
use Symfony\Component\HttpFoundation\Session\Session;
use Drupal\restaurant\Form\MultipartForm;

use Drupal\restaurant_bookings\Form\FormElements;
use Drupal\restaurant\Form\Heading;




/**
* BOOKINGS FORM STEP 1
*/
class Addbooking extends MultipartForm
{
  /**
   * 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_booking2';
  }

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

    if ($this->getSetting('requirelogin')) {

      if (! \Drupal::currentUser()->isAuthenticated()) {
        $this->addMessage($this->t('Login required to make a booking'), 'error')->http_redirect('/user/login');
      }
    }
    if ($this->inAdminPath()) {
        Heading::addHeading($form, 'Create booking');
    }


    FormElements::Calendar($form);
    FormElements::Guests($form);
    FormElements::Submit($form, array('value' => 'Next'));

    return $form;

  }

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

    $bookings = new Booking($this->conn);
    $date = $form_state->getValue('date');
    $times = $bookings->getTimes($date, true);

    $bookings->filterTimes($times, $date, $form_state->getValue('guests'));



    if (! empty ($times)) {

      /*if (! empty ($times[$_POST['service']]['Times'])) {
        $this->store->set('times', $times[$_POST['service']]['Times']);
      } */
      if (! empty ($form_state->getValue('guests'))) {
        $this->store->set('guests', $form_state->getValue('guests'));
      }
      if (! empty ($form_state->getValue('date'))) {
        $this->store->set('date', $form_state->getValue('date'));
      }
      if (! empty ($form_state->getValue('service'))) {
        $this->store->set('service', $form_state->getValue('service'));
      }

      if ($this->inAdminPath()) {
        $this->http_redirect('/admin/restaurant/bookings/times');
      } else {
        $this->http_redirect('/bookings/selecttime');
      }
    } else {
      \Drupal::messenger()->addMessage('No times are available for the date you selected');
      //mydump (get_class_methods(get_class($this)));
      //$this->addMessage(t(""), "error");
    }
  }

}
