<?php

// dmx_shop_handler.php
// -------------------------------------------------------------------------------------------------
// The 'action handler' for the dmShop family of XComponents
// Handle actions passed into page (as POST or GET parameters),
// communicating with the dmProtocol server as necessary,
// and issue HTTP redirects if the resultcode (generated by the action)
// corresponds to a nextpage_<resultcode> passed in by the component
//
// Revision   > $Rev: 152 $
// Date		  > $Date: 2009-11-26 17:37:23 +0000 (Thu, 26 Nov 2009) $
// Author     > RAK for DML
// Copyright  > (C) Digital Mail Limited (2005-2009)
// -------------------------------------------------------------------------------------------------

require_once('dmx_library.php');
require_once('dmx_run.php');

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// F U N C T I O N S
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

function dmx_handle_action($comp_class, $comp_name, $action)
{
	global $dmx_debug;
	
	$dmx_debug->heading("dmx_handle_action($comp_class, $comp_name, $action)");
	
	switch($comp_class)
	{
		case 'login':
			$resultcode = dmx_handle_action_login($comp_name, $action);
			break;
		case 'loginstatus':
			$resultcode = dmx_handle_action_loginstatus($comp_name, $action);
			break;
		case 'numberchooser':
			$resultcode = dmx_handle_action_numberchooser($comp_name, $action);
			break;
		case 'orderdealership':
			$resultcode = dmx_handle_action_orderdealership($comp_name, $action);
			break;
		case 'register':
			$resultcode = dmx_handle_action_register($comp_name, $action);
			break;
		case 'serviceplanselector':
			$resultcode = dmx_handle_action_serviceplanselector($comp_name, $action);
			break;
		case 'trolley':
			$resultcode = dmx_handle_action_trolley($comp_name, $action);
			break;
		default:
			$resultcode = 'unknown_component_error';
			$dmx_debug->msg('<b>UNKNOWN COMPONENT CLASS: ' . $comp_class . '</b>');
			break;
	}
	return $resultcode;
}

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

function dmx_handle_redirects($resultcode)
{
	// Handle any HTTP redirects, in response to generating a specific resultcode
	// These are specigied in the $xparams array as parameters of the form
	// $xparam['result_<$resultcode>'] = URL
	
	global $dmx_rc, $dmx_options, $dmx_debug;
	for ($i=0; $i<count($dmx_rc); $i++)
	{
		preg_match('/(.+?)=(.+)/', $dmx_rc[$i], $matches);
		list(, $cond, $url) = $matches;
		if ($resultcode['result'] == $cond)
		{
			// Jump to specified URL, passing on TST session reference and any additional parameters that are not part of the 'dmx_' namespace
			$unmod_url = $url;
			$append_chr = strpos($url, '?') ? '&' : '?';
			$extra_params = preg_replace('/dmx_.+?=[^&]+&?/', '', $_SERVER['QUERY_STRING']); // Strip out params in dmx_ namespace, but pass others on
			$extra_params .= ($extra_params ? '&' : '') . 'dmx_resultcode=' . dmx_serialize($GLOBALS['dmx_resultcode']); // Pass on the resultcode
			$anchor = strpos($url, '#') ? substr($url, strpos($url, '#')) : ''; // Anchors must be the last part of the URL after the query string
			if ($anchor) $url = substr($url, 0, strpos($url, '#'));
			
			// Support for dmABS Easy SEO
			if (isset($_SESSION['ABS_SEO'][substr($url, 0, -4)]) && !empty($_SESSION['ABS_SEO'][substr($url, 0, -4)]['desired_url']) && substr(strtoupper(PHP_SAPI), 0, 6) == 'APACHE')
			{
				$url = $_SESSION['ABS_SEO'][substr($url, 0, -4)]['desired_url'].'.php'; 			
			}
			// End support for dmABS Easy SEO
			
			$destination = $url . $append_chr . $extra_params . $anchor;
			if ($dmx_options['debug_level'] < 2)
			{
				header('LOCATION: ' . $destination);
				exit;
			}
			$dmx_debug->msg('Resultcode matched: <b>' . $cond . ' => ' . $url . '</b>');
			
			echo('<h2>XComponent powered navigation...</h2>');
			echo('<b>Matched result: ' . $resultcode['result'] . '</b><br />');
			echo('Page : ' . $unmod_url . '<br />');
			echo('Destination : <a href=\'' . $destination . '\'>' . $destination . '</a><br />');
			echo('<br />');
			echo('<b>All resultcodes</b><pre>' . print_r($dmx_rc, 1) . '</pre>');
			echo('<br /><br >');
			global $dmx_debug;
			$dmx_debug_msg = $dmx_debug->get();
			// $render = substr($dmx_options['doctype'], 0, 5) == 'XHTML' ? 'xhtml/' :  'html/'; // <!-- Myabe re-instate when we support XHTML fully
			$render = 'html/';
			$comp_name = 'debugger';
			$dmx_debug_msg = $dmx_debug->display(1);
			include(DOCROOT . $dmx_options['templates'] . $render . 'debug.tpl');
			exit;
		}
	}
}

