<?php
class SettingsEditor extends Controller {
	const KEY_SPLITTER='|';

	public function Index() {
		$data=parse_ini_file(ApplicationSettings::SETTINGS_PATH,true);
		return new View("SettingsEditor/index.view",array("data"=>$data));
	}
	
	public function Save($params) {
		$newSettings=array();
		foreach ($params as $param=>$value){
			if (strpos($param, self::KEY_SPLITTER)===false)
				continue;
			$setting=explode(self::KEY_SPLITTER, $param);
			$section=$setting[0];
			$key=$setting[1];
			if (!isset($newSettings[$section]))
				$newSettings[$section]=array();
			$newSettings[$section][$key]=$value;
		}
		
		$currentSettings=parse_ini_file(ApplicationSettings::SETTINGS_PATH,true);
		foreach ($currentSettings as $section=>$setting){
			if (!isset($newSettings[$section])){
				$newSettings[$section]=$setting;
				continue;
			}
			foreach ($setting as $key=>$value)
				if (!isset($newSettings[$section][$key]))
					$newSettings[$section][$key]=$value;
		}
		
		rename(ApplicationSettings::SETTINGS_PATH, ApplicationSettings::SETTINGS_PATH.(int)microtime(true));
		Utils::WriteINIFile($newSettings, ApplicationSettings::SETTINGS_PATH, true);
		
		header("location:/settingseditor");
	}
}
