<?php

namespace Drupal\restaurant_bookings\Form;
use Drupal\restaurant\Bookings\Booking;

class FormElements
{
    public static function BookingDate(&$form, array $values = array())
    {
        $values['time'] = (isset ($values['time'])) ? $values['time'] : time();

        $html = '<div id="booking-time">';
        $html .= '<dl>';

        $html .= '<dt>Booking Date</dt>';
        $html .= '<dd>' . date('d/m/Y', $values['time']) . '</dd>';

        $html .= '<dt>Booking Time</dt>';
        $html .= '<dd>' . date("H:i", $values['time']);

        $html .= '</dl>';

        $html .= '</div>';

        $form['html'] = [
            '#type' => 'markup',
            '#markup' => $html
        ];
        return $form;
    }

    /*Warning: foreach() argument must be of type array|object, string given in Drupal\restaurant_bookings\Form\FormElements::BookingTimes() (line 74 of modules/RestaurantHQ/restaurant_bookings/src/Form/FormElements.php).*/



    public static function BookingTimes(&$form, array $values = array(), $inAdmin = false)
    {
        $db = \Drupal::database();

        //mydump ($values, false);

        $return = false;
        if (isset ($values['times'])) {
            if (empty ($values['times'])) {
                $return = true;
            }
        } else {
            $return = true;
        }
        if ($return) {
            $html = t('<h2 class="times-heading">No times available for:  ' . date('l jS F Y', strtotime($values['date'])) . '</h2>');
            $form['mymarkup'] = array(
                '#markup' => $html
            );
            return $form;
        }

        $url = ($inAdmin) ? '/admin/restaurant/bookings/data/' : '/booking/ajax/data/';

        $html = '';
        $html .= ($inAdmin) ? t('<h2 class="times-heading">Select a time for ' . date('l jS F Y', strtotime($values['date'])) . '</h2>') : '';
        //$html .= '<h2 class="times-heading">Select a time for ' . date('l jS F Y', strtotime($values['date'])) . '</h2>';


        $html .= '<div id="times-wrap">';

        foreach ($values['times'] as $key => $val) {

            $html .= '<h2 class="service-heading">' . $key . '</h2>';

            $html .= '<div class="times-links">';

            if (! empty ($val)) {
                foreach ($val as $k => $v) {

                    if (! empty ($v)) {

                       $type = gettype($v);
                       if (gettype($v) == 'array') {

                         foreach ($v as $t => $time) {

                          $datepart = strtotime($values['date']);
                          $timepart = strtotime($time);
                          $timestamp = mktime(date('H', $timepart), date('i', $timepart), 0, date('m', $datepart), date('d', $datepart), date('Y', $datepart));

                          $html .= '<a class="select-time2" href="' . $url . $timestamp .'">' . $time . '</a>';
                        }


                      }

                    }

                }
            }

            $html .= '</div><br>';
        }
        $html .= '</div><!-- end times-wrap -->';

        $form['mymarkup'] = array(
            '#markup' => t($html)
        );
        return $form;
    }

    public static function TimesSelect(&$form, $value = '')
    {
    		$value = (! empty ($value)) ? date('H:i', strtotime($value)) : date('H:i', time());
    		$form['time'] = array(
      		'#type' => 'textfield',
      		'#title' => t("Time"),
      		'#description' => t("Select a time"),
      		'#attributes' => array('class' => array('timepicker'), 'autocomplete' => 'off'),
      		'#size' => 15,
      		'#default_value' => $value
    	   );
    	 	return $form;
    }

    public static function TableSelect(&$form, $bookingid = '')
    {
    		$db = \Drupal::database();
    		$tables = $db->query("SELECT id, name, number FROM restaurant_tables")->fetchAll();
    		$table = array();
    		foreach ($tables as $val) {
      		$table[$val->id] = $val->name . ' (seats ' . $val->number . ')';
    		}

    		$select = $db->query("SELECT table_id FROM restaurant_bookings_tables WHERE booking_id = ?", array($bookingid))->fetchCol();

    		$form['tables'] = array(
      		'#type' => 'select',
      		'#title' => t("Table"),
      		'#description' => t("Choose your table(s)"),
      		'#options' => $table,
      		'#multiple' => true,
      		'#size' => 8,
      		'#width' => 20,
      		'#default_value' => $select
    		);

    		return $form;

    }