// -------------------------------------------------------------------------------------------------
// C O M P O N E N T   A C T I O N   H A N D L E R S
// -------------------------------------------------------------------------------------------------

function dmx_handle_action_login($comp_name, $action)
{
	// Handle actions issued by login components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	$store = array();
	// Set fields to store for redisplay on login failure
	$fields = array('dmx_email');

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'go_to_register':
			return(array('result' => 'createaccount', 'details' => ''));
			break;

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

		case 'login':
			// Check user input
			$test[] = array($_POST['dmx_email'], 'dmx_email', 'Please enter your email address');
			$test[] = array($_POST['dmx_pin'], 'dmx_pin', 'Please enter your PIN number');
			$form = dmx_test_exists($test);
			if ($form['message'])
			{
				$store['comp_err_msg'] = $form['message'];
				$store['form']['value'] = dmx_save_form_field_values(array('dmx_email'), $_POST);
				$store['form']['error'] = $form['alert'];
				dmx_store($comp_name, $store);
				return(array('result' => 'loginerror', 'details' => 'FormValFailed'));
			}		
			unset($test);
			$test[] = array($_POST['dmx_email'], 'dmx_email', 'Please enter a valid email address');
			$form = dmx_test_email($test);
			if ($form['message'])
			{
				$store['comp_err_msg'] = $form['message'];
				$store['form']['value'] = dmx_save_form_field_values(array('dmx_email'), $_POST);
				$store['form']['error'] = $form['alert'];
				dmx_store($comp_name, $store);
				return(array('result' => 'loginerror', 'details' => 'FormValFailed'));
			}		
			
			$dmshop->_R['Cmd'] = 'Login';
			$dmshop->_R['DMID'] = $_POST['dmx_email'];
			$dmshop->_R['Password'] = $_POST['dmx_pin'];
			$dmx_debug->msg('<b>ATTEMPTING TO LOGIN</b> DMID: ' . $dmshop->_R['DMID'] . ' / Password ' . $dmshop->_R['Password']);

			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;
			
			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'LoginAck')
			{
				return(array('result' => 'login', 'details' =>  $dmx_response['DMID']));
			}
			else if ($dmx_response['Cmd'] == 'LoginNak')
			{
				$details = 'BadIDorPIN';
				$e['dmx_email'] = $e['dmx_pin'] = '_error';
				$store['form']['error'] = $e;
			}
			$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
			$store['comp_err_msg'] = dmx_translate_err_code('login', $details);
			dmx_store($comp_name, $store);
			return(array('result' => 'loginerror', 'details' => $details));
			break;

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

		case 'reminder':
			$dmshop->_R['Cmd'] = 'LoginReminder';
			$dmshop->_R['Email'] = $_POST['dmx_email'];
			$dmx_debug->msg('<b>ASKING FOR PASSWORD REMINDER</b> DMID: ' . $dmshop->_R['Email'] );
			
			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;

			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'LoginReminderAck')
			{
				$store['comp_msg'] = 'A PIN reminder has been emailed to ' . $_POST['dmx_email'] . '<br />';
				dmx_store($comp_name, $store);
				return(array('result' => 'reminder', 'details' =>  $_POST['dmx_email']));
			}
			else if ($dmx_response['Cmd'] == 'LoginReminderNak')
			{
				$details = 'BadID';
				$store['form']['error']['dmx_email'] = '_error';
			}
			$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
			$store['comp_err_msg'] = dmx_translate_err_code('login', $details);
			dmx_store($comp_name, $store);
			return(array('result' => 'loginerror', 'details' => $details));
			break;
		
		// -----------------------------------------------------------------------------------------

		default:
			$dmx_debug->msg('<b>UNKNOWN LOGIN ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_loginstatus($comp_name, $action)
{
	// Handle actions issued by loginstatus components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'login':
			return(array('result' => 'loginregister', 'details' => ''));
			break;

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

		case 'logout':
			$dmshop->_R['Cmd'] = 'KillTrolley';
			$dmx_debug->msg('<b>ATTEMPTING TO LOGOUT</b> TrolleyID: ' . $dmshop->_R['TrolleyID']);
			
			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;
		
			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'KillTrolleyAck')
			{
				// Redirect to self, forgetting the session reference
				$GLOBALS['dmx_rc'][] = 'logout=' . DMX_SELF;
				setcookie('dmb1_backup_session_ref', 'nonsense', 1, '/');											// Kill backup cookie - 0 denotes eternal
				$_SERVER['QUERY_STRING'] = preg_replace('/dmb1_SessRef=[^&]+&?/', '', $_SERVER['QUERY_STRING']); 	// Strip out TST ref in URL
				return(array('result' => 'logout', 'details' => $dmx_session));
			}
			else if ($dmx_response['Cmd'] == 'LogoutNak')
			{
				return(array('result' => 'logouterror', 'details' => $dmx_response['Reason']));
			}
			break;

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

		default:
			$dmx_debug->msg('<b>UNKNOWN LOGINSTATUS ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_numberchooser($comp_name, $action)
{
	// Handle actions issued by numberchooser components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session, $dmx_memory;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'search':
			
			$store['class'] = 'NumberChooser';

			// Check user input
			$test[1] = isset($_REQUEST['dmx_pattern1']) && $_REQUEST['dmx_pattern1'] && !(preg_match('/^[[:alnum:]!*]*$/', trim($_REQUEST['dmx_pattern1'])));
			$test[2] = isset($_REQUEST['dmx_pattern2']) && $_REQUEST['dmx_pattern2'] && !(preg_match('/^[[:alnum:]!*]*$/', trim($_REQUEST['dmx_pattern2'])));
			if ($test[1] || $test[2] )
			{
				$store['comp_err_msg'] = 'Special sequences must contain only the letters A-Z, the digits 0-9, and the wildcards ! and *';
				$store['form']['error']['dmx_pattern1'] = $test[1] ? '_error' : '';
				$store['form']['error']['dmx_pattern2'] = $test[2] ? '_error' : '';
			}
			$fields = array('dmx_pattern1', 'dmx_pattern2');
			$store['form']['value'] = dmx_save_form_field_values($fields, $_REQUEST);
			
			// Store search in NumberChooser memory
			$nc = dmx_translate_tariff($_REQUEST['dmx_tariff']);
			$store['range'] 	= $nc->range;
			$store['service'] 	= $nc->service;
			$store['plan'] 		= $nc->plan;
  			if (isset($_REQUEST['dmx_goldrange'])) $store['gold'] = $_REQUEST['dmx_goldrange'];
  			
			$prefix				= isset($_REQUEST['dmx_prefix_pattern']) ? $_REQUEST['dmx_prefix_pattern'] : NULL;
			$store['prefix'] 	= $prefix;

 			if ($nc->range == 'ukgeo')
 			{
 				$areacode = $prefix ? '0' . substr($prefix, 3) : NULL; // Replace !44 with 0
 				$res = dmx_validate_areacode($areacode);
 				$store['areacode'] 	= $res['areacode'];
 				$store['areaname'] 	= $res['areaname'];
 				$store['prefix'] 	= $prefix;
 			}
 			else
 			{
 				$store['areacode'] 	= NULL;
 				$store['areaname'] 	= NULL;
 			}

			$g = explode('-', $_REQUEST['dmx_goldrange']);
			if ($g[0] == '0')
			{
 				$store['SortedBy'] 	= 'Num_A';
 				$store['Page']		= 'Rand';
 			}
 			else
 			{
 				$store['SortedBy']	= 'GV_D';
 				$store['Page']		= '1';
			}

 			// If the memory is set but the range has changed, forget the prefix pattern
 			/*
 			if (isset($dmx_memory[strtoupper($comp_name)]['range']) && $dmx_memory[strtoupper($comp_name)]['range'] != $nc->range)
 			{
				unset($dmx_memory[strtoupper($comp_name)]['form']['value']['dmx_prefix_pattern']);
 				$store['form']['value']['dmx_prefix_pattern'] = '';
			}
			*/
			
			$store['showresults'] = 1;
			
			dmx_store($comp_name, $store);
			return(array('result' => 'search', 'details' => ''));
			break;
		
		// -----------------------------------------------------------------------------------------

		case 'page':
			$store['class'] = 'NumberChooser';
			$store['Page']  = $_REQUEST['dmx_page'];
			dmx_store($comp_name, $store);
			return(array('result' => 'page', 'details' => '')); // OR SHOULD THE RESULT OF THIS BE 'search';
			break;
			
		// -----------------------------------------------------------------------------------------

		case 'add_to_trolley':
			$dmshop->_R['Cmd'] 				= 'AddItemToTrolley';
			$dmshop->_R['Item.Number'] 		= $_REQUEST['dmx_num'];
			$dmshop->_R['Item.TariffSpec'] 	= $_REQUEST['dmx_tariffspec'];
			$dmshop->_R['_Store_trolley'] = '';
			// $dmshop->_R['Item.Tariff'] = ???;
			// $dmshop->_R['Item.UserAlias'] = ???;
			$dmx_debug->msg('<b>ATTEMPTING TO ADD NO TO TROLLEY:</b> ' . $dmshop->_R['Item.Number']);

			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;
			
			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'AddItemToTrolleyAck')
			{
				return(array('result' => 'numberpick', 'details' => $dmx_response['FmtNum']));
			}
			else if ($dmx_response['Cmd'] == 'AddItemToTrolleyNak')
			{
				$dmx_response['Reason'] = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
				switch($dmx_response['Reason'])
				{
					case 'Item not free':
						$details = 'NumberGone';
						break;
					case 'Trolley full':
						$details = 'TrolleyFull';
						break;
					default:
						$details = $dmx_response['Reason'];
				}
				$store['comp_err_msg'] = dmx_translate_err_code('numberchooser', $details);
				dmx_store($comp_name, $store);
				return(array('result' => 'numberpickerror', 'details' => $details));
			}
			break;
		
		// -----------------------------------------------------------------------------------------

		default:
			$dmx_debug->msg('<b>UNKNOWN NUMBERCHOOSER ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_orderdealership($comp_name, $action)
{
	// Handle actions issued by orderdealership components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	$store = array();
	// Set fields to store for redisplay on registration failure
	$fields = array('dmx_companyname', 'dmx_brandname', 'dmx_contactname', 'dmx_contactemail', 'dmx_custservemail', 'dmx_contactphone', 'dmx_contactfax', 'dmx_exdmid', 'dmx_mainwebsiteurl', 'dmx_custbasebiz', 'dmx_custbaseres', 'dmx_prodfocus', 'dmx_sellinboundnum', 'dmx_selltelserv', 'dmx_selltelhard', 'dmx_comments');

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'orderdealership':
			// Check user input
			$test[] = array($_POST['dmx_companyname'], 		'dmx_companyname', 	'Please enter your company name');
			$test[] = array($_POST['dmx_brandname'], 		'dmx_brandname', 	'Please enter your one-word brand name');
			$test[] = array($_POST['dmx_contactname'], 		'dmx_contactname', 	'Please enter a contact name');
			$test[] = array($_POST['dmx_contactemail'], 	'dmx_contactemail', 'Please enter a contact email address');
			$test[] = array($_POST['dmx_custservemail'], 	'dmx_custservemail','Please enter a email address for customer services');
			$test[] = array($_POST['dmx_contactphone'], 	'dmx_contactphone', 'Please enter a telephone number you can be contacted on');
			$test[] = array($_POST['dmx_contactfax'], 		'dmx_contactfax',	'Please enter a fax number you can be contacted on');
			$form = dmx_test_exists($test);
			if ($form['message'])
			{
				$store['comp_err_msg'] = $form['message'];
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error'] = array_merge($form['alert']);
				dmx_store($comp_name, $store);
				return(array('result' => 'orderdealershiperror', 'details' => 'FormValFailed'));
			}		
			$l = strlen($_POST['dmx_brandname']);
			if ($l < 5 || $l > 30)
			{
				$store['comp_err_msg'] = 'Your brand name should be between 5 and 30 characters long';
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error']['dmx_brandname'] = '_error';
				dmx_store($comp_name, $store);
				return(array('result' => 'orderdealershiperror', 'details' => 'FormValFailed'));
			}
			if (!ereg('^[[:alnum:]-]+$', $_POST['dmx_brandname']))
			{
				$store['comp_err_msg'] = 'Your brand name should only contain A-Z, a-z, 0-9 and hyphens (and spaces are not allowed)';
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error']['dmx_brandname'] = '_error';
				dmx_store($comp_name, $store);
				return(array('result' => 'orderdealershiperror', 'details' => 'FormValFailed'));
			}
			unset($test);
			$test[] = array($_POST['dmx_contactemail'], 'dmx_contactemail', 'Please enter a valid contact email address');
			$test[] = array($_POST['dmx_custservemail'], 'dmx_custservemail', 'Please enter a valid customer services email address');
			$form = dmx_test_email($test);
			if ($form['message'])
			{
				$store['comp_err_msg'] = $form['message'];
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error'] = $form['alert'];
				dmx_store($comp_name, $store);
				return(array('result' => 'orderdealershiperror', 'details' => 'FormValFailed'));
			}		
			
			// Now execute request
			$dmshop->_R['Cmd'] 				= 'OrderDealership';
			$dmshop->_R['DealerType'] 		= $_POST['dmx_dealer_type'];
			$dmshop->_R['CompanyName'] 		= $_POST['dmx_companyname'];
			$dmshop->_R['BrandName'] 		= $_POST['dmx_brandname'];
			$dmshop->_R['ContactName']		= $_POST['dmx_contactname'];
			$dmshop->_R['ContactEmail']		= $_POST['dmx_contactemail'];
			$dmshop->_R['CustServEmail']	= $_POST['dmx_custservemail'];
			$dmshop->_R['ContactPhone']		= $_POST['dmx_contactphone'];
			$dmshop->_R['ContactFax']		= $_POST['dmx_contactfax'];
			$dmshop->_R['MainWebsiteURL']	= $_POST['dmx_mainwebsiteurl'];
			$dmshop->_R['CustBaseBiz'] 		= $_POST['dmx_custbasebiz'];
			$dmshop->_R['CustBaseRes'] 		= $_POST['dmx_custbaseres'];
			$dmshop->_R['ProdFocus'] 		= $_POST['dmx_prodfocus'];
			$dmshop->_R['SellInboundNum']  	= isset($_POST['dmx_sellinboundnum']) 	? '1' : '0';
			$dmshop->_R['SellTelServ']  	= isset($_POST['dmx_selltelserv']) 		? '1' : '0';
			$dmshop->_R['SellTelHard']  	= isset($_POST['dmx_selltelhard']) 		? '1' : '0';
			$dmshop->_R['Comments']  		= $_POST['dmx_comments'];
			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;

			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => 'Badly formed response'));
			}
			if ($dmx_response['Cmd'] == 'OrderDealershipAck')
			{
				return(array('result' => 'order', 'details' => $dmx_response['NewDealerID']));
			}
			else if ($dmx_response['Cmd'] == 'OrderDealershipNak')
			{
				$details = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['comp_err_msg'] = dmx_translate_err_code('register', $details);
				dmx_store($comp_name, $store);
				return(array('result' => 'orderdealershiperror', 'details' => $details));
			}
			break;

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

		default:
			$dmx_debug->msg('<b>UNKNOWN REGISTERDEALER ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_register($comp_name, $action)
{
	// Handle actions issued by register components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	$store = array();
	// Set fields to store for redisplay on registration failure
	$fields = array('dmx_title', 'dmx_first', 'dmx_last', 'dmx_email', 'dmx_newslevel',
					'dmx_company', 'dmx_addr1', 'dmx_addr2', 'dmx_addr3', 'dmx_towncity', 'dmx_pc_zip', 'dmx_country',
					'dmx_tel_day', 'dmx_tel_home', 'dmx_tel_mobile', 'dmx_fax',
					'dmx_pin1', 'dmx_pin2', 'dmx_mem_date', 'dmx_mem_word');

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'register':
			// Check user input
			$test[] = array($_POST['dmx_first'],	'dmx_first',	'Please enter your first name');
			$test[] = array($_POST['dmx_last'],		'dmx_last',		'Please enter your last name');
			$test[] = array($_POST['dmx_email'],	'dmx_email',	'Please enter your email address');
			$test[] = array($_POST['dmx_tel_day'],	'dmx_tel_day',	'Please specify a daytime telephone number');
			$form1 = dmx_test_exists($test);
			unset($test);
			$test[] = array($_POST['dmx_pin1'],		'dmx_pin1',		'Please choose a PIN number');
			$test[] = array($_POST['dmx_pin2'],		'dmx_pin2',		'Please repeat your PIN number');
			$test[] = array($_POST['dmx_mem_date'], 'dmx_mem_date', 'Please enter a memorable date');
			$test[] = array($_POST['dmx_mem_word'], 'dmx_mem_word', 'Please give us a memorable word');
			$form2 = dmx_test_exists($test);
			if ($form1['message'] || $form2['message'])
			{
				$store['comp_err_msg'] = $form1['message'] . $form2['message'];
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error'] = array_merge($form1['alert'], $form2['alert']);
				dmx_store($comp_name, $store);
				return(array('result' => 'registererror', 'details' => 'FormValFailed'));
			}		
			unset($test);
			$test[] = array($_POST['dmx_email'], 'dmx_email', 'Please enter a valid email address');
			$form = dmx_test_email($test);
			if ($form['message'])
			{
				$store['comp_err_msg'] = $form['message'];
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error'] = $form['alert'];
				dmx_store($comp_name, $store);
				return(array('result' => 'registererror', 'details' => 'FormValFailed'));
			}		
			if ($_POST['dmx_pin1'] != $_POST['dmx_pin2'])
			{
				$store['comp_err_msg'] = 'Both PIN numbers must be identical';
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['form']['error']['dmx_pin1'] = $store['form']['error']['dmx_pin2'] = '_error';
				dmx_store($comp_name, $store);
				return(array('result' => 'registererror', 'details' => 'FormValFailed'));
			}
			
			// Now execute request
			$dmshop->_R['Cmd'] 			= 'Register';
			$dmshop->_R['Email'] 		= $_POST['dmx_email'];
			$dmshop->_R['Title'] 		= $_POST['dmx_title'];
			$dmshop->_R['Forename'] 	= $_POST['dmx_first'];
			$dmshop->_R['Surname'] 		= $_POST['dmx_last'];
			$dmshop->_R['Company'] 		= $_POST['dmx_company'];
			$dmshop->_R['Addr1'] 		= $_POST['dmx_addr1'];
			$dmshop->_R['Addr2'] 		= $_POST['dmx_addr2'];
			$dmshop->_R['Addr3'] 		= isset($_POST['dmx_addr3']) ? $_POST['dmx_addr3'] : '';
			$dmshop->_R['State'] 		= $_POST['dmx_towncity'];
			$dmshop->_R['Country'] 		= $_POST['dmx_country'];
			$dmshop->_R['Postcode'] 	= strtoupper($_POST['dmx_pc_zip']);
			$dmshop->_R['PhoneDay'] 	= $_POST['dmx_tel_day'];
			$dmshop->_R['PhoneHome'] 	= $_POST['dmx_tel_home'];
			$dmshop->_R['PhoneMobile'] 	= $_POST['dmx_tel_mobile'];
			$dmshop->_R['Fax'] 			= $_POST['dmx_fax'];
			$dmshop->_R['PIN'] 			= $_POST['dmx_pin1']; // ADD PIN CHECKING!
			$dmshop->_R['DOB'] 			= $_POST['dmx_mem_date'];
			$dmshop->_R['MMN'] 			= $_POST['dmx_mem_word'];
			$dmshop->_R['Remote_Addr']  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
			$dmshop->_R['User_Agent'] 	= isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
			$dmshop->_R['NewsLevel'] 	= isset($_POST['dmx_newslevel']) ? $_POST['dmx_newslevel'] : 0;

			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;

			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => 'Badly formed response'));
			}
			if ($dmx_response['Cmd'] == 'RegisterAck')
			{
				return(array('result' => 'register', 'details' => $dmx_response['DMID']));
			}
			else if ($dmx_response['Cmd'] == 'RegisterNak')
			{
				$dmx_response['Reason'] = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
				switch($dmx_response['Reason'])
				{
					case 'DOB out of range':
						$details = 'BadDateOfBirth';
						$store['form']['error']['dmx_mem_date'] = '_error';
						break;
					case 'MMN out of range':
						$details = 'BadMothersMaidenName';
						$store['form']['error']['dmx_mem_word'] = '_error';
						break;
					case 'DMID Taken':
						$details = 'DMIDTaken';
						$store['form']['error']['dmx_email'] = '_error';
						break;
					case 'Unable to set up billing accounts':
						$details = 'BadBilling';
						break;
					default:
						$details = '';
				}
				$store['form']['value'] = dmx_save_form_field_values($fields, $_POST);
				$store['comp_err_msg'] = dmx_translate_err_code('register', $details);
				dmx_store($comp_name, $store);
				return(array('result' => 'registererror', 'details' => $details));
			}
			break;

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

		default:
			$dmx_debug->msg('<b>UNKNOWN REGISTER ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_serviceplanselector($comp_name, $action)
{
	// Handle actions issued by serviceplanselector components
	
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session, $dmx_err_msg;

	$dmshop->_R = array();

	switch($action)
	{
		// -----------------------------------------------------------------------------------------

		case 'modify':
			// Modify the tariff attached to a number in the trolley, and/or add a free trial
			
			if (isset($_REQUEST['dmx_tariff']))
			{
				$dmshop->_R['TrolleyID'] 		= $dmx_session;	
				$dmshop->_R['Number'] 	 		= $_REQUEST['dmx_num'];
				$dmshop->_R['Item.Idx']  		= $_REQUEST['dmx_item_index'];
				$dmshop->_R['Cmd'] 				= 'ModifyItem';
				$dmshop->_R['Item.Tariff'] 		= $_REQUEST['dmx_tariff'];
				$store['index'] 				= $_REQUEST['dmx_item_index'];
				$dmshop->_R['_Store_trolley'] 	= serialize($store);
				$dmshop->request();
				$dmx_debug->msg($dmshop->debug->flush());
	
				if ($dmshop->result->status == false || !count($dmshop->result->response))
				{
					return(array('result' => 'comserr', 'details' => ''));
				}
				$dmx_response = $dmshop->result->response;
	
				// Translate results of attempt
				if (!isset($dmx_response['Cmd']))
				{
					return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
				}
				if ($dmx_response['Cmd'] == 'ModifyItemNak')
				{
					$dmx_response['Reason'] = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
					switch($dmx_response['Reason'])
					{
						case 'Item mismatch':
							$details = 'ItemMismatch';
							break;
						case 'ItemIdx out of bounds':
							$details = 'ItemGone';
							break;
						default:
							$details = $dmx_response['Reason'];
					}
					$store['comp_err_msg'] = dmx_translate_err_code('serviceselector', $details);
					dmx_store($comp_name, $store);
					return(array('result' => 'error', 'details' => $details));
				}
			}
			
			// Modify Success
			if ($dmx_response['Cmd'] == 'ModifyItemAck')
			{
				return(array('result' => 'confirm', 'details' => $_REQUEST['dmx_tariff']));
			}
			
			break;

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

		case 'show_fulltariff':
			$store['Item.Idx'] 	 = $_REQUEST['dmx_index'];
			$store['service'] 	 = $_REQUEST['dmx_service'];
			$store['plan'] 	 	 = $_REQUEST['dmx_plan'];
			dmx_store('tariffguide', $store);
			return(array('result' => 'fulltariff', 'details' => 0));
			break;

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

		default:
			$dmx_debug->msg('<b>UNKNOWN SERVICESELECTOR ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

function dmx_handle_action_trolley($comp_name, $action)
{
	// Handle actions issued by trolley components
	global $dmshop, $dmx_debug, $dmx_response, $dmx_session, $dmx_err_msg;
	
	$dmshop->_R = array();
	$dmshop->_R['TrolleyID'] = $dmx_session;	

	switch($action)
	{
		// -----------------------------------------------------------------------------------------
		
		case 'configure':
			$store['index'] = $_REQUEST['dmx_index'];
			dmx_store('trolley', $store);
			return(array('result' => 'configure', 'details' => $_REQUEST['dmx_num']));
			break;
		
		// -----------------------------------------------------------------------------------------

		case 'confirm_order':
			$dmshop->_R['Cmd'] = 'ConfirmOrder';
			$dmshop->_R['HeaderURL'] = $_REQUEST['dmx_header_url'];

			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;

			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'ConfirmOrderAck')
			{
				// Go to dmAccount if money to pay, or to clubhouse login
 				$goto = $_REQUEST['dmx_total_plus_outst'] > 0 ? $dmx_response['PaymentURL'] : 'http://my.dmclub.net/login.cfm?loginid=' . $_REQUEST['dmx_cust_id'];
				if (isset($_REQUEST['dmx_ganal_accno']) && trim($_REQUEST['dmx_ganal_accno']) && $_REQUEST['dmx_ganal_accno'] != 'OFF' && !dmx_check_for_tester_ip())
				{
					// via the clientside_redirect script (for Google Analytics compatability)
					$GLOBALS['dmx_rc'][] = 'confirm=' . '/dmx/core/ganal/clientside_redirect.php?url=' . urlencode($goto) . '&ganal_accno=' . $_REQUEST['dmx_ganal_accno'] . '&ganal_trans_rep=' . $_REQUEST['dmx_ganal_trans_rep'];
				}
				else
				{
					// or directly, if not using Google Analytics
					$GLOBALS['dmx_rc'][] = 'confirm=' . $goto . '&ganal_accno=OFF';
				}
				
				// To support trolly AJAX polling, nullify the sucessfully confirmed order in the local session - MAYBE LOOK AGAIN AT THIS!!!
				$_SESSION['dmx_init_response']['QntItems'] = 0;
				$_SESSION['dmx_init_response']['TotalInc'] = '0.00';
				
				return(array('result' => 'confirm', 'details' => $_REQUEST['dmx_total_plus_outst']));
			}
			else if ($dmx_response['Cmd'] == 'ConfirmOrderNak')
			{
				$dmx_response['Reason'] = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
				switch($dmx_response['Reason'])
				{
					case 'Not checkout ready':
						$details = 'NotCheckoutReady';
						break;
					case 'Items no longer available':
						$details = 'ItemsGone';
						break;
					default:
						$details = $dmx_response['Reason'];
				}
				$store['comp_err_msg'] = dmx_translate_err_code('trolley', $details);
				dmx_store($comp_name, $store);
				return(array('result' => 'confirmerror', 'details' => $details));
			}
			break;

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

		case 'delete':
			$dmshop->_R['Cmd'] 		= 'RemoveItemFromTrolley';
			$dmshop->_R['Item.Idx'] = $_REQUEST['dmx_index'];
			$dmshop->_R['Number'] 	= $_REQUEST['dmx_num'];
			$store['index'] = 0;
			$dmshop->_R['_Store_trolley'] = serialize($store);
			$dmx_debug->msg('<b>ATTEMPTING TO DELETE ITEM ' . $dmshop->_R['Item.Idx'] . ' FROM TROLLEY:</b> ' . $dmshop->_R['Number']);

			$dmshop->request();
			$dmx_debug->msg($dmshop->debug->flush());

			if ($dmshop->result->status == false || !count($dmshop->result->response))
			{
				return(array('result' => 'comserr', 'details' => ''));
			}
			$dmx_response = $dmshop->result->response;
			
			// Translate results of attempt
			if (!isset($dmx_response['Cmd']))
			{
				return(array('result' => 'comserr', 'details' => $dmx_response['Reason']));
			}
			if ($dmx_response['Cmd'] == 'RemoveItemFromTrolleyAck')
			{
				return(array('result' => 'delete', 'details' => $_REQUEST['dmx_num']));
			}
			else if ($dmx_response['Cmd'] == 'RemoveItemFromTrolleyNak')
			{
				$dmx_response['Reason'] = urldecode($dmx_response['Reason']); // Hack to tackle double-URL encoding problem
				switch($dmx_response['Reason'])
				{
					case 'Item mismatch':
						$details = 'NotInTrolley';
						break;
					case 'ItemIdx out of bounds':
						$details = 'BadPosition';
						break;
					default:
						$details = $dmx_response['Reason'];
				}
				$store['comp_err_msg'] = dmx_translate_err_code('trolley', $details);
				dmx_store($comp_name, $store);
				return(array('result' => 'deleteerror', 'details' => $details));
			}
			break;

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

		case 'reauthenticate':
			return(array('result' => 'reauthenticate', 'details' => ''));
			break;
		
		// -----------------------------------------------------------------------------------------

		case 'display_loginregister':
			return(array('result' => 'loginregister', 'details' => ''));
			break;
		
		// -----------------------------------------------------------------------------------------

		case 'show_typical_invoice':
			$store['index'] 	 = $_REQUEST['dmx_index'];
			$store['number'] 	 = $_REQUEST['dmx_num_f'];
			if (isset($_REQUEST['dmx_tariff']))  $store['tariff'] 	= $_REQUEST['dmx_tariff'];
			$store['popup'] 	 = $_REQUEST['dmx_popup'] == '_self' ? 0 : 1;
			$store['button_url'] = $_SERVER['PHP_SELF'] . '?' . preg_replace('/dmx_.+?=[^&]+&?/', '', $_SERVER['QUERY_STRING']); // URL minus params in dmx_ namespace
			dmx_store('trolley', $store);
			return(array('result' => 'typinv', 'details' => isset($_REQUEST['dmx_num']) ? $_REQUEST['dmx_num'] : 0));
			break;

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

		case 'trolley_clicked':
			return(array('result' => 'trolleyclicked', 'details' => ''));
			break;
		
		// -----------------------------------------------------------------------------------------

		default:
			$dmx_debug->msg('<b>UNKNOWN TROLLEY ACTION:</b> ' . $action);
			return(array('result' => 'unknown_action', 'details' => $action));
			break;
	}
}

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

?>