<?php

namespace Drupal\kate_demo\Form;

use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;

class GetZipcodeForm implements FormInterface {

	public function getFormID() {
		return 'get_zipcode';
	}

	public function buildForm( array $form, FormStateInterface $form_state ) {
		// pop some content into the first page out of a content node
		// pick out the right content node by its title, which should be
		// set to 'Demo'...  Content should be abstracted out from code!
		// The joy of CMS!

		$query = \Drupal::entityQuery( 'node' )
			->condition( 'title', 'Demo' )
			->condition( 'status', 1 )
			->range( 0, 1 );
		$entities = $query->execute();

		if ( !empty( $entities ) ) {
			$node = \Drupal::entityTypeManager()->getStorage( 'node' )
				->load( array_shift( $entities ) );

			$form[ 'explanation' ]	=	array(
				 '#type'		=>	'markup',
				 '#markup'	=>	$node->get( 'body' )->getValue()[0]['value']
			);
		}

		// start of our actual very simple Drupal form to collect the zipcode
		// that starts the demo.
		$form[ 'some_text' ] = array(
			'#type' => 'markup',
			'#markup' => t( 'Please enter your zip code.' ),
		);

		$form[ 'zipcode' ] = array(
			'#type' => 'textfield',
			'#title' => t( 'Zip Code' ),
			'#size' => 5,
			'#maxlength' => 5,
			'#required' => true,
		);

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

		return $form;
	}

	public function validateForm( array &$form, FormStateInterface $form_state ) {
		if ( !preg_match( '/^\d{5}$/', $form_state->getValue( 'zipcode' ) ) )
			$form_state->setErrorByName( 'zipcode', t( 'Please enter a five digit numeric US zipcode.' ) );
	}

	public function submitForm( array &$form, FormStateInterface $form_state ) {
		$zipcode	=	$form_state->getValue( 'zipcode' );

		Header( 'Location: /kate_demo/' . $zipcode . '/show_weather' );
		die();
	}

}