<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # All Rights Reserved. 											  # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this on your server unless the files  # ||
|| # you downloaded were done so with permission.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// #############################################################################
if ($_REQUEST['action'] == 'lottery' OR empty($_REQUEST['action']))
{
	print_cp_header($vbphrase['dbtech_vbshop_lottery_management']);
	
	// Table header
	$headings = array();
	$headings[] = $vbphrase['title'];
	$headings[] = $vbphrase['description'];
	$headings[] = $vbphrase['active'];
	$headings[] = $vbphrase['dbtech_vbshop_ticket_price'];
	$headings[] = $vbphrase['dbtech_vbshop_previous_draw_date'];
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbshop_next_draw_date']);
	$headings[] = $vbphrase['dbtech_vbshop_prizes'];
	$headings[] = $vbphrase['edit'];
	$headings[] = $vbphrase['delete'];
	
	
	if (count(VBSHOP::$cache['lottery']))
	{
		print_form_header('vbshop', 'lottery');	
		construct_hidden_code('action', 'modify');
		print_table_header($vbphrase['dbtech_vbshop_lottery_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbshop_lottery_management_descr'], false, count($headings));	
		print_cells_row($headings, 0, 'thead');
		
		foreach (VBSHOP::$cache['lottery'] as $lotteryid => $lottery)
		{
			$prizes = array();
			foreach ($lottery['prizes'] as $key => $prizeinfo)
			{
				if (!VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"] OR 
					!$prizeinfo['prize'] OR
					!VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]
				)
				{
					// Gtfo
					continue;
				}
				
				// Add it to the final prize array
				$prizes["$key"] = $key . '. <strong>' . VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"]['title'] . '</strong> - <em>' . $prizeinfo['prize'] . ' ' . VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]['title'] . '</em>';
			}
			
			// Table data
			$cell = array();
			$cell[] = $lottery['title'];
			$cell[] = nl2br($lottery['description']);
			$cell[] = ($lottery['active'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
			$cell[] = $lottery['ticketprice'] . ' ' . VBSHOP::$cache['currency']["$lottery[currencyid]"]['title'];
			$cell[] = ($lottery['prevdraw'] ? vbdate($vbulletin->options['dateformat'], $lottery['prevdraw']) : 'N/A');
			$cell[] = vbdate($vbulletin->options['dateformat'], $lottery['nextdraw']);
			$cell[] = implode('<br />', $prizes);
			
			$cell[] = construct_link_code($vbphrase['edit'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery&amp;action=modify&amp;lotteryid=' . $lotteryid);
			$cell[] = construct_link_code($vbphrase['delete'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery&amp;action=delete&amp;lotteryid=' . $lotteryid);
			
			// Print the data
			print_cells_row($cell, 0, 0, -5, 'middle', 0, 1);
		}
		print_submit_row($vbphrase['dbtech_vbshop_add_new_lottery'], false, count($headings));	
	}
	else
	{
		print_form_header('vbshop', 'lottery');	
		construct_hidden_code('action', 'modify');
		print_table_header($vbphrase['dbtech_vbshop_lottery_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbshop_no_lotterys'], false, count($headings));
		print_submit_row($vbphrase['dbtech_vbshop_add_new_lottery'], false, count($headings));	
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$lotteryid = $vbulletin->input->clean_gpc('r', 'lotteryid', TYPE_UINT);
	$lottery = ($lotteryid ? VBSHOP::$cache['lottery']["$lotteryid"] : false);
	
	if (!is_array($lottery))
	{
		// Non-existing lottery
		$lotteryid = 0;
	}
	
	$lotteryprizes 	= array();
	foreach ((array)VBSHOP::$cache['lotteryprize'] as $lotteryprizeid => $lotteryprize)
	{
		// Index by categoryid
		$lotteryprizes["$lotteryprizeid"] = $lotteryprize['title'];
	}
	
	// Sort the array as a string
	asort($lotteryprizes, SORT_STRING);	
	
	if (!count($lotteryprizes))
	{
		// Missing categories
		print_stop_message('dbtech_vbshop_missing_x',
			$vbphrase['dbtech_vbshop_lotteryprize'],
			$vbulletin->session->vars['sessionurl'],
			'lotteryprize',
			'modify'
		);
	}
	
	// Shove this in at the start
	$lotteryprizes = array(0 => 'N/A') + $lotteryprizes;
	
	$currencys 	= array();
	foreach ((array)VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		// Index by categoryid
		$currencys["$currencyid"] = $currency['title'];
	}
	
	// Sort the array as a string
	asort($currencys, SORT_STRING);	
	
	if (!count($currencys))
	{
		// Missing categories
		print_stop_message('dbtech_vbshop_missing_x',
			$vbphrase['dbtech_vbshop_currency'],
			$vbulletin->session->vars['sessionurl'],
			'currency',
			'modify'
		);
	}
	
	$defaults = array(
		'title' 		=> 'Lottery',
		'description' 	=> 'A lottery that gives untold rewards.',
		'active' 		=> 1,
		'displayorder'	=> 10,
		'ticketprice'	=> 50,
		'numbers'		=> array(
			'main'	=> 7,
			'bonus'	=> 2,
			'total'	=> 34,
		),
		'drawinterval'	=> 7,
		'nextdraw' => (TIMENOW + 604800),
	);
	
	$headings = array(
		$vbphrase['usergroup'],
		$vbphrase['dbtech_vbshop_banned_from_lottery']
	);
	
	if ($lotteryid)
	{
		// Edit
		print_cp_header(strip_tags(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_lottery'], $lottery['title'])));
		print_form_header('vbshop', 'lottery');
		construct_hidden_code('action', 'update');
		construct_hidden_code('lotteryid', $lotteryid);
		print_table_header(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_lottery'], $lottery['title']));
	}
	else
	{
		// Add
		print_cp_header($vbphrase['dbtech_vbshop_add_new_lottery']);
		print_form_header('vbshop', 'lottery');
		construct_hidden_code('action', 'update');
		print_table_header($vbphrase['dbtech_vbshop_add_new_lottery']);
		
		$lottery = $defaults;
	}
	
	print_description_row($vbphrase['dbtech_vbshop_main_settings'], false, 2, 'optiontitle');	
	print_input_row($vbphrase['title'], 								'lottery[title]', 						$lottery['title']);
	print_textarea_row($vbphrase['description'], 						'lottery[description]', 				$lottery['description']);
	print_yes_no_row($vbphrase['active'],								'lottery[active]',						$lottery['active']);
	//print_input_row($vbphrase['display_order'], 						'lottery[displayorder]', 				$lottery['displayorder']);
	print_description_row($vbphrase['dbtech_vbshop_lottery_settings'], false, 2, 'optiontitle');
	print_input_row($vbphrase['dbtech_vbshop_ticket_price'], 			'lottery[ticketprice]', 				$lottery['ticketprice']);
	print_select_row($vbphrase['dbtech_vbshop_ticket_price_currency'], 	'lottery[currencyid]', 	$currencys, 	$lottery['currencyid']);
	print_input_row($vbphrase['dbtech_vbshop_main_numbers_drawn'], 		'lottery[numbers][main]', 				$lottery['numbers']['main']);
	print_input_row($vbphrase['dbtech_vbshop_bonus_numbers_drawn'], 	'lottery[numbers][bonus]', 				$lottery['numbers']['bonus']);
	if (VBSHOP::$isPro)
	{
		print_input_row($vbphrase['dbtech_vbshop_total_numbers_drawn'], 'lottery[numbers][total]', 				$lottery['numbers']['total']);
		print_input_row($vbphrase['dbtech_vbshop_draw_frequency'], 		'lottery[drawinterval]', 				$lottery['drawinterval']);
	}
	else
	{
		construct_hidden_code('lottery[numbers][total]', 	34);
		construct_hidden_code('lottery[drawinterval]', 		0);
	}
	print_time_row($vbphrase['dbtech_vbshop_next_draw_date'], 			'lottery[nextdraw]', 					$lottery['nextdraw'], false);	
	for ($i = 1; $i <= 10; $i++)
	{
		print_description_row($vbphrase['dbtech_vbshop_prize_settings'], false, 2, 'optiontitle');		
		print_select_row($vbphrase['dbtech_vbshop_prize_x'] . $i, 		'lottery[prizes][' . $i . '][prizeid]', 	$lotteryprizes, $lottery['prizes']["$i"]['prizeid']);
		print_input_row($vbphrase['dbtech_vbshop_payout_x'] . $i, 		'lottery[prizes][' . $i . '][prize]', 						(isset($lottery['prizes']["$i"]['prize']) ? $lottery['prizes']["$i"]['prize'] : 0));
		print_select_row($vbphrase['dbtech_vbshop_currency_x'] . $i, 	'lottery[prizes][' . $i . '][currencyid]', 	$currencys, 	$lottery['prizes']["$i"]['currencyid']);
	}
	print_description_row($vbphrase['permissions'], false, 2, 'optiontitle');
	print_cells_row($headings, 0, 'thead');	
	print_label_row('&nbsp;', '
		<input type="button" value="' . $vbphrase['all_yes'] . '" onclick="vBShop_Admin.toggleRadio(this.form, 1, \'lottery[permissions]\');" class="button" />
		<input type="button" value=" ' . $vbphrase['all_no'] . '" onclick="vBShop_Admin.toggleRadio(this.form, 0, \'lottery[permissions]\');" class="button" />
		<input type="button" value=" ' . $vbphrase['all_default'] . '" onclick="vBShop_Admin.toggleRadio(this.form, -1, \'lottery[permissions]\');" class="button" />
	');
	foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup)
	{
		print_yes_no_other_row($usergroup['title'], 'lottery[permissions][' . $usergroupid . ']', $vbphrase['default'], (isset($lottery['permissions'][$usergroupid]) ? $lottery['permissions'][$usergroupid] : -1));
	}
	print_submit_row(($lotteryid ? $vbphrase['save'] : $vbphrase['dbtech_vbshop_add_new_lottery']));	
	VBSHOP::js('_admin');
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'lotteryid' 	=> TYPE_UINT,
		'lottery' 		=> TYPE_ARRAY,
	));
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Lottery', $vbulletin, ERRTYPE_CP);
	
	// set existing info if this is an update
	if ($vbulletin->GPC['lotteryid'])
	{
		if (!$existing = VBSHOP::$cache['lottery']["{$vbulletin->GPC[lotteryid]}"])
		{
			// Couldn't find the lottery
			print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_lottery'], $vbulletin->GPC['lotteryid']);
		}
		
		// Set existing
		$dm->set_existing($existing);
				
		// Added
		$phrase = $vbphrase['dbtech_vbshop_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbshop_added'];
	}
	
	// lottery fields
	foreach ($vbulletin->GPC['lottery'] AS $key => $val)
	{
		if (!$vbulletin->GPC['lotteryid'] OR $existing["$key"] != $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	}
	
	// Save! Hopefully.
	$dm->save();
		
	define('CP_REDIRECT', 'vbshop.php?do=lottery');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_lottery'], $phrase);
}

// #############################################################################
if ($_REQUEST['action'] == 'delete')
{
	$vbulletin->input->clean_gpc('r', 'lotteryid', TYPE_UINT);
	
	print_cp_header(construct_phrase($vbphrase['dbtech_vbshop_delete_x'], $vbphrase['dbtech_vbshop_lottery']));
	print_delete_confirmation('dbtech_vbshop_lottery', $vbulletin->GPC['lotteryid'], 'vbshop', 'lottery', 'dbtech_vbshop_lottery', array('action' => 'kill'), '', 'title');
	print_cp_footer();
}

// #############################################################################
if ($_POST['action'] == 'kill')
{
	$vbulletin->input->clean_gpc('r', 'lotteryid', TYPE_UINT);
	
	if (!$existing = VBSHOP::$cache['lottery']["{$vbulletin->GPC[lotteryid]}"])
	{
		// Couldn't find the lottery
		print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_lottery'], $vbulletin->GPC['lotteryid']);
	}
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Lottery', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
	$dm->delete();
	
	define('CP_REDIRECT', 'vbshop.php?do=lottery');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_lottery'], $vbphrase['dbtech_vbshop_deleted']);	
}

print_cp_footer();