    public static function Calendar(&$form, $value = '')
    {
        $db = \Drupal::database();
        $value = (! empty ($value)) ? $value : date('Y-m-d');

        $form['date'] = array(
            '#type' => 'date',
            '#title' => t('Booking Date'),
            '#required' => true,
            '#format' => 'Y-m-d',
            '#default_value' => $value
        );
        return $form;
    }

    public static function Details(&$form, array $values = array(), array $descriptions = array(), $message = null)
    {
    	$required = true;

      $isadmin = false;
      if (strpos($_SERVER['REQUEST_URI'], '/admin') !== false) {
        $isadmin = true;
      }

      //$isadmin = ($_SERVER['REQUEST_URI']);
        if (! empty ($message)) {
            $form['message'] = array(
                '#type' => 'markup',
                '#markup' => t('<div style="color: red;">' . $message . '</div>')
            );
        }
        $options = array(
            'Mr' => 'Mr',
            'Mrs' => 'Mrs',
            'Miss' => 'Miss',
            'Ms' => 'Ms',
            'Dr' => 'Dr'
        );
        $form['title'] = array(
            '#type' => 'select',
            '#options' => $options,
            '#title'   => t('Title'),
            '#description' => isset($descriptions['title']) ? $descriptions['title'] : '',
            '#default_value' => isset ($values['title']) ? $values['title'] : ''

        );

        $default = (isset ($values['email'])) ? $values['email'] : '';
        $span = 'Email';
        if ($required) {
          if (! $isadmin) {
            $span = ($required) ? 'Email <span class="req">*</span>' : 'Email';
          }
        }
        $form['email'] = array(
            '#type' => 'email',
            '#title' => t($span),
            '#description' => isset($descriptions['email']) ? $descriptions['email'] : '',
            '#default_value' => t($default),
            '#required' => $required
        );

        $default = (isset ($values['firstname'])) ? $values['firstname'] : '';
        $span = 'Firstname';
        if ($required) {
          if (! $isadmin) {
            $span = ($required) ? 'Firstname <span class="req">*</span>' : 'Firstname';
          }
        }
        $form['firstname'] = array(
            '#type' => 'textfield',
            '#description' => isset($descriptions['firstname']) ? $descriptions['firstname'] : '',
            '#title' => t($span),
            '#default_value' => t($default),
            '#required' => $required
        );

        //$default = (isset ($values['lastname'])) ? $values['lastname'] : '';
        //$span = ($required) ? 'Lastname <span class="req">*</span>' : 'Lastname';

        $default = (isset ($values['lastname'])) ? $values['lastname'] : '';
        $span = 'Lastname';
        if ($required) {
          if (! $isadmin) {
            $span = ($required) ? 'Lastname <span class="req">*</span>' : 'Lastname';
          }
        }
        $form['lastname'] = array(
            '#type' => 'textfield',
            '#description' => isset($descriptions['lastname']) ? $descriptions['lastname'] : '',
            '#title' => t($span),
            '#default_value' => t($default),
            '#required' => $required
        );

        //$default = (isset ($values['phone'])) ? $values['phone'] : '';
        //$span = ($required) ? 'Phone <span class="req">*</span>' : 'Phone';

        //$default = (isset ($values['phone'])) ? $values['phone'] : '';
        $default = (isset ($values['phone'])) ? $values['phone'] : '';
        $span = 'Phone';
        if ($required) {

          if (! $isadmin) {
            $span = ($required) ? 'Phone <span class="req">*</span>' : 'Phone';
          }
        }
        $form['phone'] = array(
            '#type' => 'tel',
            '#description' => isset($descriptions['phone']) ? $descriptions['phone'] : '',
            '#title' => t($span),
            '#default_value' => t($default),
            '#required' => $required
        );


        $default = (isset ($values['company'])) ? $values['company'] : '';
        $form['company'] = array(
           '#type' => 'textfield',
           '#description' => isset($descriptions['company']) ? $descriptions['company'] : '',
           '#title' => t("Company"),
           '#default_value' => t($default),
        );

        return $form;
    }

