<?php

// autoshop.php
// -------------------------------------------------------------------------------------------------
// Loaded when ash_* parameters (autoshop parameters) are detected
//
// Revision   > $Rev: 125 $
// Date		  > $Date: 2009-10-15 10:32:22 +0100 (Thu, 15 Oct 2009) $
// Author     > RAK for DML
// Copyright  > (C) Digital Mail Limited (2005-2009)
// -------------------------------------------------------------------------------------------------

function dmx_autoshop($commands)
{
	global $dmx_session, $dmx_options, $dmx_debug;
	
	$dmx_autoshop_message_buffer = '';
	
	// Check we have a Trolley
	if (!$dmx_session)
	{
		ob_start();
		dmx_initialise_trolley();
		ob_end_clean();
	}

	// Resequence autoshop commands so order is: choose, register, confirm
	// (not all commands may be present)
	uksort($commands, 'dmx_autoshop_command_sequencer');
	
	// Execute autoshop commands
	$num_numbers_added 	= 0; // Use to count numbers successfuly added to trolley - DOES THIS NEED TO BE IN THE SESSION?
	$registered 		= NULL;
	$transfer_url 		= NULL;
	foreach($commands as $command => $val)
	{
		$dmx_debug->heading("dmx_autoshop($command, $val)");
		$GLOBALS['time1'] = dmx_add_benchmark("Start of dmx_autoshop($command)");
		switch($command)
		{
			case 'choose':
				$num_numbers_added += dmx_auto_choose($val);
				break;
				
			case 'register':
				$registered = dmx_auto_register($val);
				break;
				
			case 'confirm':
				$transfer_url = dmx_auto_confirm($val);
				break;
				
			default:
				$dmx_debug->msg('Unrecognised command');
				break;
		}
	}
	
	// Decide where to go next
	$destination = $transfer_url ? $transfer_url : $dmx_options['auto_trolley_url'];
	
	$_SESSION['AUTOSHOP']['messages'] 	= dmx_automsg_get();;
	$_SESSION['AUTOSHOP']['debug'] 		= $dmx_debug->display(1);
	if ($destination)
	{
		session_write_close();
		header('LOCATION: ' . $destination . '?dmb1_SessRef=' . $dmx_session); // What about further autoshop commands, like register and confirm- don't want to go to here in this case
		exit;
	}

}

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

function dmx_auto_choose($input)
{
	global $dmshop, $dmx_session, $dmx_debug;
	
	
	$success = 0;
	
	$in = explode('+', $input);
	foreach($in as $ch)
	{
		@list($range, $service, $plan) = explode('-', $ch);
		$areacode = NULL;
		if (substr(strtolower($range), 0, 5) == 'ukgeo')
		{
			$areacode  	= substr($range, 6, -1);
			$range 		= 'ukgeo';
		}
		$dmx_debug->msg("<b>Autoshop for: $range $areacode $service $plan</b>");
		
		// Work out the tariff
		$tariff = dmx_modify_tariff('*', NULL, $range, $service, $plan, TRUE);
	
		// Randomly choose a number on the tariff
		$dmshop->_R['Cmd'] 			= 'ChooseNumber';
		$dmshop->_R['TrolleyID'] 	= $dmx_session;
		$dmshop->_R['TariffSpec'] 	= $tariff;
		$dmshop->_R['GVFrom'] 		= 0;
		$dmshop->_R['GVTo'] 		= 0;
		if ($areacode) $dmshop->_R['Filter'] = '44' . substr($areacode, 1) . '*';
		$dmshop->request();
		$dmx_debug->msg($dmshop->debug->flush());
		
		if ($dmshop->result->status == false || !count($dmshop->result->response))
		{
			// No reply
			dmx_automsg_err("Adding a $range $areacode $service $plan number failed - no reply from shopping server");
			continue;
		}
		$response = $dmshop->result->response;
		dmx_add_benchmark('Response from ' . $dmshop->url, $GLOBALS['time1']);
		if ($response['Cmd'] == 'ChooseNumberNak')
		{ 
			$response['Reason'] = urldecode($response['Reason']); // Hack to tackle double-URL encoding problem
			dmx_automsg_err("Adding a $range $areacode $service $plan number failed - {$response['Reason']}");
			continue;
		}
		if ($response['QntPages'] == 0)
		{
			// No numbers returned
			dmx_automsg_err("Adding a $range $areacode $service $plan number failed - no matching numbers available");
			continue;
		}

		// Get the first number from the response, and add it to the trolley
		$numbers      = explode(',', $response['Num']);
		$first_number = explode(':', $numbers[0]);
		$number_raw   = $first_number[0];
		$number_fmt   = $first_number[1];

		$dmshop->_R['Cmd'] 				= 'AddItemToTrolley';
		$dmshop->_R['TrolleyID'] 		= $dmx_session;
		$dmshop->_R['Item.Number'] 		= $number_raw;
		$dmshop->_R['Item.TariffSpec'] 	= $response['TariffSpec'];
		$dmshop->_R['_Response']		= 'Extended';
		$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))
		{
			dmx_automsg_err("Adding a $range $areacode $service $plan number failed - no reply from shopping server");
			continue;
		}
		$response = $dmshop->result->response;
		
		// Translate results of attempt
		if (!isset($response['Cmd']))
		{
			dmx_automsg_err("Adding a $range $areacode $service $plan number failed - badly formed response from shopping server");
			continue;
		}
		if ($response['Cmd'] == 'AddItemToTrolleyAck')
		{
			// Success
			dmx_automsg_msg("$number_fmt has been added to your order");
			$success++;
			continue;
		}
		else if ($response['Cmd'] == 'AddItemToTrolleyNak')
		{
			$response['Reason'] = urldecode($response['Reason']); // Hack to tackle double-URL encoding problem
			switch($response['Reason'])
			{
				case 'Item not free':
					dmx_automsg_err("Adding a $range $areacode $service $plan number failed - number already taken by someone else");
					break;
				case 'Trolley full':
					dmx_automsg_err("Adding a $range $areacode $service $plan number failed - your shopping trolley is full");
					break;
				default:
					dmx_automsg_err("Adding a $range $areacode $service $plan number failed - {$response['Reason']}");
					$details = $response['Reason'];
			}
			continue;
		}

	} // End foreach
	return $success;
}

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

