<?php
/*
 * Copyright (c) 2012, 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
 */

// clean up database and config
require dirname(__FILE__).'/uninstall.php';

// init database

function realurl2AddColumn($name, $ddl) {
	$pdo = sly_DB_Persistence::getInstance();
	$pre = sly_Core::getTablePrefix();

	$pdo->query('SHOW COLUMNS FROM '.$pre.'article WHERE Field = ?', array($name));

	if ($pdo->affectedRows() == 0) {
		$pdo->query('ALTER TABLE '.$pre.'article ADD COLUMN '.$name.' '.$ddl);
	}
}

realurl2AddColumn('wv24_fragment', 'VARCHAR(256) NOT NULL AFTER revision');
realurl2AddColumn('wv24_skip', 'TINYINT(1) NOT NULL DEFAULT "0" AFTER wv24_fragment');

// reload global settings
// (makes it possible to access the settings and set some sensible default values)

function realurl2Install(array $params) {
	// reload settings
	WV8_Settings::reloadConfig();

	// set default values
	$settings     = WV8_Settings::getSettings('realurl2');
	$base         = substr(sly_Util_HTTP::getBaseUrl(true, 'http'), 5); // cut off 'http:'
	$langs        = sly_Util_Language::findAll(true);
	$service      = new WV8_Service();
	$defaultClang = sly_Core::getDefaultClangId();

	$fragmentValues  = array();
	$lowercaseValues = array();
	$cleanupValues   = array();

	foreach ($langs as $clangID) {
		// assume all languages have locales like 'de_DE'
		$locale = sly_Util_Language::getLocale($clangID);
		$locale = explode('_', $locale, 2);
		$locale = strtolower(reset($locale));

		if (empty($locale)) {
			$locale = 'lang'.$clangID;
		}

		// set default values
		$fragmentValues[$clangID]  = $base.($clangID == $defaultClang ? '' : "/$locale");
		$lowercaseValues[$clangID] = 1;
		$cleanupValues[$clangID]   = 1;
	}

	$service->store($settings['realurl2/default_fragment'], $fragmentValues);
	$service->store($settings['realurl2/lowercase'], $lowercaseValues);
	$service->store($settings['realurl2/cleanup'], $cleanupValues);

	// done
	return $params['subject'];
}

sly_Core::dispatcher()->register('SLY_ADDON_POST_INSTALL', 'realurl2Install');
