<?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
 */

$canView = _WV2_Metainfo::isAllowed('view');
$canEdit = _WV2_Metainfo::isAllowed('edit');

$userID    = $user ? $user->getId() : null;
$languages = array();
$curUser   = sly_Util_User::getCurrentUser();
$isAdmin   = $curUser->isAdmin();
$sysLangs  = sly_Util_Language::findAll();
$allowed   = $curUser->getAllowedCLangs();

foreach ($sysLangs as $id => $lang) {
	if (!in_array($id, $allowed) && !$isAdmin) continue;
	$languages[$id] = sly_html($lang->getName());
}

$availableInfos = WV2_MetaProvider::getAllUserMetaInfos();
$assignedData   = $user ? WV2_MetaProvider::userData($user, null, null, $clang, true) : array();
$dataToDisplay  = _WV2_Metainfo::getInfosToDisplay($availableInfos, false, $assignedData, $availableInfos);

$lastGroup = t('metainfo_fieldset_title');
if (!empty($dataToDisplay) && isset($dataToDisplay[''])) {
	$form->beginFieldset($lastGroup);
}

if ($user && count($languages) > 1) {
	$links = array();
	$get   = 'page=user&amp;func='.($userID ? 'edit&amp;id='.$userID : 'add');

	foreach ($languages as $id => $name) {
		if ($id == $clang) $links[] = sly_html($name);
		else $links[] = '<a href="?clang='.$id.'&amp;'.$get.'">'.sly_html($name).'</a>';
	}

	$element = new sly_Form_Text(t('metainfo_languageselect'), implode(' | ', $links));
	$element->setIsHTML(true);

	$form->addHiddenValue('clang', $clang);
	$form->add($element);
}

$first = true;

foreach ($dataToDisplay as $groupName => $group) {
	foreach ($group as $data) {
		$value = $data['value'];
		$info  = $data['info'];

		if ($lastGroup != $groupName) {
			$form->beginFieldset($groupName);

			if (!$first) {
				$form->getCurrentFieldset()->setAttribute('class', 'add-toggle');
			}

			$first     = false;
			$lastGroup = $groupName;
		}

		if ($canEdit) {
			$info->renderForm($form, array($value));
		}
		else {
			$value = $info->deserialize($value);
			$text  = new sly_Form_Text($info->getTitle(), is_array($value) ? implode(', ', $value) : $value);
			$form->add($text);
		}
	}
}

$layout = sly_Core::getLayout();
$layout->addJavaScript("
jQuery(function($) {
	try {
		$('fieldset.add-toggle').each(function() {
			$(this).wvToggleFieldset().addClass('wv-hidden');
		})
	}
	catch (e) {}
});
");
