<?php

namespace Drupal\restaurant_bookings\Form\Ajax;

use 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 Times 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 'opening_times';
  }

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

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

      if (! \Drupal::currentUser()->isAuthenticated()) {
          header("HTTP/1.1 401 Unauthorized");
          exit;
      }
    }
    
    $session = $this->getSession();
    
    if ($this->hasParam('guests')) {
    	$session->set('guests', $this->getParam('guests'));
    }
   
    if ($this->hasParam('timestamp')) {
    	$session->set('date', $this->getParam('timestamp'));
    }
    
    if (strpos($_SERVER['REDIRECT_URL'], '/booking/ajax/day') !== false) {

    	$date = date('Y-m-d', $session->get('date'));

    } else {
    		if (date('n', time()) == date('n', $session->get('date'))) {
    		$date = date('Y-m-d', mktime(0,0,0, date('n', $session->get('date')), date('j', time()), date('Y', $session->get('date'))));
    	} else {
    		$date = date('Y-m-d', $session->get('date'));
    	} 
    }


   
    $bookings = new Booking(\Drupal::database());
    $times = $bookings->getTimes($date, false);
    $bookings->filterTimes($times, $date, $session->get('guests'));

    
    $values = [
        'times' => $times,
        'date' => $date
    ];

    FormElements::BookingTimes($form, $values, $this->inAdminPath());
    
    //return array('#markup' => 'what the');

    return $form;

  }

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

  }

}
