<?php

// Call in the XComponents engine and options file
define('MOD_PHP', substr(PHP_SAPI, 0, 3) != 'cgi'); // Are we running as mod_php?
define('DOCROOT', 
	MOD_PHP && isset($_SERVER['DOCUMENT_ROOT']) ? 
		$_SERVER['DOCUMENT_ROOT'] : 
		(
			MOD_PHP && isset($_SERVER['SCRIPT_FILENAME']) ? 
				substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])) : 
				(
					substr(str_repeat('../', count(explode('/', preg_replace('_/+_', '/', $_SERVER['PHP_SELF'])))-2), 0, -1) != '' ?
						substr(str_repeat('../', count(explode('/', preg_replace('_/+_', '/', $_SERVER['PHP_SELF'])))-2), 0, -1) :
						'.'
				)
		)
	);
include(DOCROOT . '/dmx/dmx_options.php');
include(DOCROOT . '/dmx/core/php/dmx_shop_handler.php');
include(DOCROOT . '/dmx/core/php/dmx_shop_components.php');

// Abs code starts here
$abs_root = '';
@include(DOCROOT . '/abs_version_control.php');

// Forward simple visitors
if (empty($_SERVER['QUERY_STRING']))
{
	header('LOCATION: /ens/demo/');
	exit;
}

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// ENS Logic

$display = NULL;

// Initialise Embedded Number Signup (ENS) array in session, if it doesn't exist
if (!isset($_SESSION['ENS']))
{
	$_SESSION['ENS'] = array(
		'mode' 				=> 1,
		'transfer_target' 	=> 'new',
		'full_trolley_url' 	=> '/numbers/ukgeo/checkout.php'
	);
}

// -------------------------------------------------------------------------------------------------

// Capture parameters in the ens_ namespace (embedded number signup)
// and merge with parameters from session (new parameters overwrite session parameters)

$ens = array();
preg_match_all('/ens_(.+?)=([^&]+)?&?/', $_SERVER['QUERY_STRING'], $matches);
foreach($matches[1] as $pname) $ens[$pname] = array_shift($matches[2]);
if (isset($ens['display']))
{
	// ens_display can set which view to display, but we don't want to remember this parameter
	$display = strtoupper($ens['display']);
	unset($ens['display']);
}
$ens = array_merge($_SESSION['ENS'], $ens);

// Look for additonal ens_xp_ params, (xparams originally supplied in the URL)
$xp = array();
foreach($ens as $key => $value)
{	
	if (substr($key, 0, 3) == 'xp_')
	{
		$xp[substr($key, 3)] = $value;
		unset($ens[$key]);	
	}
}
// Impose some rules, based on the ENS mode
if ($ens['mode'] == 1)
{
	// dmABS transfer mode: force full trolley URL
	$ens['full_trolley_url'] = '/numbers/ukgeo/checkout.php'; 
}
else
{
	// Self-contained signup mode: force transfer target
	$ens['transfer_target'] = 'top'; 
}
if (!in_array($ens['transfer_target'], array('top', 'new', 'new-force'))) $ens['transfer_target'] = 'top'; // NB: 'same' not allowed in Embedded Number Signup

// Finally, store non 'ens_xp_' parameters in the session
$_SESSION['ENS'] = $ens;

// -------------------------------------------------------------------------------------------------
// Has an XComponent generated a resultcode? If so, rewrite $display

$rcr = isset($dmx_resultcode['result']) ? $dmx_resultcode['result'] : NULL;

switch ($rcr)
{
	case 'confirm';
	case 'delete';
	case 'deleteerror';
	case 'confirmerror';
	case 'login';
	case 'numberpick';
	case 'register';
	case 'trolleyclicked';
		$display = 'TROLLEY';
		break;

	case 'typinv':
		$display = 'TYPICALINVOICE';
		break;

	case 'configure':
		$display = 'SVCPLANSELECTOR';
		break;
		
	case 'createaccount':
	case 'loginregister':
	case 'registererror':
		$display = 'REGISTER';
		break;
		
	case 'loginerror':
	case 'reauthenticate':
		$display = 'LOGIN';
		break;
	
	default:
		if (empty($display)) $display = 'NUMBERCHOOSER';
		break;
}

if (isset($_GET['showlogin'])) $display = 'LOGIN';

$skip_dmshop = in_array($display, array('COLLAPSEDTROLLEY', 'MINITROLLEY', 'COMPACTTROLLEY'));

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// TST ADDITIONAL PARAMS