function dmx_auto_register($input)
{
	global $dmshop, $dmx_session, $dmx_debug;
	
	// To do...
}

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

function dmx_auto_confirm($input)
{
	global $dmshop, $dmx_session, $dmx_options, $dmx_debug;

	if ($input == '0') return FALSE;
	
	$dmshop->_R['Cmd'] 			= 'ConfirmOrder';
	$dmshop->_R['TrolleyID'] 	= $dmx_session;
	$dmshop->request();
	$dmx_debug->msg($dmshop->debug->flush());

	if ($dmshop->result->status == false || !count($dmshop->result->response))
	{
		// No reply
		dmx_automsg_err("Failed to confirm order - no reply from shopping server");
		return FALSE;
	}
	$response = $dmshop->result->response;

	// Translate results of attempt
	if (!isset($response['Cmd']))
	{
		dmx_automsg_err("Failed to confirm order - badly formed response from shopping server");
		return FALSE;
	}
	
	if ($response['Cmd'] == 'ConfirmOrderAck')
	{
		// Go to dmAccount if money to pay, or to clubhouse login
		// $goto = $_REQUEST['dmx_total_plus_outst'] > 0 ? $response['PaymentURL'] : 'http://my.dmclub.net/login.cfm?loginid=' . $_REQUEST['dmx_cust_id'];
		$goto = $response['PaymentURL'];
		
		if ($dmx_options['ganal']['accno'] != 'OFF' && !dmx_check_for_tester_ip())
		{
			// via the clientside_redirect script (for Google Analytics compatability)
			$url = '/dmx/core/ganal/clientside_redirect.php?url=' . urlencode($goto) . '&ganal_accno=' . $dmx_options['ganal']['accno'] . '&ganal_trans_rep=' . 1414141414141414141414141414;
		}
		else
		{
			// or directly, if not using Google Analytics
			$url = $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 $url;
	}
	else if ($response['Cmd'] == 'ConfirmOrderNak')
	{
		$rresponse['Reason'] = urldecode($response['Reason']); // Hack to tackle double-URL encoding problem
		switch($response['Reason'])
		{
			case 'Not checkout ready':
				dmx_automsg_err("Failed to confirm order - not all numbers in the trolley are checkout ready");
				break;
			case 'Items no longer available':
				dmx_automsg_err("Failed to confirm order - some numbers in the trolley are no longer available");
				break;
			default:
				dmx_automsg_err("Failed to confirm order - {$response['Reason']}");
				break;
		}
		return FALSE;
	}
}

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// AUTOSHOP MESSAGE BUFFER FUNCTIONS

function dmx_automsg_msg($msg)
{
	global $dmx_autoshop_message_buffer;
	$dmx_autoshop_message_buffer .= $msg . '<br />';
}

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

function dmx_automsg_err($msg)
{
	global $dmx_autoshop_message_buffer;
	$dmx_autoshop_message_buffer .= '<span class="error">' . $msg . '</span><br />';
}

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

function dmx_automsg_get()
{
	global $dmx_autoshop_message_buffer;
	return $dmx_autoshop_message_buffer;
}

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// AUTOSHOP COMMAND SEQUENCER

function dmx_autoshop_command_sequencer($a, $b)
{
	$order = array('choose', 'register', 'confirm');
	return (array_search($a, $order) > array_search($b, $order) ? 1 : -1);
}

?>