<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

abstract class sly_Controller_Globalsettings_Saver extends sly_Controller_Globalsettings {
	protected function saveList($settings) {
		if (empty($_POST)) return;

		$errors   = array();
		$response = array('status' => 0, 'message' => t('wv8_settings_updated'));
		$list     = array();
		$service  = new WV8_Service();

		foreach ($settings as $setting) {
			try {
				$setting = $this->getSetting($setting);

				if ($setting->getData('hidden')) {
					continue;
				}

				if ($setting->getData('multilingual_only', false) && !sly_Util_Language::isMultilingual()) {
					continue;
				}

				$id  = $setting->getID();
				$old = $setting->getValues();

				$this->updateFromForm($service, $setting);

				$list[$id] = array(
					'old'       => $old,
					'new'       => $setting->getValues(),
					'namespace' => $setting->getNamespace(),
					'name'      => $setting->getName()
				);
			}
			catch (Exception $e) {
				if ($setting instanceof _WV8_Setting) {
					$errors[$setting->getID()] = $setting->getTitle().': '.$e->getMessage();
				}
				else {
					$errors[$setting] = 'Die gewählte Einstellung konnte nicht gefunden werden.';
				}
			}
		}

		// notify the system
		sly_Core::dispatcher()->notify('WV8_SETTINGS_UPDATED', $list);

		// send AJAX response
		if (sly_get('ajax', 'int', 0) === 1) {
			if (!empty($errors)) {
				$response = array(
					'status'  => 1,
					'failed'  => count($errors),
					'errors'  => $errors,
					'message' => t('wv8_settings_errors')
				);
			}

			while (ob_get_level()) ob_end_clean();
			header('Content-Type: application/json; charset=UTF-8');
			print json_encode($response);
			die;
		}

		print sly_Helper_Message::info(t('wv8_settings_updated'));

		if (!empty($errors)) {
			print '<p>'.ht('wv8_settings_errors').'</p>';
			print sly_Helper_Message::warn(implode("<br />\n", array_values($errors)));
		}
	}

	private function getSetting($setting) {
		if ($setting instanceof _WV8_Setting) return $setting;

		$parts = explode('/', $setting);
		if (count($parts) !== 2) throw new WV8_Exception('Invalid setting.');

		return WV8_Settings::getSetting($parts[0], $parts[1]);
	}

	private function updateFromForm(WV8_Service $service, _WV8_Setting $setting) {
		$values    = $setting->serializeForm();
		$languages = sly_Util_Language::findAll(true);
		$rawValues = $setting->getValues(true); // raw

		if ($setting->isMonolingual()) {
			foreach ($languages as $clangID) {
				$rawValues[$clangID] = $values;
			}
		}
		else {
			$rawValues = $values;
		}

		$service->store($setting, $rawValues);
	}
}
