<?php

namespace Drupal\restaurant_settings\Form;

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



class Openingtimes extends AppForm {

    private $count = 0;

  /**
   * 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_form';
  }

  private function openingTimes(&$form, $day = '', $i = '', $values = array())
  {

    $name = 'name' . $day . $i;
    $open = 'open' . $day . $i;
    $close = 'close' . $day . $i;

    //mydump ($close);

    //$value_open = (isset ($values['open'])) ? date('H:i A', strtotime($values['open'])) : '';
    //$value_close = (isset ($values['close'])) ? date('H:i A', strtotime($values['close'])) : '';

    $value_open = (isset ($values->open)) ? date('H:i', strtotime($values->open)) : '';
    $value_close = (isset ($values->close)) ? date('H:i', strtotime($values->close)) : '';

    $form[$name] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#size' => 15,
      '#attributes' => array('placeholder' => 'eg Lunch'),
      //'#default_value' => $values->name
      '#default_value' => (! empty ($values->name)) ? $values->name : ''
    );

    $form[$open] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Open'),
      '#size' => 15,
      '#attributes' => array('class' => array('timepicker'), 'autocomplete' => 'off'),
      '#default_value' => $value_open
    );

    $form[$close] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Close'),
      '#size' => 15,
      '#attributes' => array('class' => array('timepicker'), 'autocomplete' => 'off'),
      '#default_value' => $value_close
    );

    $form['clear' . $this->count] = array(
        '#markup' => $this->t('<div class="clear3" style="clear: both;"></div>')

    );
    $this->count++;
  }

  private function Exceptions(&$form, $i, $values = array())
  {

    $name_value = (isset ($values->name)) ? $values->name : '';
    $date = (isset ($values->from_date)) ? date('Y-m-d', strtotime($values->from_date)) : '';
    //$fromtime = (isset ($values['from_date'])) ? date('H:i A', strtotime($values['from_date'])) : '';
    //$totime = (isset ($values['to_date'])) ? date('H:i A', strtotime($values['to_date'])) : '';
    $fromtime = (isset ($values->from_date)) ? date('H:i', strtotime($values->from_date)) : '';
    $totime = (isset ($values->to_date)) ? date('H:i', strtotime($values->to_date)) : '';
    $type = (isset ($values->type)) ? $values->type : '';





    $form["exception[name][$i]"] = array(
      '#type' => 'textfield',
      '#placeholder' => 'eg Christmas day',
      '#title' => 'Name',
      '#default_value' => $name_value,
      '#size' => 15
    );

    $form["exception[date][$i]"] = array(
      '#type' => 'date',
      '#title' => 'Date',
      '#default_value' => $date,
      '#size' => 15
    );

    $form["exception[from][$i]"] = array(
      '#type' => 'textfield',
      '#title' => 'From',
      '#attributes' => array('class' => array('timepicker'), 'autocomplete' => 'off'),
      '#default_value' => $fromtime,
      '#size' => 15
    );

    $form["exception[to][$i]"] = array(
      '#type' => 'textfield',
      '#title' => 'To',
      '#attributes' => array('class' => array('timepicker'), 'autocomplete' => 'off'),
      '#default_value' => $totime,
      '#size' => 15
    );

    $form["exception[type][$i]"] = array(
      '#type' => 'select',
      '#title' => $this->t('Type'),
      '#options' => array(
        'open' => 'open',
        'close' => 'close'
      ),
      '#default_value' => $type
    );



  }

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

      $days = self::getDays();

      $form['element'] = array(
          '#type' => 'hidden',
          '#value' => 'hide'
      );

      $html = '<p>Setup opening times for your restaurant. To remove a service time, leave the opening, closing or name fields blank (all fields are required for a time to get saved).</p>';

      foreach ($days as $key => $val) {
          $html .= '<div class="box">';
          $html .= '<div class="label">' . $val . '</div>';

          $form['markup1' . $val] = array(
              "#markup" => $this->t($html)
          );



          $i = 0;
          $times = $this->conn->query("SELECT * FROM restaurant_opening_times WHERE day = ? ORDER BY open ASC", array($val))->fetchAll();

          foreach ($times as $time) {
              $this->openingTimes($form, $val, $i, $time);

              $form['markup0' . $val . $i] = array(
                  "#markup" => '<div class="clear">&nbsp;</div>'
              );

              $i++;
          }

          $form['markup0' . $val . $i] = array(
              "#markup" => '<div class="clear">&nbsp;</div>'
          );



          for ($i; $i<1; $i++) {

              $this->openingTimes($form, $val, $i);

              $form['markup2' . $val . $i] = array(
                  "#markup" => '<div class="clear">&nbsp;</div>'
              );
          }

          if ($i >= 1) {
              $i++;

              $this->openingTimes($form, $val, $i);

          }

          $html = '</div>';
          //$form['markup2' . $val] = array('#markup' => $html);
      }

      $html = '<div class="box"><div class="label">Exceptions</div>';
      $html .= '<p style="font-weight: normal">Exceptions cover closing on days such as public holidays where your restaurant would otherwise be open, or times you are open that you would ordinarily be closed. Note that closing times take precedence over opening times ie if you have two exceptions for a single day, one opening and one closing the restaurant, the restaurant will be closed and you won\'t be able to take bookings in that period. To open or close for en entire day, set \'from\' time';
      $html .= ' to 12:00 AM and \'to\' time to 11:59 PM.</p>';

      $form['markupExceptions1'] = array(
          "#markup" => $html
      );

      $i = 0;

      $exceptions = $this->conn->query("SELECT * FROM restaurant_opening_exceptions")->fetchAllAssoc('id');

      foreach ($exceptions as $exception) {

          $this->Exceptions($form, $i, $exception);

          $form['markup3' . $val . $i] = array(
              "#markup" => '<div class="clear">&nbsp;</div>'
          );

          $i++;
      }

      for ($i; $i<2; $i++) {

          $this->Exceptions($form, $i);

          $form['markup3' . $val . $i] = array(
              "#markup" => $this->t('<div class="clear">&nbsp;</div>')
          );
      }

       $form['markup4'] = array(
              "#markup" => $this->t('<div class="clear">&nbsp;</div><br>')
        );

      $form['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Save'),
          '#attributes' => array('style' => array('clear: both !important'))
      ];

      $form['markupExceptions2'] = array(
          "#markup" => '</div><br><br>'
      );

      return $form;
  }

  public static function getDays()
	{
		return array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
	}

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $days = self::getDays();
    $bookings = array();

    $exception = $_POST['exception'];

    if ((isset ($_POST['element']) && ($_POST['element'] == 'hide'))) {

      $this->conn->delete('restaurant_opening_exceptions')->execute();
      foreach ($exception['name'] as $key => $val) {

          if (! empty ($val)) {

            if ((! empty ($exception['from'][$key])) && (! empty ($exception['to'][$key])) && (! empty ($exception['name'][$key]))) {

              $data = array(
              'name' => $exception['name'][$key],
              'type' => $exception['type'][$key],
              'from_date' => $exception['date'][$key] . ' ' . date('H:i', strtotime($exception['from'][$key])) . ':00',
              'to_date' => $exception['date'][$key] . ' ' . date('H:i', strtotime($exception['to'][$key])) . ':59'
            );
            $this->conn->insert('restaurant_opening_exceptions')->fields($data)->execute();
          }

        }
      }

      /** bookings */
      foreach ($days as $day) {
        foreach ($_POST as $key => $val) {
          $tokens = array('form_build_id', 'form_token', 'form_id', 'op');
          if (in_array($key, $tokens)) {
            continue;
          }

          if (strpos($key, $day) !== false) {
            if (! isset ($bookings[$day])) {
              $bookings[$day] = array();
            }
            preg_match('/[0-9]+/', $key, $matches);
            $num = $matches[0];
            $bookings[$day][$num] = array();
          }
        }
      }

      $this->conn->delete('restaurant_opening_times')->execute();

      $rows = 0;


      foreach ($bookings as $key => $val) {
        foreach ($val as $k => $v) {
          $data = array();
          $data['day'] = $key;
          $data['name'] = $_POST['name' . $key . $k];
          $open = $_POST['open' . $key . $k];
          $close = $_POST['close' . $key . $k];

          if ((! empty ($data['name'])) && (! empty ($close)) && (! empty  ($open))) {
            $open = strtotime($open);
            $close = strtotime($close);

            $data['open'] = date('H:i:s', $open);
            $data['close'] = date('H:i:s', $close);

            $this->conn->insert('restaurant_opening_times')->fields($data)->execute();
          }
        }
      }

      //if ($rows == 0) {}

      $this->conn->delete('restaurant_bookings_cache')->execute();
    }

  }



}