    public static function Buttons(&$form, $timestamp = '')
    {
        $array = array();
        $parts = explode('/', $_SERVER['REQUEST_URI']);
        foreach ($parts as $val) {
            if ((! is_numeric($val)) && (! empty ($val))) {
                $array[] = $val;
            }
        }
        $uri = '/' . implode('/', $array);

        $timestamp = (empty($timestamp)) ? time() : $timestamp;

		$nexttext = 'Continue';

        switch ($uri) {

            case '/booking/ajax/data':

                $backlink = '/booking/ajax/day/';
                $backlinkclass = array('buttons', 'left-button', 'active-button');
                $nextclass = array('buttons', 'right-button', 'active-button');
                $nextlink = '/booking/ajax/data/';

                break;

            case '/booking/ajax/day':

                $backlink = '/booking/ajax/data/';
                $backlinkclass = array('buttons', 'left-button', 'active-button');
                $nextclass = array('buttons2', 'right-button', 'active-button');
                $nextlink = '/booking/ajax/data/';

                break;

            case '/booking/ajax/requirements':

                $backlink = '/booking/ajax/data/';
                $backlinkclass = array('buttons', 'left-button', 'active-button');
                $nextclass = array('buttons2', 'right-button', 'active-button');
                $nextlink = '/booking/ajax/requirements/';

                break;

			case '/booking/ajax/summary':

				$backlink = '/booking/ajax/requirements/';
				$backlinkclass = array('buttons', 'left-button', 'active-button');
				$nextclass = array('buttons2', 'right-button', 'active-button');
				$nextlink = '/booking/ajax/booking/';
				$nexttext = 'Book';

				break;

            default:
               $backlink = '/booking/ajax/data/';
               $backlinkclass = array('buttons', 'left-button', 'active-button');
               $nextclass = array('buttons2', 'right-button', 'active-button');
               $nextlink = '/booking/ajax/data/';
        }



        $form['topdiv'] = array(
            '#type' => 'markup',
            '#markup' => '<div id="buttons-div">'
        );

        //$timestamp = date('Y-m-d', $timestamp);

        $str = '<a class="' . implode(' ', $backlinkclass) . '" href="' . $backlink . $timestamp . '">Back</a>';
        $form['leftlink'] = array(
            '#type' => 'markup',
            '#markup' => $str
        );


        $str = '<a id="submit-details-button" class="' . implode(' ', $nextclass) . '" href="' . $nextlink . $timestamp . '">' . $nexttext . '</a>';
        $form['rightlink'] = array(
            '#type' => 'markup',
            '#markup' => $str
        );


        $form['clear'] = array(
            '#type' => 'markup',
            '#markup' => '<div style="clear: both;"></div>'
        );


        $form['buttons'] = array(
            '#type' => 'markup',
            '#markup' => t('</div>')
        );

    	return $form;
    }

    public static function Emailconfirmation(&$form, array $values = array())
    {
        $form['emailconfirmation'] = array(
            '#type' => 'checkbox',
            '#title' => t('Send email confirmation'),
            '#default_value' => 1,
        );

        return $form;
    }

    public static function Guests(&$form, $value = '', $options = array())
    {
        $db = \Drupal::database();

		  $guests = (! empty ($value)) ? $value : 2;
		  $title = (isset ($options['title'])) ? $options['title'] : 'Guests';

        $form['guests'] = array(
            '#width' => 100,
            '#type' => 'number',
            '#title' => t($title),
            '#min' => 1,
            '#max' => $db->query("SELECT value FROM restaurant_settings WHERE name = ?", array('maxbookings'))->fetchField(),
            '#attributes' => array('class' => array('edit-guests')),
            '#required' => false,
            '#default_value' => $guests
        );

        return $form;
    }