function ens_get_tst_additional_params_json()
{
	// CONSIDER MOVING TO XCOMPONENTS LAYER... (see also /common/abs_lib.php)
	//
	$site_entry = !isset($_REQUEST['dmb1_SessRef']) && !isset($_COOKIE['dmb1_backup_session_ref']);
	if (!$site_entry) return '{}';
	$ta = new stdclass; 					// HOLDS TST_ADDITIONAL PARAMS
	$ta->tstw = 'dmABS';					// WebApp
	$ta->tstv = $GLOBALS['dmx_version'];	// Version -- Should this be dmABS version specifically?
	$ta->tstf = ens_get_tst_flags();		// WebApp-specific flags
	$d = $GLOBALS['dmx_debug_settings'];
	if (!isset($_GET['tstd']) && isset($d->send_tstd) && $d->tstd) $ta->tstd = $d->tstd; // Debug string (can not override tstd in URL)
	$json = new Services_JSON();
	$tst_additional_params_json = $json->encode($ta);
	return $tst_additional_params_json;
	//
	// END CONSIDER MOVING TO XCOMPONENTS LAYER
}

// -------------------------------------------------------------------------------------------------

function ens_get_tst_flags()
{
	// Add ENS-specific analytics flags to TST data
	
	global $dmx_options;
	
	// 'E' for Embedded Number Signup
	$f = 'E';
	if (isset($_GET['ens_mode']) && $_GET['ens_mode'] == '1')
	{
		$f .= 'T'; // dmABS transfer mode
	}
	else
	{
		$f .= 'X'; // Self-contained mode
	}
	
	// Is site using Google Analytics?
	//
	// CONSIDER MOVING TO XCOMPONENTS LAYER... (see also /common/abs_lib.php)
	//
	if ($dmx_options['ganal']['accno'] != 'OFF') $f .= 'G';

	// Does URL contain NumberChooser control parameters?
	function preg_array($pattern, $array)
	{
		$match = FALSE;
		foreach ($array as $key => $value)
		{
			if (preg_match($pattern, $value))
			{
				$match = TRUE;
				break;
			}
		}
		return $match;
	}
	$url_keys = array_keys($_GET);
	if (preg_array('/dmx_range*/', 		$url_keys))	$f .= 'N';
	if (preg_array('/dmx_service*/', 	$url_keys))	$f .= 'N';
	if (preg_array('/dmx_plan*/', 		$url_keys))	$f .= 'N';
	if (preg_array('/dmx_gold*/', 		$url_keys))	$f .= 'N';
	if (preg_array('/dmx_areacode*/', 	$url_keys))	$f .= 'N';
	$f = preg_replace('/N+/', 'N', $f);
	//
	// END CONSIDER MOVING TO XCOMPONENTS LAYER
	
	return $f;
}

// -------------------------------------------------------------------------------------------------

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>ENS - Embedded Number Signup</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" value="Thu, 16 Mar 2000 11:00:00 GMT" />

<!-- ************************** -->
<!-- (1) INITIALISE XCOMPONENTS -->
<!-- ************************** -->
<?php
dmx_initialise_trolley($skip_dmshop);
$tst_additional_params_json = ens_get_tst_additional_params_json();
?>

<!-- **************************** -->
<!-- (2) SEED ADDITIONAL TST DATA -->
<!-- **************************** -->

<script language="javascript" type="text/javascript">
/*<![CDATA[[*/
try
{
	var tst_additional_params = <?=$tst_additional_params_json;?>;
}
catch(error) {;}
/*]]>*/
</script>

<script language="javascript" type="text/javascript">
/*<![CDATA[[*/
var abs_root = '<?=$abs_root;?>';
/*]]>*/
</script>

<!-- *************** -->
<!-- (3) INCLUDE TST -->
<!-- *************** -->
<?php
dmx_include_tst();
?>
</head> <!-- XCom & TST modifications added -->

<style type="text/css">

body
{
	margin: 0px;
	padding: 1px 0px;
}

.dmx .trolley .full .grabut_left_forward ul li a, #continue_shopping.grabut_left_forward ul li a
{
	width: 125px;
}

#continue_shopping
{
	margin-left: 3px;
}

#areacode_button
{
	margin: 5px 0px 5px 20px;
}

#identity
{
	color: #999;
	font-size: 8px;
	margin-top: 0px;
	clear: right;
	float: right;
}

</style>


</head> <!-- XCom & TST modifications added -->

<body class="dmb0">

<?php

// Render

// Default xparams
$xparams = array();
$xparams['showpreamble'] 	= 1;
$xparams['showheader'] 		= 0;
$xparams['showborder'] 		= 0;
$xparams['embedded'] 		= 1;

