<?php 

/**
 * ProcessWire General site settings module
 *
 * Allows to set global site settings 
 *
 * by Piotr Markiewicz (pmarki)
 * 
 * Additional revisions by Marc Wolf (@macrura)
 *
 * https://processwire.com
 *
 * http://modules.processwire.com/modules/process-general-settings/
 * https://github.com/flydev-fr/ProcessGeneralSettings
 * 
 */

class GeneralSettings extends \ProcessWire\Process implements \ProcessWire\Module, \ProcessWire\ConfigurableModule {

	public static function getModuleInfo() {
		return array(
			'title' 	=> \ProcessWire\__('General Site Settings', 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module'),
			'summary' 	=> \ProcessWire\__('Configurable module that stores a variety of global site settings', 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module'),
			'version' 	=> 122,
			'permanent' => false, 
			'autoload' 	=> true,
			'icon' 		=> 'sliders', 
			//'installs'	=> 'ProcessGeneralSettings',
			'requires' 	=> 'ProcessGeneralSettings',
			);
	}

	protected static $defaults = array(
			'global' => 'g_settings',
			'settings' => '{"0":{"api":"title","label":"Your site title","type":"Text","width":"100","description":"","select":""}}',
	);


	public function init() {

		parent::init();

		if ($this->wire('user')->isLoggedin() && $this->input->get('name') == __CLASS__) {
			$root = $this->config->urls->siteModules . 'ProcessGeneralSettings'; // parent module – this should be adjusted
			$this->config->styles->prepend($root . '/' . 'Settings.css');
			$this->config->scripts->add($root . '/' . 'Settings.js');
		}

		//register wire 'global'
		if (isset($this->data['global'])) {
			$this->wire($this->data['global'], $this);
		}

		if (!isset($this->data['settings'])) {
			parent::init();
			return;
		}

		//set api as key with value as value
		//it makes it callable $settings->key
		$langData = array();
		$data = json_decode($this->data['settings'], true);
		foreach ($data as $key => $field) {
			if (!isset($field['api'])) continue;

			$value = (isset($field['value']) ? $field['value'] : '');
			if ($field['type'] == 'Textarea') {
				$value = nl2br($value);
			}

			if ($this->user->language) {
				//if api ends with language name: site_name_polish, add its value to langData array
				//so if user language is polish calling site_name will return its polish value
				if (strpos($field['api'], '_'.$this->user->language->name) !== false) {
					//$api without language suffix - site_title
					$api = str_replace('_'.$this->user->language->name, '', $field['api']);
					foreach ($data as $k => $f) {
						if ($f['api'] === $api) {
							$langData[$api] = $field['value'];
						}
					}
				}
			}
			$this->set($field['api'], $value);
		}
		foreach ($langData as $key => $value) {
			$this->set($key, $value);
		}


	}


	/**
	 * Render all settings with basic markup
	 * 
	 * @return string markup
	 *
	 */
	public function render() {
		$out = '<p>';
		foreach (json_decode($this->data['settings'], true) as $key => $field) {
			if (isset($field['api']) && $field['type'] != 'Fieldset') {
				$v = (isset($field['value'])) ? $field['value'] : '';
				$out .= $this->wire('sanitizer')->entities($field['label'])
					. ' ('. $field['api'] . ') => ' 
					. nl2br($this->wire('sanitizer')->entities($v)) . '<br>';
			}
		}
		return $out .'</p>';
	}


	static public function getModuleConfigInputfields(array $data) {
		$data = array_merge(self::$defaults, $data);
		$options = array();
		$values = array();
		$json = (isset( $data['settings'] )) ? json_decode($data['settings'], true) : '';

		if(isset($data['settings_import']) && $data['settings_import'] != '') {
			$json = json_decode($data['settings_import'], true);
			$data['settings'] = $data['settings_import'];
			$data['settings_import'] = '';
		}

		foreach ($json as $key => $value) {
			if ($value['type'] == 'Fieldset' || $value['type'] == 'FieldsetClose') {
				$options[$value['api']] ='-- '. $value['label'] . ' -- ' . $value['width'] . '%';
			} else {
				$options[$value['api']] = $value['label'] . ' ('. $value['api'] .') - ' . $value['width'] . '%';
			}
			$values[] = $value['api'];
		}

		$order = array();
		$fields = new \ProcessWire\InputfieldWrapper();
		$modules = \ProcessWire\wire('modules');

		//------------------------------------------
		$field = $modules->get("InputfieldMarkup");
		$field->label = \ProcessWire\__("Help", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$help = ('<b>API variable</b> - Any combination of letters (a-z), numbers (0-9) and underscores (no spaces). 
				You can call it in template files to output a value ($settings->site_name will return "My site").
				<br>IMPORTANT: take care to not overload ProcessWire properties ($page, $user, etc.). It must be unique across all settings.<br>
				<b>Label</b> - descriptive name for a backend user<br>
				<b>Description</b> - longer explanation shown as notes in ProcessWire backend<br>
				<b>Width</b> - field width in %, set between 10 and 100<br>
				<b>Options for select or radios</b> - this will be used as names and labels, the best one word only');
		$field->entityEncodeText = false;
		$field->entityEncodeLabel = false;
		$field->attr('value', $help); 
		$field->collapsed = \ProcessWire\Inputfield::collapsedYes;
		$fields->append($field);

		//------------------------------------------
		$field = $modules->get("InputfieldText");
		$field->attr('name', 'global');
		$field->label = \ProcessWire\__("Global name", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->attr('value', $data['global']); 
		$field->description = \ProcessWire\__('Use to call settings property in frontend ($settings->property).', 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->notes = \ProcessWire\__("After changing make sure to change it in your template files.", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->collapsed = \ProcessWire\Inputfield::collapsedYes;
		$fields->append($field);

		//------------------------------------------
		$field = \ProcessWire\wire('modules')->get("InputfieldTextarea");
		$field->attr('name', 'settings');
		$field->attr('id', 'settings');
		$field->label = \ProcessWire\__("Json data", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->attr('value', $data['settings']); 
		$field->columnWidth = 34;
		$field->collapsed = \ProcessWire\Inputfield::collapsedYes;
		$fields->append($field);


		//------------------------------------------
		$field = \ProcessWire\wire('modules')->get("InputfieldTextarea");
		$field->attr('name', 'settings_import');
		$field->attr('id', 'settings_import');
		$field->label = \ProcessWire\__("Import Settings Config", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->description = \ProcessWire\__('Paste a JSON array of settings here - Warning - pasting here will clear all saved settings in the Process Module.', 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->attr('value', $data['settings_import']); 
		$field->collapsed = \ProcessWire\Inputfield::collapsedYes;
		$fields->append($field);


		//------------------------------------------
		$field = $modules->get("InputfieldAsmSelect");
		$field->attr('name', 'order');
		$field->attr('id', 'ASMOrder');
		$field->label = \ProcessWire\__("Settings", 'C:/webpages/creative/site/modules/ProcessGeneralSettings/GeneralSettings.module');
		$field->addOptions($options);
		$field->attr('value', $values); 
		$fields->append($field);


		return $fields;
	}


}