    public static function Notes(&$form, $bookingid = '', $checked = '')
    {
        $db = \Drupal::database();
        $requirements = $db->query("SELECT * FROM restaurant_requirements")->fetchAll();

        $selected = array();
        $requirement = '';
        if (! empty ($bookingid)) {
        		$selected = $db->query("SELECT requirement_id FROM restaurant_bookings_requirements WHERE booking_id = ?", array($bookingid))->fetchCol();
        		$requirement = $db->query("SELECT requirements FROM restaurant_bookings WHERE id = ?", array($bookingid))->fetchField();
        }

        $label = (empty ($requirements)) ? '<div id="textarea-label"><br>Special Requirements</div>' : '<br><div id="textarea-label">Other: Please Specify</div>';

        $textarea = '';
        if (!empty ($checked)) {
            $textarea = (isset ($checked['textarea'])) ? $checked['textarea'] : $requirement;
            if (empty ($selected)) {
                $selected = $checked['selected'];
            }
        }


        if (! empty($requirements)) {

            $options = array();
            foreach ($requirements as $val) {
                $options[$val->id] = $val->requirement;
            }

            $form['notes'] = array(
                '#type' => 'fieldset',
                '#title' => t('<br>Special Requirements'),
                '#collapsible' => true,
                '#collapsed' => false
            );

            $form['notes']['checkrequirements'] = array(
                '#type' => 'checkboxes',
                '#options' => $options,
                '#default_value' => $selected
            );


        }

         $form['notes']['requirements'] = array(
            '#type' => 'textarea',
            '#description' => '',
            '#title' => t ($label),
            '#default_value' => $requirement
        );

        return $form;
    }

    public static function MonthLink($timestamp)
    {

		  $time = strtotime("+ 1 months", $timestamp);
		  $nexttime = mktime(0, 0, 0, date('n', $time), 1, date('Y', $time));

		  $time = strtotime("- 1 months", $timestamp);
		  $lasttime = mktime(0, 0, 0, date('n', $time), 1, date('Y', $time));

        $calendar  = '<div class="month-link-left" id="month-left">';
          if (date('n', time()) != date('n', $timestamp)) {
          	$calendar .= '<a class="calendar-link-arrow" href="/booking/ajax/calendar/' . $lasttime . '">' . '<<' . '</a>';
          }
        $calendar .= '</div><!-- end month-left-->';

        $calendar .= '<div id="month-centre">';
        $calendar .= date('D, j M Y', $timestamp);
        $calendar .= '</div><!-- end month-centre-->';

        $calendar .= '<div class="month-link-right" id="month-right">';
        	$calendar .= '<a class="calendar-link-arrow" href="/booking/ajax/calendar/' . $nexttime . '">' . '>>' . '</a>';
        $calendar .= '</div><!-- end month-right -->';

        return $calendar;
    }


    public static function HtmlCalendar(&$form, $timestamp = '')
    {

    		$timestamp = (empty ($timestamp)) ? time() : $timestamp;
        $endoffset = date('w', mktime(0,0,0, date('n', $timestamp), 1, date('Y', $timestamp)));

			/**
			 * 'n' Numeric representation of a month, without leading zeros
			 * 'j' Day of the month without leading zeros
			 * 'Y' A full numeric representation of a year, at least 4 digits, with - for years BCE.
			 * 'd' Day of the month, 2 digits with leading zeros
			 */
    		if (date('n', time()) == date('n', $timestamp)) { //if current month
          if (date('j', time()) == date('j', $timestamp)) {// if curent day
            $timestamp = mktime(0,0,0, date('n', $timestamp), date('j', time()), date('Y', $timestamp));
          }
    		}

        $offset = array();

        switch ($endoffset) {
          case 6:
            break;

          case 0:
            break;

          default:
            $offset = range(0, $endoffset - 1);
        }




    		$currentMonth = date('m', $timestamp);
        $currentDay = date('d', $timestamp);
        $currentYear = date('Y', $timestamp);



    		$daysOfWeek = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
        //$daysOfWeek = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');


    		$daysInMonth = date('t', strtotime($currentYear . '-' . $currentMonth . '-01'));


        //$offset = range(1, $endoffset);


    		$days = range(1, $daysInMonth);


    		$calendar = '<div id="calendar-div">';

    			$calendar .= '<div id="month">';

    				$calendar .= self::MonthLink($timestamp);

    			$calendar .= '</div>';

    			$calendar .= '<div class="shadow bookings-padd-calendar">';

    			$calendar .= '<div id="days-of-week" class="padd2">';
    			foreach ($daysOfWeek as $key => $val) {
    				$calendar .= '<div class="days day">' . $val . '</div>';
				}
				$calendar .= '</div>';

				$calendar .= '<div class="padd2">';


                $styles = array('day');
                foreach ($offset as $val) {

                  $content = '&nbsp;';
                  $calendar .= '<div class="' . implode(' ', $styles) . '">' . $content . '</div>';

                }




    			foreach ($days as $key => $val) {

    				$styles = array('day');
    				$day = ($val < 10) ? '0' . $val : $val;
    				$selected = mktime(0,0,0, $currentMonth, $day, $currentYear);
    				$now = mktime(0,0,0, $currentMonth, date('d', $timestamp), $currentYear);
    				$content = $val;
            //$content = ($val == 0) ? '' : $val;


            if ($selected >= mktime(0,0,0, date('n', time()), date('j', time()), date('Y', time()))) {
    					$styles[] = 'active';
    					$content = '<a class="calendar-link-day" href="/booking/ajax/day/' . $selected . '">' . $val . '</a>';

    				}

    				if ($selected == $now) {
						$styles[] = 'selected';
					}

    				$calendar .= '<div class="' . implode(' ', $styles) . '"><span class="number">' . $content . '</span></div>';

    			}
    			//exit;


    		$calendar .= '</div></div></div>';

    		$form['htmlcalendar'] = array(
            '#type' => 'markup',
            '#markup' => $calendar
        	);

    		return $form;
    }