switch ($display)
{
	case 'COLLAPSEDTROLLEY':
	case 'MINITROLLEY':
		$xparams['variant'] 				= 'collapsed';
		$xparams['showborder'] 				= 1;
		$xparams['auto_sync_interval'] 		= 5;
		$xparams['transfer_target'] 		= $ens['transfer_target'];
		$xparams['result_trolleyclicked'] 	= $ens['full_trolley_url'];
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.trolley', 'troy', $xparams);
		break;

	case 'COMPACTTROLLEY':
		$xparams['variant'] 				= 'compact';
		$xparams['showicons'] 				= 0;
		$xparams['showactions'] 			= 0;
		$xparams['auto_sync_interval'] 		= 5;
		$xparams['transfer_target'] 		= $ens['transfer_target'];
		$xparams['result_trolleyclicked'] 	= $ens['full_trolley_url'];
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.trolley', 'troy', $xparams);
		break;
		
	case 'FULLTROLLEY':
	case 'TROLLEY':
		$xparams['transfer_target'] 	= $ens['transfer_target'];
		$xparams['variant'] 			= 'full';
		$xparams['showoptions'] 		= 1;
		$xparams['auto_sync_interval'] 	= 5;
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.trolley', 'troy', $xparams);
		?>
		<div id="continue_shopping" class="grabut_left_forward">
			<ul>
				<li><a href="<?=DMX_SELF;?>">Continue Shopping</a></li>
			</ul>
		</div>
		<?php
		break;
		
	case 'TYPICALFIRSTINVOICE':
		dmx_render('dmshop.typicalfirstinvoice', 'inv', $xparams);
		break;
	
	case 'SVCPLANSELECTOR':
		$xparams['width'] 		= 680;
		$xparams['link_cce'] 	= 'carlos';
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.serviceplanselector', 'sidney', $xparams);
		break;
	
	case 'LOGIN':
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.login', 'larry', $xparams);
		break;
	
	case 'REGISTER':
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.register', 'reggie', $xparams);
		?>
		<div class="grabut_left_forward">
			<ul>
				<li><a href="?showlogin=1">Existing customer? Login here</a></li>
			</ul>
		</div>
		<?php
		break;

	case 'ORDERDEALERSHIP':
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.orderdealership', 'reggiedeal', $xparams);
		?>
		<div class="grabut_left_forward">
			<ul>
				<li><a href="?showlogin=1">Existing customer? Login here</a></li>
			</ul>
		</div>
		<?php
		break;

	case 'NUMBERCHOOSER':
	default:
		$state = dmx_expose_nc_state();
		?>
		<?php if ($state->range == 'ukgeo') : ?>
			<div style="position: relative;">
				<?php
				include(DOCROOT . '/dmx/demo/xdrivers/areacode_chooser.php');
				areacode_chooser(DOCROOT . '/dmx/demo/xdrivers/areacodes.csv', 'charlie');
				?>
				<div id="areacode_button" class="grabut_right_reload">
					<ul>
						<li><a href="#" onclick="this.blur(); xdriver.charlie.areacode_chooser.setStyle('display', 'block'); return false;">Change areacode</a></li>
					</ul>
				</div>
			</div>
		<?php endif; ?>
		<?php
		$xparams['cols'] 		= 3;
		$xparams['showclass'] 	= 0;
		$xparams['showtariffs'] = 0;
		$xparams['tariffs'] 	= '*';
		if ($ens['mode'])
		{
			if (!in_array($ens['transfer_target'], array('top', 'new', 'new-force'))) $ens['transfer_target'] = 'top'; // NB: 'same' not allowed in Embedded Number Signup
			$xparams['transfer_target'] 	= $ens['transfer_target'];
			$xparams['result_numberpick'] 	= '/numbers/0800/checkout.php';
		}
		else
		{
			$xparams['transfer_target'] = 'same';
		}
		$xparams = array_merge($xparams, $xp);
		dmx_render('dmshop.numberchooser', 'charlie', $xparams);
		break;
}

?>

<div id="identity">
	<?php if ($display != 'COLLAPSEDTROLLEY' && $display != 'MINITROLLEY') : // Display user's login status ?>
		<?php if (isset($dmx_init_response['DMID']) && $dmx_init_response['DMID']) :?>
			<?=$dmx_init_response['DMID'];?> <?php if ($dmx_init_response['Authenticated']) : ?>(+)<?php else : ?>(-)<?php endif;?>
		<?php else: ?>
			You are not logged in
		<?php endif; ?>
	<?php endif; ?>
</div>

<?php

dmx_render('dmshop.debug');
dmx_render('dmshop.benchmarks');

?>

</body>
</html>