<?php
/**
 * Popup include page
 * Displays a list with modules
 *
 * @package     Add to Menu
 * @version     1.2.0
 *
 * @author      Peter van Westen <peter@nonumber.nl>
 * @link        http://www.nonumber.nl
 * @copyright   Copyright (C) 2010 NoNumber! All Rights Reserved
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

$lang =& JFactory::getLanguage();
$lang->load( 'plg_editors-xtd_addtomenu', JPATH_ADMINISTRATOR );
$lang->load( 'com_menus', JPATH_ADMINISTRATOR );

$comp_file = JRequest::getVar( 'comp' );
$vars = JRequest::getVar( 'vars' );

$option = $vars['option'];
$file = dirname(__FILE__).DS.'components'.DS.$option.DS.$comp_file.'.php';

$component='';
require_once $file;

if ( !$component ) {
	return;
}

$insert = JRequest::getVar( 'insert' );

if ( $insert ) {
	insertMenuItem( $component );
} else {
	$lang =& JFactory::getLanguage();
	$lang->load( $option, JPATH_ADMINISTRATOR );
	if( isset( $component['urlparams']['option'] ) && $component['urlparams']['option'] != $option ) {
		$lang->load( $component['urlparams']['option'], JPATH_ADMINISTRATOR );
		$lang->load( $component['urlparams']['option'].'.menu', JPATH_ADMINISTRATOR );
	}

	renderHTML( $component );
}

function insertMenuItem( &$component )
{
	$db =& JFactory::getDBO();

	$item =& JTable::getInstance( 'menu' );

	$item->name = JRequest::getVar( 'name', '' );
	$item->alias = JRequest::getVar( 'alias', '' );
	if( !strlen( $item->alias ) ) { $item->alias = $item->name; }
	$item->alias = filterAlias( $item->alias );

	$item->published = JRequest::getVar( 'published', 0 );
	$menuitem = JRequest::getVar( 'menuitem', 'mainmenu::0' );
	$menuitem = explode( '::', $menuitem );
	$item->menutype = $menuitem['0'];
	$item->parent = (int) $menuitem['1'];

	$item->sublevel = 0;
	if ( $item->parent ) {
		$query = 'SELECT `sublevel`' .
				' FROM #__menu' .
				' WHERE id = '.$item->parent.
				' LIMIT 1';
		$db->setQuery( $query );
		$item->sublevel = (int) $db->loadResult();
		$item->sublevel++;
	}

	$query = 'SELECT `ordering`' .
			' FROM #__menu' .
			' WHERE menutype = "'.$item->menutype.'"'.
			' AND parent = '.$item->parent.
			' ORDER BY `ordering` DESC'.
			' LIMIT 1';
	$db->setQuery( $query );
	$item->ordering = (int) $db->loadResult();
	$item->ordering++;

	$item->type = 'component';

	$query = 'SELECT `id`' .
			' FROM `#__components`' .
			' WHERE `link` <> \'\'' .
			' AND `parent` = 0' .
			' AND `option` = \''.$component['urlparams']['option'].'\''.
			' LIMIT 1';
	$db->setQuery( $query );
	$item->componentid = $db->loadResult();

	$item->link = 'index.php?';
	$urlparams = array();
	foreach( $component['urlparams'] as $key => $val ) {
		$val = getVar( $val );
		if ( strlen( $val ) ) {
			$urlparams[] = $key.'='.$val;
		}
	}
	$item->link .= implode( '&', $urlparams );

	$menuparams = array();
	foreach( $component['menuparams'] as $key => $val ) {
		$val = getVar( $val );
		if ( strlen( $val ) ) {
			$menuparams[] = $key.'='.$val;
		}
	}
	$item->params .= implode( "\n", $menuparams );

	if ( !$item->check() ) {
		echo "<script> window.parent.addtomenu_setMessage( '".$item->getError( true )."', 0 ); </script>\n";
		return false;
	}

	if (!$item->store())
	{
		echo "<script> window.parent.addtomenu_setMessage( '".$row->getError(true)."', 0 ); </script>\n";
		return false;
	}

	echo "<script> window.parent.addtomenu_setMessage( '".JText::_( 'Menu item saved' )."', 1 ); </script>\n";
}

function renderHTML( &$component )
{
	if ( isset( $component['dbselect']['table'] ) ) {
		$where = array();
		foreach( $component['dbselect']['where'] as $key => $val ) {
			$val = getVar( $val );
			$where[] = '`'.$key.'` = \''.$val.'\'';
		}

		$db =& JFactory::getDBO();
		$query = 'SELECT '.
				$component['dbselect']['name'].' as name, '.
				$component['dbselect']['alias'].' as alias'.
			' FROM '.$component['dbselect']['table'].
			' WHERE '.implode( ' AND ', $where ).
			' LIMIT 1';
		$db->setQuery( $query );
		$item = $db->loadObject();
	} else {
		$item = '';
		$item->name = JText::_( $component['dbselect']['name'] );
		$item->alias = $item->name;
		if ( isset( $component['dbselect']['alias'] ) ) {
			$item->alias = $component['dbselect']['alias'];
		}
		$item->alias = filterAlias( $item->alias );
	}

	$width = '100%;';

	$elements = array();

	$elements[] = el(
		'Title',
		'<input class="inputbox" type="text" name="name" style=width:'.$width.';" maxlength="255" value="'.$item->name.'" />'
	);
	$elements[] = el(
		'Alias',
		'<input class="inputbox" type="text" name="alias" style=width:'.$width.';" maxlength="255" value="'.$item->alias.'" />'
	);
	$elements[] = el(
		'Published',
		'<input type="radio" name="published" value="0"  />
		<label for="published0">'.JText::_( 'No' ).'</label>
		<input type="radio" name="published" value="1" checked="checked"  />
		<label for="published1">'.JText::_( 'Yes' ).'</label>'
	);
	$elements[] = el(
		'Parent Item',
		getMenuItems( 'menuitem', $width )
	);
	if ( count( $component['extra'] ) ) {
		$elements[] = el(
			'@spacer',
			'<strong>'.JText::_( 'Extra options' ).'</strong>'
		);
		foreach( $component['extra'] as $element ) {
			if ( $element['type'] == 'radio' || $element['type'] == 'select' ) {
				if ( !is_array( $element['value'] ) ) {
					 $element['value'] =  array( $element['value'] );
				}
				$options = array();
				foreach( $element['value'] as $key => $val ) {
					$options[]	= JHTML::_( 'select.option', $key, JText::_( $val ), 'value', 'text' );
				}
			} else {
				if ( is_array( $element['value'] ) ) {
					$element['value'] =  array_shift( $element['value'] );
				}
			}

			switch( $element['type'] ) {
				case 'select':
					$el = JHTML::_( 'select.genericlist', $options, 'extra['.$element['name'].']', 'class="inputbox"' );
					break;
				case 'radio':
					$el = JHTML::_( 'select.radiolist', $options, 'extra['.$element['name'].']', 'class="inputbox"' );
					// add breaks between each radio element
					$el = preg_replace( '#(</label>)(\s*<input )#i', '\1<br />\2', $el );
					break;
				case 'textarea':
					$el = '<textarea style=width:'.$width.';height:100px;" name="extra['.$element['name'].']">'.$element['value'].'</textarea>';
					break;
				case 'hidden':
					$el = '<input type="hidden" name="extra['.$element['name'].']" value="'.$element['value'].'" />';
				case 'text':
				default:
					$el = '<input type="text" name="extra['.$element['name'].']" style=width:'.$width.';" value="'.$element['value'].'" />';
					break;
			}
			if ( !isset( $element['label'] ) ) {
				$element['label'] = $element['name'];
			}
			$elements[] = el(
				JText::_( $element['label'] ),
				$el
			);
		}
	}

	outputHTML( $component, $elements );
}

function el( $name, $element )
{
	$ob = '';
	$ob->name = $name;
	$ob->element = $element;
	return $ob;
}

function getMenuItems( $name, $width = '100%' )
{
	$db =& JFactory::getDBO();

	// load the list of menu types
	$query = 'SELECT menutype, title'
			.' FROM #__menu_types'
			.' ORDER BY id'
			;
	$db->setQuery( $query );
	$menuTypes = $db->loadObjectList();

	// load the list of menu items
	$query = 'SELECT id, parent, name, menutype, type, published'
			.' FROM #__menu'
			.' WHERE published != "-2"'
			.' ORDER BY menutype, parent, ordering'
			;
	$db->setQuery($query);
	$menuItems = $db->loadObjectList();

	// establish the hierarchy of the menu
	// TODO: use node model
	$children = array();

	if ($menuItems)
	{
		// first pass - collect children
		foreach ($menuItems as $v)
		{
			$pt 	= $v->parent;
			$list 	= @$children[$pt] ? $children[$pt] : array();
			array_push( $list, $v );
			$children[$pt] = $list;
		}
	}

	// second pass - get an indent list of the items
	$list = JHTML::_('menu.treerecurse', 0, '', array(), $children, 9999, 0, 0 );

	// assemble into menutype groups
	$n = count( $list );
	$groupedList = array();
	foreach ($list as $k => $v) {
		$groupedList[$v->menutype][] =& $list[$k];
	}

	// assemble menu items to the array
	$options 	= array();

	foreach ($menuTypes as $count => $type)
	{
		if ( $count ) {
			$options[]	= JHTML::_('select.option',  '0', '------------------------------', 'value', 'text', true);
		} else {
			$selected = $type->menutype.'::0';
		}

		$options[]	= JHTML::_( 'select.option', $type->menutype.'::0', $type->title . ' - ' . JText::_( 'Top' ) );

		if (isset( $groupedList[$type->menutype] ))
		{
			$n = count( $groupedList[$type->menutype] );
			for ($i = 0; $i < $n; $i++)
			{
				$item =& $groupedList[$type->menutype][$i];

				//If menutype is changed but item is not saved yet, use the new type in the list
				if ( JRequest::getString('option', '', 'get') == 'com_menus' ) {
					$currentItemArray = JRequest::getVar('cid', array(0), '', 'array');
					$currentItemId = (int) $currentItemArray['0'];
					$currentItemType = JRequest::getString('type', $item->type, 'get');
					if ( $currentItemId == $item->id && $currentItemType != $item->type) {
						$item->type = $currentItemType;
					}
				}
				if ( $item->published == 0 ) {
					$item->treename .= ' ('.JText::_( 'Unpublished' ).')';
				}
				$options[] = JHTML::_( 'select.option', $type->menutype.'::'.$item->id, '&nbsp;&nbsp;&nbsp;'.$item->treename );
			}
		}
	}

	$attribs = 'class="inputbox" style=width:'.$width.';"';
	$attribs .= ' size="'.( ( count( $options) > 10 ) ? 10 : count( $options) ).'"';

	return JHTML::_( 'select.genericlist',  $options, $name, $attribs, 'value', 'text', $selected );
}

function getVar( $var ) {
	if ( $var['0'] == '$' ) {
		$var = getVal( substr( $var, 1 ) );
	}
	return $var;
}

function getVal( $val ) {
	$vars = JRequest::getVar( 'vars' );
	$extra = JRequest::getVar( 'extra' );

	if( isset( $extra[$val] ) ) {
		$value = $extra[$val];
	} else if( isset( $vars[$val] ) ) {
		$value = $vars[$val];
	} else {
		$value = JRequest::getVar( $val );
	}

	if ( is_array( $value ) ) {
		$value = $value['0'];
	}

	return $value;
}

function filterAlias( $alias ) {
	$alias = JFilterOutput::stringURLSafe( $alias );
	if( trim( str_replace( '-', '', $alias ) ) == '' ) {
		$datenow =& JFactory::getDate();
		$alias = $datenow->toFormat( "%Y-%m-%d-%H-%M-%S" );
	}
	return $alias;
}

function outputHTML( &$component, &$elements )
{
	JHTML::_( 'behavior.tooltip' );

	$document =& JFactory::getDocument();
	$document->addStyleSheet( JURI::root( true ).'/administrator/modules/mod_addtomenu/addtomenu/css/addtomenu_popup.css' );

	$uri =& JURI::getInstance();
?>
	<form action="<?php echo $uri->toString(); ?>" method="post" name="adminForm" id="adminForm">
		<input type="hidden" name="insert" value="1" />
		<fieldset>
			<div style="float: left">
				<h1><?php echo JText::_( 'Add to Menu' ); ?></h1>
			</div>
			<div style="float: right">
				<div class="button2-left"><div class="blank hasicon apply">
					<a rel="" onclick="document.getElementById('adminForm').submit();" href="javascript://" title="<?php echo JText::_('Add') ?>"><?php echo JText::_('Add') ?></a>
				</div></div>
				<div class="button2-left"><div class="blank hasicon cancel">
					<a rel="" onclick="window.parent.document.getElementById('sbox-window').close();" href="javascript://" title="<?php echo JText::_('Cancel') ?>"><?php echo JText::_('Cancel') ?></a>
				</div></div>
			</div>
			<div style="clear: both;"></div>
			<?php echo JText::_( $component['name'] ); ?>
		</fieldset>

		<table width="100%" class="paramlist admintable" cellspacing="1">
			<tbody>
				<?php
					foreach ( $elements as $element ) {
						if ( $element->name == '@spacer' ) {
							echo
							'<tr>'.
								'<td colspan="2">'.$element->element.'</td>'.
							'</tr>';
						} else if ( $element->name ) {
							echo
							'<tr>'.
								'<td class="paramlist_key">'.JText::_( $element->name ).'</td>'.
								'<td>'.$element->element.'</td>'.
							'</tr>';
						} else {
							echo $element->element;
						}
					}
				?>
			</tbody>
		</table>

		<fieldset>
			<div style="float: right">
				<div class="button2-left"><div class="blank hasicon apply">
					<a rel="" onclick="document.getElementById('adminForm').submit();" href="javascript://" title="<?php echo JText::_('Add') ?>"><?php echo JText::_('Add') ?></a>
				</div></div>
				<div class="button2-left"><div class="blank hasicon cancel">
					<a rel="" onclick="window.parent.document.getElementById('sbox-window').close();" href="javascript://" title="<?php echo JText::_('Cancel') ?>"><?php echo JText::_('Cancel') ?></a>
				</div></div>
			</div>
		</fieldset>
	</form>
<?php
}