    public static function Submit(&$form, array $values = array())
    {
        $value = (isset($values['value'])) ? $values['value'] : 'Submit';
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t($value),
            '#attributes' => array('class' => array('edit-button'))
        );
        return $form;
    }

    public static function Front(&$form, $date, $guests, $isadmin)
    {
        $db = \Drupal::database();
        $top = '<div id="bookings-div">';
        $top .= '<div id="bookings-left-col">';
        $top .= '<div class="shadow bookings-padd-left" style="margin-bottom: 15px;">';

                $form['top'] = array(
                	'#type' => 'markup',
                	'#markup' => t($top)
                );

    			$form['padd1'] = array(
    				'#type' => 'markup',
    				'#markup' => '<div class="padd2">'
    			);
    			$form = self::Guests($form, array(), array('title' => 'Booking for <span id="guests">2</span> <span id="persons">people</span>'));
    			$form['padd2'] = array(
    				'#type' => 'markup',
    				'#markup' => '</div></div>'
    			);


    			$form['htmlcalendar-wrap'] = array(
    				'#type' => 'markup',
    				'#markup' => '<div id="htmlcalendar-top">'
    			);

    			$form = self::HtmlCalendar($form);

    			$form['htmlcalendar-bottom'] = array(
    				'#type' => 'markup',
    				'#markup' => '</div>'
    			);


    		$leftcol = '</div><!-- end bookings-left-col -->';
    		$form['left-col'] = array(
    			'#type' => 'markup',
    			'#markup' => t($leftcol)
    		);

    		$rightcol = '<div id="bookings-right-col" class="padd"><div id="times-right-col" class="shadow">';
    		$form['rightcol'] = array(
    			'#type' => 'markup',
    			'#markup' => t($rightcol)
    		);
			$html = '<div id="spinner-wrap" style="display: block;"><div id="spinner-div" style="margin-left: 100px"><img width="70" height="70" alt="spinner image" src="' . get_restaurant_path(false) . '/img/spinner.gif"></div></div>';
			$form['spinner'] = array(
				'#type' => 'markup',
				'#markup' => $html
			);

    		$bookings = new Booking($db);
    		$times = $bookings->getTimes($date, false);
    		$bookings->filterTimes($times, $date, $guests);

    		$form = self::BookingTimes($form, array('times' => $times, 'date' => date('Y-m-d H:i:s', $date)), $isadmin);

    		$rightend = '</div></div><!-- end bookings-right-col -->';
    		$form['rightend'] = array(
    			'#type' => 'markup',
    			'#markup' => t($rightend)
    		);

    		$bottom = '</div><!-- end bookings div-->';
    		$form['bottom'] = array(
    			'#type' => 'markup',
    			'#markup' => t($bottom)
    		);

    return $form;
    }
}
