<?php

namespace modules\formEdit;

class main extends \moduleMain {

	use \modules\output\traits {
		\modules\output\traits::__construct as __ConstructOutput;
	}
	use \modules\input\traits {
			\modules\input\traits::__construct as __ConstructInput;
		}

	private $active = FALSE;

	public function __construct() {
		parent::__construct(__DIR__);
		$this->__ConstructOutput();
		$this->__ConstructInput();
	}

	public function Activate() {
		hook_add('component.add', [$this, '__component']);
		hook_add('formedit.validate', [$this, '__validate']);
		hook_add('fieldlist.filter', [ $this, '__custom_fields' ]);		// you should not need to add a hook to this chain.  add to "fieldlist.{fieldtype}.html" instead
	}

	public function __component(&$status, $requested) {
		if ($requested == 'formedit') {
			$this->active = TRUE;
			// load view
			$view = $this->__loadView('formedit_view');
			$view->handlebars_template();
//			$status = '{{> fields fieldlist=fieldlist}}';
			$status = '{{> formedit}}';
		}
	}
	
	public function __custom_fields(&$result, $active) {			// $result is the handlebars data structure that will be returned to the frontend
		if (isset($result['fieldlist'])) {
			foreach($result['fieldlist'] as &$field) {
				$module_name = preg_match('~^(.*?)\[~', $field['name'], $value) ? $value[1] : '';
				$fieldname = preg_match('~\[(.*?)\]~', $field['name'], $value) ? $value[1] : '';
				$settings = $active[$module_name];
				$field['value'] = $settings[$fieldname] ?? '';			// get the current value
				$hookname = 'fieldlist.' . strtolower($field['type']) . '.html';
				$field = hook_execute($hookname, $field);			// the custom html for this control should be in $field['custom']
				$result[$fieldname] = $field['value'];
			}
		}
	}
	
	// process the fields - get values and any error messages
	public function __validate(&$result, $definitions) {
		$post = $this->post();
		$errors = [];
		$data = [];
		foreach($definitions as $def) {
			$name = $def['name'] ?? '';
			$required = $def['required'] ?? FALSE;		// not for checkboxes
			switch($def['type']) {
				case 'string':
				case 'tel':
					$value = trim($post[$name] ?? '');	// not for multiselect
					if ($value == '' && $required) {
						$errors[$name] = ['message' => '?'];		// must have a value
						break;
					}
					$data[$name] = $value;
					break;

				case 'email':
					$value = trim($post[$name] ?? '');	// not for multiselect
					if ($value == '' && $required) {
						$errors[$name] = ['message' => '?'];		// must have a value
						break;
					}
					// validate email
					if (($p = strrpos($value, '@')) !== FALSE) {
						$domain = strtolower(substr($value, $p + 1));
						if (strlen($domain) < 4 || strpos($domain, '.') === FALSE) {
							$errors[$name] = ['message' => 'This does not look like a valid email address'];
							break;
						}
						$disposable = hook_execute('email.check', NULL, $domain);
						if ($disposable) {
							$errors[$name] = ['message' => 'Temporary email addresses are not acceptable'];
						} else {
							$data[$name] = $value;
						}
					} else {
						$errors[$name] = ['message' => 'This does not look like a valid email address'];
					}
					break;

				case 'select':
					break;

				case 'text':
					$value = trim($post[$name] ?? '');	// not for multiselect
					if ($value == '' && $required) {
						$errors[$name] = ['message' => 'This field is required'];		// must have a value
						break;
					}
					$data[$name] = $value;
					break;
				// case checkbox
			}
		}
		if (count($errors)) {
			$result = ['field' => $errors];
		} else {
			$result = ['data' => $data ];
		}
	}
}

/*
generate form html using handlebars from an array
load existing data
save data
error checking
to do: use by single-module settings (system page, and google mail page)
also generate buttons

*/