<?php
	# class.ammslist.php
	# 
	# pulled so we can run list code outside the webservice
	
	#$path = "e:/program files/apache software foundation/apache2.2/htdocs/us2_inm/inmproject";
	$path = SF_ROOT_DIR;
	require_once ("$path/apps/webservices/includes/inc.ammslist_config.php");
	require_once ("$path/apps/webservices/includes/class.ammslist_var.php");
	
	
		
	$Path = $path . "/classes";
	define('_VALID_RBS', 1 );
	#require_once($Path . '/config.inc.php');
	#require_once($rbsConfig_absolute_path ."/includes/class.database.php");
	#require_once($rbsConfig_absolute_path ."/includes/class.rbs2.php");
	#require_once("$Path/class.nameserver_objects.php");
		
	$rbsConfig_absolute_path = "$path/classes/rbs";
	#require_once ("$path/classes/config.inc.php");
	require_once ("$path/classes/class.nameserver_objects.php");
	require_once ("$path/classes/class.cyber_hackney.php");
	
	class AmmsList {
	
		var $path;
		
		public function __construct()
		{
			
			#$sSQLServer = "betty";
			#$sSQLUser = "totouser";
			#$sSQLPass = "leash4all";
			#$sSQLDatabase = "nameserver";
		
			global $sSQLServer;
			global $sSQLUser;
			global $sSQLPass;
			global $sSQLDatabase;
			#$this->sql_connect['server'] = $sSQLServer;
			#$this->sql_connect['pass'] = $sSQLPass;
			#$this->sql_connect['db'] = $sSQLDatabase;
			
			
			$this->context = sfContext::getInstance();
			$this->request = $this->context->getRequest();
			$this->database = new database($sSQLServer, $sSQLUser, $sSQLPass, $sSQLDatabase);
			
			$this->amms_global = (object) NULL;
		}
		
//		public function GetListStatus($Input)
//		{
//			$client_id		= intval($Input->ClientId);
//			$customer_id	= intval($Input->CustomerId);
//			$user_id		= intval($Input->UserId);
//			$list_id		= intval($Input->ListId);
//			
//			return $this->processGetListStatus($client_id, $customer_id, $user_id, $list_id);
//		}
//		
//		public function GetOrderProductList($in_client_id=0, $in_customer_id=0, $in_user_id = 0, $in_list_id=0)
//		{
//			$client_id		= intval($in_client_id);
//			$customer_id	= intval($in_customer_id);
//			$user_id		= intval($in_user_id);
//			$list_id		= intval($in_list_id);
//			
//			return $this->processGetOrderProductList($client_id, $customer_id, $user_id, $list_id);
//		}
//		
//		public function GetList($Input)
//		{
//			$client_id		= intval($Input->ClientId);
//			$customer_id	= intval($Input->CustomerId);
//			$user_id		= intval($Input->UserId);
//			$list_id		= intval($Input->ListId);
//			
//			return $this->processGetList($client_id, $customer_id, $user_id, $list_id);
//		}

		/**
		* Public Webservices Method: UploadList
		*********************************************************************************/
		public function UploadList ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$list_in		= $Input->ListIn;
		
				$Response = new UploadListResponse();


				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the order_id > 0.	
				```````````````````````````````````````````````````````*/
				if (count($list_in) == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1101;
					$Response->Desc			= ERROR_1101_DESC;
					return $Response;
				}
				
				
				return $this->processUploadList($client_id, $customer_id, $user_id, $list_in);
		}


		/**
		* Public Webservices Method: GetListStatus
		*********************************************************************************/
		public function GetListStatus ($Input)
		{
				$this->LogOut("GetListStatus:: Input", $Input);
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$list_id		= intval($Input->ListId);
				
				
		
				$Response = new GetListStatusResponse();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the list_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($list_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1102;
					$Response->Desc			= ERROR_1102_DESC;
					return $Response;
				}
				
				
				$this->LogOut("GetListStatus:: About to call processGetListStatus($client_id, $customer_id, $user_id, $list_id)");
				
				return $this->processGetListStatus($client_id, $customer_id, $user_id, $list_id);
		}


		/**
		* Public Webservices Method: GetList
		*********************************************************************************/
		public function GetList ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$list_id		= intval($Input->ListId);
		
				$Response = new GetList();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the list_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($list_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1102;
					$Response->Desc			= ERROR_1102_DESC;
					return $Response;
				}
				
				
				return $this->processGetList($client_id, $customer_id, $user_id, $list_id);
		}


		/**
		* Public Webservices Method: GetBasicListByArray : Get basic recipient info for validation purposes
		* 2/15/2011 Lom Nguyen
		*********************************************************************************/
		public function GetBasicListByArray ($arrayListDataId=array(), $recordLimit=0, $arrayExtraSelectField=array())
		{
				if(! $arrayListDataId) return array();
				if(! is_array($arrayListDataId)) $arrayListDataId = array($arrayListDataId);

				/*` Get the accuzip status for the list data
				```````````````````````````````````````````````````````*/
				$C = new Criteria();
				$C->addSelectColumn(AmmsListDataPeer::AMMS_LIST_DATA_ID);
				$C->addSelectColumn(AmmsListDataPeer::ACCUZIP_COMPLETE_YN);
				$C->addAnd(AmmsListDataPeer::AMMS_LIST_DATA_ID, $arrayListDataId, Criteria::IN);
				$Rs = AmmsListDataPeer::doSelectRs($C);
		
				while($Rs->next())
				{
					$AmmsListDataId		= $Rs->get(1);
					$AccuzipCompletedYn	= $Rs->get(2);
					
					if($AccuzipCompletedYn=='Y') $arrayNewListDataId[] = $AmmsListDataId;
				}
		
		
				/*` Get list data rows
				```````````````````````````````````````````````````````*/
				$C = new Criteria();
				$C->addSelectColumn(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID);
				$C->addSelectColumn(AmmsListDataDetailPeer::AMMS_LIST_DATA_DETAIL_ID);
				$C->addSelectColumn(AmmsListDataDetailPeer::NAME_MASTER_ID);
				$C->addSelectColumn(AmmsListDataDetailPeer::VALID_YN);
				$C->addSelectColumn(AmmsListDataDetailPeer::FIRST_NAME);
				$C->addSelectColumn(AmmsListDataDetailPeer::LAST_NAME);
				
				if($arrayExtraSelectField) $C->addSelectColumn(AmmsListDataDetailPeer::EXTRA);
								
				$C->addAnd(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID, $arrayNewListDataId, Criteria::IN);
				$C->addAnd(AmmsListDataDetailPeer::DUPLICATE_DETECTED_YN, 'N');
				$C->addAscendingOrderByColumn(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID);
				$C->addAscendingOrderByColumn(AmmsListDataDetailPeer::ROW_ID);

				if($recordLimit) $C->setLimit($recordLimit);
				$Rs = AmmsListDataDetailPeer::doSelectRs($C);
				
				while($Rs->next())
				{
						$extra			= array();
						$AmmsListDataId	= $Rs->get(1);

						/*` Initialize new address record
						``````````````````````````````````````````````````````````*/
						$address = new AmmsAddressOut();
						$address->AmmsListDataDetailId 	= $Rs->get(2);
						$address->iNameMasterIndex 		= $Rs->get(3);
						$address->ValidYn				= $Rs->get(4);
						$address->First					= $Rs->get(5);
						$address->Last					= $Rs->get(6);
						
						if($arrayExtraSelectField)
						{
							$extra = unserialize($Rs->get(7));
							
							foreach($arrayExtraSelectField as $field)
							{
								switch($field) {
									case 'EXTERNAL_ID': $address->ExternalId 	= $extra['dms_external_id'];  break;
									case 'VIN': 		$address->Vin 			= $extra['VIN'];  break;
									default:
										if(!$address->Options) $address->Options = array();
										$address->Options["$field"] = $extra["$field"];
									break;
								}
							}
						}
						
						$arrayResult["$AmmsListDataId"][] = $address;
				}

				return $arrayResult;	
		}
		
		
		
		/**
		* Public Webservices Method: GetListByArray
		* 7/14/2009 Lom Nguyen
		*********************************************************************************/
		public function GetListByArray ($arrayListDataId=array(), $recordLimit=0, $selectNameInfo=false, $selectExtraData=true, $ignoreDupes=false, $validOnly=true)
		{
				if(! $arrayListDataId) return array();
				if(! is_array($arrayListDataId)) $arrayListDataId = array($arrayListDataId);


				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
					die("User is restricted from accessing this system. Please contact support.");	

				// $Response 	=  $this->GetListByArrayRapid($arrayListDataId, $recordLimit, $selectNameInfo, $selectExtraData, $ignoreDupes, $validOnly);

				// return $Response;


				// /*` Get the upload ids for the list data
				// ```````````````````````````````````````````````````````*/
				// $arrayAmmsListDataUploadId 			= array();
				// $arrayAmmsListDataIgnoreNCOA		= array();
				// $arrayUploadDataAmmsListDetailMap	= array();

				// $Conn 		= Propel::GetConnection();
				// $Query 		= "SELECT amms_list_data_id, upload_id, upload_master_id "
				// 			. "FROM amms_list_data WHERE amms_list_data_id IN (" . join(",", $arrayListDataId) . ") ";
				// $Rs 		= $Conn->executeQuery($Query);
				// while($Rs->next()) {

				// 	$AmmsListDataId	= $Rs->get('amms_list_data_id');
				// 	$UploadId		= $Rs->get('upload_id');
				// 	$UploadMasterId	= $Rs->get('upload_master_id');

				// 	$arrayAmmsListDataUploadId["$AmmsListDataId"] = $UploadId;
				// 	$arrayAmmsListDataCyberUploadId["$AmmsListDataId"] = $UploadMasterId;

				// }

				$Conn 				= Propel::GetConnection();


				$AmmsListDataSearch	= array('cyber' => array(), 'rapid' => array());
				$Query 				= "SELECT * FROM amms_list_data "
									. "WHERE amms_list_data_id IN (" . join(",", $arrayListDataId) . ") ";
								$this->LogOut("Query = " . $Query);
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next()) {
					$SearchRow 		= $Rs->getRow();
					if ( $SearchRow['upload_master_id'] > 0 ) {
						$AmmsListDataSearch['cyber'][] = $SearchRow['amms_list_data_id'];
					} else {
						$AmmsListDataSearch['rapid'][] = $SearchRow['amms_list_data_id'];
					}
				}
				// echo "AmmsListDataSearch = " . print_r($AmmsListDataSearch, true) . "\n";

				$ResponseCyber 	= false;
				$ResponseRapid 	= false;
				if ( count($AmmsListDataSearch['cyber']) > 0 ) {
					$ResponseCyber 	=  $this->GetListByArrayCyber($AmmsListDataSearch['cyber'], $recordLimit, $selectNameInfo, $selectExtraData, $ignoreDupes, $validOnly);
				} 
				if ( count($AmmsListDataSearch['rapid']) > 0 ) {
					$ResponseRapid 	=  $this->GetListByArrayRapid($AmmsListDataSearch['rapid'], $recordLimit, $selectNameInfo, $selectExtraData, $ignoreDupes, $validOnly);
				}
				$Response 		= array();
				if ( is_array($ResponseCyber) ) {
					foreach($ResponseCyber as $id => $rec) {
						$Response[$id] = $rec;
					}
				}
				if ( is_array($ResponseRapid) ) {
					foreach($ResponseRapid as $id => $rec) {
						$Response[$id] = $rec;
					}
				}
				return $Response;
		}


		public function GetListByArrayCyber($arrayListDataId=array(), $recordLimit=0, $selectNameInfo=false, $selectExtraData=true, $ignoreDupes=false, $validOnly=true)
		{
			
				if(! $arrayListDataId) return array();
				if(! is_array($arrayListDataId)) $arrayListDataId = array($arrayListDataId);

				
				/* Check to see if all the lists are ready
				```````````````````````````````````````````````````````*/
				$status_code = true;	


				$Conn 				= Propel::GetConnection();
				$Cyber 				= new CybeRHackney();
			
				// Can we move forward? - AmmsList must have accuzip_complete_yn = 'Y' for all of the list(s)
				$AmmsListDataList 	= false;
				$status_code 	= true;
				$Query 			= "SELECT * FROM amms_list_data "
								. "WHERE amms_list_data_id IN (" . join(",", $arrayListDataId) . ") ";
				$Rs 			= $Conn->executeQuery($Query);
				while($Rs->next()) {
					$Row 		= $Rs->getRow();
					$AmmsListDataList[$Row['amms_list_data_id']] = $Row;

					if ( $Row['accuzip_complete_yn'] == 'N' )
						$status_code = false;
				}				
		
				if($status_code==false) return false;
			
				$arrayResult 	= array();

				foreach($AmmsListDataList as $AmmsListDataId => $AmmsListDataRec) {

					$AmmsListDataDetail = array();


					$ValidQuery 		= "";
					$DupesQuery 		= "";
					if($validOnly)
						$ValidQuery 	= "AND VALID_YN = 'Y' ";

					if($ignoreDupes==false)
						$DupesQuery 	= "AND DUPLICATE_DETECTED_YN = 'N' ";


					$Query 		= "SELECT * FROM amms_list_data_detail "
								. "WHERE amms_list_data_id = {$AmmsListDataId} "
								. $DupesQuery
								. $ValidQuery
								. "ORDER BY row_id ";
							// echo "Query = {$Query}\n";
					$Rs 		= $Conn->executeQuery($Query);
					while($Rs->next()) {
						$Row 	= $Rs->getRow();
						$AmmsListDataDetail[$Row['amms_list_data_detail_id']] = $Row;
					}


					$UploadMasterId 		= $AmmsListDataRec['upload_master_id'];
					$UploadData 			= $Cyber->GetUploadDataRecords($this->ClientId, $this->CustomerId, 0, $UploadMasterId);
					// echo "Back from Cyber.\n";

					// Organize by the amms_list_data_detail_id in the record
					$UploadDataByDetailId 	= array();
					foreach($UploadData as $id => $UploadRec) {
						$UploadDataByDetailId[$UploadRec['AMMS_LIST_DATA_DETAIL_ID']] = $UploadRec;
					}


					foreach($AmmsListDataDetail as $DataDetail) {

						$address 			= new AmmsAddressOut();				
					

						$Extra 				= '';
						$NameInfo			= '';
						if($selectNameInfo) 	
							$NameInfo 		= $DataDetail['NameInfo'];
						if($selectExtraData) 	
							$Extra 			= $DataDetail['extra'];

						$PostalKeyParts 	= explode("|", $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_key']);
						$Zip5 				= substr($PostalKeyParts[0], 1, 5);
						$Zip4 				= substr($PostalKeyParts[0], 6, 4);
						$ZipPlus4 			= "{$Zip5}-{$Zip4}";
						$DPC 				= substr($PostalKeyParts[0], 10, 3);
						$DPBC 				= substr($DPC, -1);

						$address->RowId		= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['record_id'];
						$address->Prefix	= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['PREFIX'];
						$address->First		= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['FIRST'];
						$address->Middle	= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['MIDDLE'];
						$address->Last		= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['LAST'];
						$address->Suffix	= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['SUFFIX'];
						$address->MoveYn 	= 'N';
						$address->AmmsListDataDetailId 	= $DataDetail['amms_list_data_detail_id'];

						// The rapidmail version has an implied 'V' flag because an iNameMasterIndex record only gets created if the record is flagged as 'v' (valid)
						// Because this is a cyber upload we get both verified and unverified values.
						if ( $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_status'] == 'V') {
							$address->ValidYn 		= 'Y';
							$address->Address		= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_address'];
							$address->Suite			= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_address2'];
							$address->City			= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_city'];
							$address->State			= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_state'];
							$address->Zip			= $ZipPlus4;
							$address->PostalBarcode = $PostalKeyParts[0];
							$address->PostalCRRT	= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_crrt'];
							$address->PostalSCF		= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_scf'];
							$address->PostalDPBC	= $DPBC;
							$address->PostalDPC		= $DPC;
							$address->Zip5			= $Zip5;
							$address->Zip4			= $Zip4;
							$address->CountyNumber	= "";
							$address->CountyName	= $UploadDataByDetailId[$DataDetail['amms_list_data_detail_id']]['postal_county'];
							$address->Lat			= "";
							$address->Lon			= "";
							$address->iNameMasterIndex	= $DataDetail['name_master_id'];
							$address->DuplicateDetectedYn	= $DataDetail['duplicate_detected_yn'];
							$address->Extra 		= $Extra;
							$address->NameInfo 		= $NameInfo;
						// } else {

						// 	$NameInfo 				= unserialize($DataDetail['name_info']);
						// 	echo "NameInfo = " . print_r($NameInfo, true) . "\n";


						// 	$address->ValidYn		= "N";
						// 	$NameInfo 	= unserialize($DetaDetail['name_info']);
						// 	if ( $ignore_ncoa_yn == "Y" )	$address->ValidYn	= "Y";
						// 	$address->Address		= $NameInfo->Address;
						// 	$address->Suite			= $NameInfo->Suite;
						// 	$address->City			= $NameInfo->City;
						// 	$address->State			= $NameInfo->State;
						// 	$address->Zip			= $NameInfo->Zip;
						}
						
						$arrayResult[$AmmsListDataId][] = $address;
					}
				}
				return $arrayResult;
				
		}






		public function GetListByArrayRapid ($arrayListDataId=array(), $recordLimit=0, $selectNameInfo=false, $selectExtraData=true, $ignoreDupes=false, $validOnly=true)
		{
			
				if(! $arrayListDataId) return array();
				if(! is_array($arrayListDataId)) $arrayListDataId = array($arrayListDataId);


				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
					die("User is restricted from accessing this system. Please contact support.");					
				
				echo "GetListByArrayRapid()\n";
				echo "arrayListDataId = " . print_r($arrayListDataId, true) . "\n";
				
				$CUpload 		= new Upload($this->database);
				$CUploadData 	= new UploadData($this->database);
				$CNameMaster	= new NameMaster($this->database);	
							
				/* Check to see if all the lists are ready
				```````````````````````````````````````````````````````*/
				$status_code = true;	


				/*` Get the upload ids for the list data
				```````````````````````````````````````````````````````*/
				$arrayAmmsListDataUploadId 			= array();
				$arrayAmmsListDataIgnoreNCOA		= array();
				$arrayUploadDataAmmsListDetailMap	= array();
				
				$C = new Criteria();
				$C->addSelectColumn(AmmsListDataPeer::AMMS_LIST_DATA_ID);
				$C->addSelectColumn(AmmsListDataPeer::UPLOAD_ID);
				$C->addSelectColumn(AmmsListDataPeer::IGNORE_NCOA_YN);
				$C->addAnd(AmmsListDataPeer::AMMS_LIST_DATA_ID, $arrayListDataId, Criteria::IN);
				$Rs = AmmsListDataPeer::doSelectRs($C);
				
				while($Rs->next())
				{
					$AmmsListDataId	= $Rs->get(1);
					$UploadId		= $Rs->get(2);
					$arrayAmmsListDataUploadId["$AmmsListDataId"] = $UploadId;
					$arrayAmmsListDataIgnoreNCOA["$AmmsListDataId"] = $Rs->get(3);
				}
		

				/*` Get the upload status
				```````````````````````````````````````````````````````*/
				$arrayUploadStatus = $CUpload->GetProcessingStatus ($arrayAmmsListDataUploadId);

				foreach($arrayUploadStatus as $iUploadIndex => $Status)
				{
					$dtAccuzipReceived	= strtotime($Status['dtAccuzipReceived']);
					$dtAccuzipPosted	= strtotime($Status['dtAccuzipPosted']);
					$cProcessing		= $Status['cProcessing'];
					
					# If any one upload is not yet completed, we'll flag the whole request as incomplete
					if (! ($dtAccuzipReceived > $dtAccuzipPosted && $cProcessing == 'N') ) {
						$status_code = false;
					} 
				}
			#print_r($arrayAmmsListDataUploadId); die("*");	
				if($status_code==false) return false;
				
	

				/*` Get list data rows
				```````````````````````````````````````````````````````*/
				$arrayAmmsListResult 		= array();
				$arrayUploadDataResult		= array();
				# Rick's fix 11/4/2010
				$arrayUploadDataIndex		= array();
				
				$C = new Criteria();
				$C->addSelectColumn (AmmsListDataDetailPeer::AMMS_LIST_DATA_ID);
				$C->addSelectColumn (AmmsListDataDetailPeer::ROW_ID);
				$C->addSelectColumn (AmmsListDataDetailPeer::UPLOAD_DATA_ROW_ID);
				$C->addSelectColumn (AmmsListDataDetailPeer::AMMS_LIST_DATA_DETAIL_ID);
				
				if($selectNameInfo) 	$C->addSelectColumn (AmmsListDataDetailPeer::NAME_INFO);
				if($selectExtraData)	$C->addSelectColumn (AmmsListDataDetailPeer::EXTRA);
				
				$C->add(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID, $arrayListDataId, Criteria::IN);
				
				if($validOnly)
					$C->add(AmmsListDataDetailPeer::VALID_YN, 'Y');
				
				$C->addAscendingOrderByColumn(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID);
				$C->addAscendingOrderByColumn(AmmsListDataDetailPeer::ROW_ID);
				
				if($ignoreDupes==false)
					$C->add(AmmsListDataDetailPeer::DUPLICATE_DETECTED_YN, 'N');
				
				if($recordLimit)
					$C->setLimit($recordLimit);
					
				$Rs = AmmsListDataDetailPeer::doSelectRs($C);
				#die("*Please try again later*");
				while($Rs->next())
				{
					$AmmsListDataId			= $Rs->get(1);
					$RowId					= $Rs->get(2);
					$UploadDataRowId		= $Rs->get(3);
					$AmmsListDataDetailId	= $Rs->get(4);
					$NameInfo				= '';
					$Extra					= '';
					$i = 5;
					
					if($selectNameInfo)		{ $NameInfo = $Rs->get($i); $i++; }
					if($selectExtraData) 	{ $Extra = $Rs->get($i); }
					
					
					# Store into temp array
					$arrayUploadDataAmmsListDetailMap[$UploadDataRowId] = $AmmsListDataDetailId;
					
					if($UploadDataRowId > 0){
						$arrayUploadDataResult["$UploadDataRowId"]['extra']		= $Extra;
						$arrayUploadDataResult["$UploadDataRowId"]['ListId'] 	= $AmmsListDataId;
						$arrayUploadDataResult["$UploadDataRowId"]['name_info'] = $NameInfo;
						# Rick's fix 11/4/2010
						$arrayUploadDataIndex[] 								= $UploadDataRowId;	
											# betty.nameserver.upload_data.iuploaddataindex
						
					}
					else {
						$arrayAmmsListResult[$AmmsListDataId][$RowId]['extra'] 		= $Extra;
						$arrayAmmsListResult[$AmmsListDataId][$RowId]['name_info'] 	= $NameInfo;
					}
				}
				
				

			
				/*` Get the data from the upload table
				```````````````````````````````````````````````````````*/
				# Rick's fix 11/4/2010
				#$arrayUploadData 	= $CUpload->GetDataForMailing($arrayAmmsListDataUploadId);
				$arrayUploadData	= $CUpload->GetDataForMailingByDetail($arrayUploadDataIndex);
				$arrayResult		= array();
				
	

				foreach($arrayUploadData as $iUploadIndex => $arrayRowData)
				{
					$AmmsListDataId = array_search($iUploadIndex, $arrayAmmsListDataUploadId);
					

					foreach($arrayRowData as $RowId => $Data)
					{
						$iUploadDataIndex 		= $Data['iUploadDataIndex'];
						$AmmsListDataDetailId 	= $arrayUploadDataAmmsListDetailMap[$iUploadDataIndex];
											
						$ListId = $arrayUploadDataResult["$iUploadDataIndex"]['ListId'];
						if(! $ListId)
							$ListId = $AmmsListDataId;
						
						$IgnoreNCOA		= $arrayAmmsListDataIgnoreNCOA["$ListId"];
						
				
						if(! (isset($arrayUploadDataResult["$iUploadDataIndex"]) || isset($arrayAmmsListResult[$ListId][$RowId]))) continue;
						

						$Extra 		= '';
						$NameInfo	= '';
						
						if($arrayUploadDataResult["$iUploadDataIndex"]) {
							$Extra 		= $arrayUploadDataResult["$iUploadDataIndex"]['extra'];
							$NameInfo 	= $arrayUploadDataResult["$iUploadDataIndex"]['name_info'];
							#echo 'using $arrayUploadDataResult["$iUploadDataIndex"]'." ---> $iUploadDataIndex -> $Extra\r\n";
						}
						else {
							$Extra 		= $arrayAmmsListResult[$ListId][$RowId]['extra'];
							$NameInfo 	= $arrayAmmsListResult[$ListId][$RowId]['name_info'];
							#echo 'using $arrayAmmsListResult'."\r\n";
						}

						
						#if(! $arrayAmmsListResult[$AmmsListDataId][$RowId]) continue;
	
						/*` Initialize new address record
						``````````````````````````````````````````````````````````````*/
						$address = new AmmsAddressOut();
						$address->RowId		= $RowId;
						$address->Prefix	= $Data['sPrefix'];
						$address->First		= $Data['sFirst'];
						$address->Middle	= $Data['sMiddle'];
						$address->Last		= $Data['sLast'];
						$address->Suffix	= $Data['sSuffix'];
						$address->MoveYn 	= 'N';
						$address->ValidYn	= "N"; # default
						$address->Address	= $Data['sAddress'];
						$address->Suite		= $Data['sSuite'];
						$address->City		= $Data['sCity'];
						$address->State		= $Data['sState'];
						$address->Zip		= $Data['sZip'];
						$address->Zip5		= substr($Data['sZip'], 0, 5);
						$address->Zip4		= substr($Data['sZip4'], 0, 4);
						$address->PostalDPBC= $Data['ud_sDPBC'];
						$address->Extra		= $Extra;
						$address->AmmsListDataDetailId 	= $AmmsListDataDetailId;
						$address->iNameMasterIndex 		= 0;
						
						if($selectNameInfo) $address->NameInfo = $NameInfo;
						
						
						/*` If this name is valid
						``````````````````````````````````````````````````````````````*/
						if($Data['iNameMasterIndex'] > 0)
						{
							# Is this a move? (ignore address suffix because of normalization (Drive -> DR))
							$src_addr = explode(" ", strtoupper(trim($Data['sAddress'])));
							$new_addr = explode(" ", strtoupper(trim($Data['n_address'])));
							
							if ( count($src_addr) >= 1 ) {
								for($i = 0; $i < count($src_addr) -1; $i++) {
									if ( $src_addr[$i] != $new_addr[$i] ) $address->MoveYn = 'Y';
								}
							}
												
							$address->ValidYn		= "Y";
							$address->Address		= $Data['n_address'];
							$address->Suite			= $Data['n_suite'];
							$address->City			= $Data['n_city'];
							$address->State			= $Data['n_state'];
							$address->Zip			= $Data['n_zip'];
							$address->PostalBarcode = $Data['sZipBarcode'];
							$address->PostalCRRT	= $Data['sCRRT'];
							$address->PostalSCF		= $Data['sSCF'];
							$address->PostalDPBC	= $Data['sDPBC'];
							$address->PostalDPC		= $Data['sDPC'];
							$address->Zip5			= $Data['n_zip5'];
							$address->Zip4			= $Data['n_zip4'];
							$address->CountyNumber	= $Data['sCountyNumber'];
							$address->CountyName	= $Data['sCountyName'];
							$address->Lat			= $Data['sLat'];
							$address->Lon			= $Data['sLon'];
							$address->iNameMasterIndex	= $Data['iNameMasterIndex'];
						}
						elseif($IgnoreNCOA=='Y')
						{
							if(strlen($address->Zip5)==5 && strlen($address->Zip4)==4 && strlen($address->PostalDPBC)==3)
								$address->PostalBarcode = sprintf("/%s%s%s/", $address->Zip5, $address->Zip4, $address->PostalDPBC);
							
							$address->ValidYn		= "Y";
						}
	
	
						$arrayResult["$ListId"][] = $address;
					}
				}
				
			
			
			
			
			
				return $arrayResult;	
		}
		
		
		/**
		* Public Webservices Method: MakePullFromList
		*********************************************************************************/
		public function MakePullFromList ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$list_id		= intval($Input->ListId);
		
				$Response = new GetList();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the list_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($list_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1102;
					$Response->Desc			= ERROR_1102_DESC;
					return $Response;
				}
				
				
				return $this->processMakePullFromList($client_id, $customer_id, $user_id, $list_id);
		}

		/**
		* Public Webservices Method: GetPull
		*********************************************************************************/
		public function GetPull ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$list_id		= intval($Input->ListId);
		
				$Response = new GetPull();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the list_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($list_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1102;
					$Response->Desc			= ERROR_1102_DESC;
					return $Response;
				}
				
				
				return $this->processGetPull($client_id, $customer_id, $user_id, $list_id);
		}

		/**
		* Public Webservices Method: GetPull
		*********************************************************************************/
		public function GetPullByPull ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
				$pull_id		= intval($Input->PullId);
		
				$Response = new GetPullByPull();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				/*`` Check the pull_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($pull_id == 0 )
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1104;
					$Response->Desc			= ERROR_1104_DESC;
					return $Response;
				}
				
				
				return $this->processGetPullByPull($client_id, $customer_id, $user_id, $pull_id);
		}

		/**
		* Public Webservices Method: ImportFromPander
		*********************************************************************************/
		public function ImportFromPander ($Input)
		{
				$Username		= stripslashes($Input->Username);
				$Password		= stripslashes($Input->Password);
				$client_id		= intval($Input->ClientId);
				$customer_id	= intval($Input->CustomerId);
				$user_id		= intval($Input->UserId);
		
				$Response = new GetPullByPull();
				
				/*`` Check the user has access
				```````````````````````````````````````````````````````*/
				$WebserviceUser = new WebserviceUserPeer();
				$User = $WebserviceUser->GetUser ($Username, $Password);

				if ($User === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1001;
					$Response->Desc			= ERROR_1001_DESC;
					return $Response;
				}

				/*`` Check current user ip address for access control
				```````````````````````````````````````````````````````*/
				$UserId = $this->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
				if ( $UserId === false)
				{
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1028;
					$Response->Desc			= ERROR_1028_DESC;
					return $Response;
				}
				
				
				/*`` Check the user_id > 0.	
				```````````````````````````````````````````````````````*/
				if ($user_id == 0 )
				{
					$Response->Code			= ERROR;

					$Response->ErrorCode	= 1004;
					$Response->Desc			= ERROR_1004_DESC;
					return $Response;
				}
				
				
				
				return $this->processImportFromPander($client_id, $customer_id, $user_id, $pull_id);
		}
		
		
		/**
		* Private Method Function: processUploadlist
		*********************************************************************************/
		//private function processUploadlist ($client_id=0, $customer_id=0 )
		//-Daniel -07/14/08
		private function processUploadlist ($client_id=0, $customer_id=0,$user_id=0, $list_in )
		{
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users 	= array( 4 );
			$msg = "date:" . date("Y-m-d H:i:s") . "\r\n"
				. "client_id=$client_id\r\n"
				. "customer_id=$customer_id\r\n"
				. "list:".print_r($list_in,true)."\r\n";
			$this->LogOut($msg);
				
			if (!$this->database) {
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1032;
				$Response->Desc			= ERROR_1032_DESC;
				return $Response;
			}
			
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			# How many records do we have in the list?
			
			
			
			//$list_count = count($list_in->AmmsAddressIn->Struct);
				//-Daniel -07/14/08
				$list_count = count($list_in->AmmsAddressIn);
			
			#echo "processUploadlist count:$list_count\r\n";
			if ( $list_count > 0 ) {
				//$list_data = $list_in->AmmsAddressIn->Struct;
				//Daniel -07/14/08
				$list_data = $list_in->AmmsAddressIn;
				#echo "List=>".print_r($list_data,true)."\r\n";
				# Get a new import ID
				$conn	= Propel::GetConnection();
				
				unset($CUpload->iUploadIndex);
				$CUpload->iUploadTypeIndex 			= 1;
				$CUpload->iUserUploadFormatIndex 	= 542;
				$CUpload->iCategoryIndex 			= 1;
				$CUpload->iClientIndex 				= $client_id;
				$CUpload->iCustomerIndex 			= $customer_id;
				$CUpload->sUploadPath 				= "";
				$CUpload->sUploadDescription 		= "AmmsList Soap Service";
				$CUpload->iUserIndex 				= 192;
				$CUpload->iUploadedByUserIndex 		= 192;
				$CUpload->iGrossRecords 			= $list_count;
				$CUpload->cNcoa 					= 'Y';
				$CUpload->cMatchLastName 			= 'Y';
				$CUpload->cProcessing 				= "N";
				$CUpload->cActive 					= 'Y';
				if ( ! $CUpload->store() ) {
					#Store failed
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1030;
					$Response->Desc			= ERROR_1030_DESC;
					return $Response;
				}
				$iUploadIndex = $CUpload->iUploadIndex;
				
				$amms_list_data = new AmmsListData();
				$amms_list_data->setUploadId($iUploadIndex);
				$amms_list_data->setCreatedByUserId($user_id);
				$amms_list_data->setCreatedDate(date("Y-m-d H:i:s"));
				$amms_list_data->save($conn);
				$amms_list_data_id = $amms_list_data->getAmmsListDataId();
				
				# if we get one record it's not going to be in an array so make it an array.
				if ( !is_array($list_data) ) $list_data = array('0' => $list_data);
				
				foreach($list_data as $data)
				{
					unset($CUploadData->iUploadDataIndex);
					$CUploadData->iUploadIndex 		= $iUploadIndex;
					$CUploadData->iUploadRecordIndex= $data->RowId;	
					$CUploadData->sPrefix 			= $data->Prefix;
					$CUploadData->sFirst 			= $data->First;
					$CUploadData->sMiddle 			= $data->Middle;
					$CUploadData->sLast 			= $data->Last;
					$CUploadData->sSuffix 			= $data->Suffix;
					$CUploadData->sAddress 			= $data->Address;
					$CUploadData->sSuite 			= $data->Suite;
					$CUploadData->sCity 			= $data->City;
					$CUploadData->sState 			= $data->State;
					$CUploadData->sZip 				= $data->Zip;
					if ( ! $CUploadData->store() ) {
						# Store failed
						$Response->Code			= ERROR;
						$Response->ErrorCode	= 1031;
						$Response->Desc			= ERROR_1031_DESC;
						return $Response;
					}
					$iUploadDataIndex = $CUploadData->iUploadDataIndex;
					$amms_list_data_detail = new AmmsListDataDetail();
					$amms_list_data_detail->setAmmsListDataId($amms_list_data_id);
					$amms_list_data_detail->setRowId($data->RowId);
					$amms_list_data_detail->setNameInfo(serialize($data));
					$amms_list_data_detail->setUploadDataRowId($iUploadDataIndex);
					$amms_list_data_detail->setExtra($data->Extra);
					$amms_list_data_detail->save();
					
				}
				# Update the upload completed timestamp
				$CUpload->dtUploadCompleted = date("Y-m-d H:i:s");
				if ( ! $CUpload->store() ) {
					#Store failed
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1030;
					$Response->Desc			= ERROR_1030_DESC;
					return $Response;
				}
				
				$resp = $this->StartAccuzip($iUploadIndex);
				# Pass along the accuzip errors if there are any
				$Response->Code			= $resp->Code;
				$Response->Desc			= $resp->Desc;
				$Response->ListId		= $amms_list_data_id;
			} else {
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1003;
				$Response->Desc			= ERROR_1003_DESC;
			}
			return $Response;
		}
		
		
		/**
		* Private Method Function: processGetListStatus
		*********************************************************************************/
		private function processGetListStatus ($client_id=0, $customer_id=0, $user_id=0, $list_id=0)
		{
			$this->LogOut("Init:: client_id=$client_id, customer_id=$customer_id, user_id=$user_id, list_id= $list_id");
			$Response = new GetListStatusResponse();
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			$this->LogOut("Trying to establish CUpload");
			$CUpload = new Upload($this->database);
			$this->LogOut("Have CUpload");
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			$this->LogOut("client_id=$client_id, customer_id=$customer_id, user_id=$user_id, list_id= $list_id");
			if ( $list_id > 0 ) {
			
				$amms_list_data = AmmsListDataPeer::retrieveByPk($list_id);
				$this->LogOut("amms_list_data=", $amms_list_data);
					#$Response->Code			= ERROR;
					#$Response->ErrorCode	= 1099;
					#$Response->Desc			= "amms_list_data = " . print_r($amms_list_data, true);
					#return $Response;
				$iUploadIndex = $amms_list_data->getUploadId();
				
				$status_code = false;
				if ( $CUpload->load($iUploadIndex) ) {
					$this->LogOut("iUploadIndex=$iUploadIndex\nCUpload=", $CUpload);
					
					$lAccuzipReceived = strtotime($CUpload->dtAccuzipReceived);
					$lAccuzipPosted = strtotime($CUpload->dtAccuzipPosted);
					if ( $lAccuzipReceived > $lAccuzipPosted && $CUpload->cProcessing == 'N' ) {
						$status_code = true;
					} 
				} else {
					# Oops - can't load the record.
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1033;
					$Response->Desc			= ERROR_1033_DESC;
					return $Response;
				}
				
				if ( $status_code ) {
					# Yup list is ready
					$Response->Code			= SUCCESS;
				} else {
					# Not ready
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1103;
					$Response->Desc			= ERROR_1103_DESC;
				}
			} else {
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1102;
				$Response->Desc			= ERROR_1102_DESC;
			}
			unset($CUpload);
			return $Response;
		}
		
		
		/**
		* Private Method Function: processGetList
		*********************************************************************************/
		private function processGetList ($client_id=0, $customer_id=0, $user_id = 0, $list_id = 0)
		{
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			$CNameMaster	= new NameMaster($this->database);
			
			$address_list	= new ArrayOfAmmsAddressOut();
			
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			
			$status_code = false;
			if ( $list_id > 0 ) {
			
				$amms_list_data = AmmsListDataPeer::retrieveByPk($list_id);
				$iUploadIndex 	= $amms_list_data->getUploadId();
				$ignore_ncoa_yn	= $amms_list_data->getIgnoreNcoaYn();
					
				#$Response->Code			= ERROR;
				#$Response->ErrorCode	= 1099;
				#$Response->Desc			= "iUploadIndex = " . print_r($iUploadIndex, true);
				#return $Response;
					
				if ( $CUpload->load($iUploadIndex) ) {
					$lAccuzipReceived = strtotime($CUpload->dtAccuzipReceived);
					$lAccuzipPosted = strtotime($CUpload->dtAccuzipPosted);
					if ( $lAccuzipReceived > $lAccuzipPosted && $CUpload->cProcessing == 'N' ) {
						$status_code = true;
					} 
				} else {
					# Oops - can't load the record.
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1033;
					$Response->Desc			= ERROR_1033_DESC;
					return $Response;
				}
			} else {
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1102;
				$Response->Desc			= ERROR_1102_DESC;
				return $Response;
			}
			
			if ( !$status_code )
			{
				# Not ready
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1103;
				$Response->Desc			= ERROR_1103_DESC;
				return $Response;
			
			}
			
			$C = new Criteria();
			$C->add(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID, $list_id);
			$C->addAscendingOrderByColumn(AmmsListDataDetailPeer::ROW_ID);
			$C->add(AmmsListDataDetailPeer::DUPLICATE_DETECTED_YN, 'N');
			$amms_list_data_detail = AmmsListDataDetailPeer::doSelect($C);
			
				#$Response->Code			= ERROR;
				#$Response->ErrorCode	= 1099;
				#$Response->Desc			= "amms_list_data_detail = " . print_r($amms_list_data_detail, true);
				#return $Response;
			if ( !is_array($amms_list_data_detail) ) $amms_list_data_detail = array('0' => $amms_list_data_detail);
			foreach($amms_list_data_detail as $data_detail) {
				$row_id = $data_detail->getRowId();
				$upload_data_row_id = $data_detail->getUploadDataRowId();
				$extra = $data_detail->getExtra();
				if ( $upload_data_row_id > 0 )
				{
					# Load the datarow directly
					$CUploadData->load($upload_data_row_id);
				} else {
					# Old Style
					$CUploadData->GetByUploadRecord($iUploadIndex, $row_id);
				}
				
				
				$address = new AmmsAddressOut();
				$address->RowId		= $row_id;
				$address->UploadDataRowId	= $upload_data_row_id;
				$address->Prefix	= $CUploadData->sPrefix;
				$address->First		= $CUploadData->sFirst;
				$address->Middle	= $CUploadData->sMiddle;
				$address->Last		= $CUploadData->sLast;
				$address->Suffix	= $CUploadData->sSuffix;
				if ( $CUploadData->iNameMasterIndex > 0 ) {
					$CNameMaster->load($CUploadData->iNameMasterIndex);
					
					# Is this a move? (ignore address suffix because of normalization (Drive -> DR))
					$src_addr = explode(" ", strtoupper(trim($CUploadData->sAddress)));
					$new_addr = explode(" ", strtoupper(trim($CNameMaster->sAddress)));
					$address->MoveYn = 'N';
					if ( count($src_addr) >= 1 ) {
						for($i = 0; $i < count($src_addr) -1; $i++) {
							if ( $src_addr[$i] != $new_addr[$i] ) $address->MoveYn = 'Y';
						}
					}
					$address->ValidYn		= "Y";
					$address->UploadDataRowId = $data_detail->getUploadDataRowId();
					$address->Address		= $CNameMaster->sAddress;
					$address->Suite			= $CNameMaster->sSuite;
					$address->City			= $CNameMaster->sCity;
					$address->State			= $CNameMaster->sState;
					$address->Zip			= $CNameMaster->sZip;
					$address->PostalBarcode = $CNameMaster->sZipBarcode;
					$address->PostalCRRT	= $CNameMaster->sCRRT;
					$address->PostalSCF		= $CNameMaster->sSCF;
					$address->PostalDPBC	= $CNameMaster->sDPBC;
					$address->PostalDPC		= $CNameMaster->sDPC;
					$address->Zip5			= $CNameMaster->sZip5;
					$address->Zip4			= $CNameMaster->sZip4;
					$address->CountyNumber	= $CNameMaster->sCountyNumber;
					$address->CountyName	= $CNameMaster->sCountyName;
					$address->Lat			= $CNameMaster->sLat;
					$address->Lon			= $CNameMaster->sLon;
					$address->iNameMasterIndex	= $CNameMaster->iNameMasterIndex;
					$address->DuplicateDetectedYn	= $data_detail->getDuplicateDetectedYn();
				} else {
					$address->ValidYn	= "N";
					if ( $ignore_ncoa_yn == 'Y') $address->ValidYn	= "Y";
					$address->Address	= $CUploadData->sAddress;
					$address->Suite		= $CUploadData->sSuite;
					$address->City		= $CUploadData->sCity;
					$address->State		= $CUploadData->sState;
					$address->Zip		= $CUploadData->sZip;
					#spoof the barcode on polk provided files.
					if ( strlen($CUploadData->sZip5) == 5 && 
						 strlen($CUploadData->sZip4) == 4 &&
						 strlen($CUploadData->sDPBC) == 3 && $ignore_ncoa_yn == "Y" )
					{
						$address->PostalBarcode = sprintf("/%s%s%s/", 
									$CUploadData->sZip, 
									$CUploadData->sZip4,
									$CUploadData->sDPBC);
					}
				}
				$address->Extra		= $extra;
				
				$address_list->AmmsAddressOut[] = $address;
			}
			
			$Response->Code			= SUCCESS;
			$Response->ListOut		= $address_list;
			return $Response;
		}
		
		
	
		/**
		* Private Method Function: GetPricing
		*********************************************************************************/
		private function StartAccuzip($upload_id=0)
		{
		
			# Use the pricing SOAP service to get the pricing information.
			
			$Classmap = array ('AccuzipMakeCSV'=>'AccuzipMakeCSV','AccuzipMakeCSVResponse'=>'AccuzipMakeCSVResponse', 'SaveuProduceAsset'=>'SaveuProduceAsset', 'SaveuProduceAssetResponse'=>'SaveuProduceAssetResponse'); 
			
			$Options = array (	
						'soap_version'=>SOAP_1_2, 
						'trace'=>1, 
						'classmap'=>$Classmap, 
						
						//'uri'=>"http://24.227.64.160/webservices/"
						//Daniel -07/14/08
						//'uri'=>"http://71.99.204.143/webservices/"
						'uri'=>"http://gateway.printhd.us/webservices/"  // I think this is the correct path - Rick 2021-03-01
					);
			
			# Set up the wsdl soap client.
			//$Client2 = new SoapClient ("http://24.227.64.160/webservices/wsdl/ammsinternal.wsdl", $Options);
			//Daniel -07/14/08
			// $Client2 = new SoapClient ("http://71.99.204.143/webservices/wsdl/ammsinternal.wsdl", $Options);
			$Client2 = new SoapClient ("http://gateway.printhd.us/webservices/wsdl/ammsinternal.wsdl", $Options); // I think this is the correct
			
			
			
			$CSV 				= new AccuzipMakeCSV();
			$Response 			= new AccuzipMakeCSVResponse();
			
			
			$CSV->UploadId		= $upload_id;
			
			
			try {
				$Response = $Client2->AccuzipMakeCSV($CSV);
				
			} catch ( SoapFault $E ) {
				$Response->Code 	= ERROR;
				$Response->Desc		=  "AccuzipMakeCSV error" . print_r($E, true) . "<br />";
			}
			#echo $Client->__getLastResponse();
			
			
			return $Response;
			
		}
			
			
			
		
		/**
		* Private Method Function: processMakePullFromList
		*********************************************************************************/
		private function processMakePullFromList($client_id=0, $customer_id=0, $user_id = 0, $list_id = 0)
		{
			
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			$CPull			= new Pull($this->database);
			$CPulled		= new Pulled($this->database);
			$CNameMaster	= new NameMaster($this->database);
			$CPullDetail	= new PullDetail($this->database);
			$Response		= new MakePullFromListResponse();
			
			$address_list	= new ArrayOfAmmsAddressOut();
			
			
			$CPull->DebugOn();
			
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			
			if ( $list_id > 0 ) {
				$amms_list_data = AmmsListDataPeer::retrieveByPk($list_id);
				$iUploadIndex	= $amms_list_data->getUploadId();
				$iPullIndex		= $amms_list_data->getPullId();
				
				$pull_id = 0;
				if ( $iPullIndex > 0 ) {
					# just return the pull_id
					$pull_id = $iPullIndex;	
				
				} else {
					# No pull was set so let's just create a new pull
					$CPull->reset();
					unset($CPull->iPullIndex);	#			# Create a new record
					$CPull->sDescription 		= "Admin - ";
					$CPull->iPulledByUserIndex 	= 4;
					$CPull->dtPulled 			= date("Y-m-d H:i:s");
					$CPull->sStatus 			= "Pending";
					$CPull->sMode				= "New";
					$CPull->iClientIndex		= $client_id;
					$CPull->iCustomerIndex		= $customer_id;
					$CPull->cBarcodeOnly		= "Y";
					$CPull->cScfOnly			= "N";
					$CPull->cUseNCOA			= "Y";
					$CPull->sFilterQuery		= "1";
					$CPull->cProcessing			= "N";
					$CPull->cActive				= "Y";
					$CPull->cCloned				= "N";
					$CPull->cUniqueAddress		= "Y";
					$CPull->sFilterList 		= $CPull->GetEmptyFilterList();
					echo " trying to CPull->GetEmptyFilterList<br />";
					$CPull->RebuildQuery();
					$CPull->sFilterQuery 		= $CPull->GetDefaultFilterQuery();
					if ( !$CPull->store())
					{
						echo "Store failed with " . $CPull->_db->getErrorMsg();
					}
					echo " storing query<br />";
					
					$iPullIndex 				= $CPull->iPullIndex;
					$pull_id 					= $iPullIndex;
					echo "pull_id = $pull_id<br />";
					
					$CPullDetail->reset();
					$CUpload->load($iUploadIndex);
					unset($CPullDetail->iPullDetailIndex);	# So we create a new record
					$CPullDetail->iPullIndex = $CPull->iPullIndex;
					$CPullDetail->iUploadIndex = $iUploadIndex;
					$CPullDetail->sAction = "Include";
					$CPullDetail->iCategoryIndex = 1;
					$iMaxCount = 0;
					if ( $iMaxCount == 0 ) {
						if ( $CPull->cUseNCOA == 'Y' ) {
							$iMaxCount = $CUpload->iNetRecords;
						} else {
							$iMaxCount = $CUpload->iGrossRecords;
						}
					}
					$CPullDetail->iMaxCount = $iMaxCount;
					$CPullDetail->store();
					echo "storing CPullDetail<br />";
					
					echo "reloading pull ($pull_id)<br />";
					$CPull->load($pull_id);
					
					# Get the actual pulled table built
					echo "CPull->iPullIndex = " . $CPull->iPullIndex . "<br />";
					echo "calling CPull->GetFilterQueryList<br />";
					$CPull->GetFilterQueryList();

					
					$amms_list_data->setPullId($iPullIndex);
					$amms_list_data->save();
				}
			}
			
			$Response->Code			= SUCCESS;
			$Response->PullId		= $pull_id;
			return $Response;
		}
		
		
		/**
		* Private Method Function: processGetListStatus
		*********************************************************************************/
		private function processGetPull ($client_id=0, $customer_id=0, $user_id = 0, $list_id = 0)
		{
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			$CNameMaster	= new NameMaster($this->database);
			$CPull			= new Pull($this->database);
			$CPulled		= new Pulled($this->database);
			
			$address_list	= new ArrayOfAmmsPullOut();
			
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			
			if ( $list_id > 0 ) {
			
				$amms_list_data = AmmsListDataPeer::retrieveByPk($list_id);
				$iUploadIndex 	= $amms_list_data->getUploadId();
				$iPullIndex		= $amms_list_data->getPullId();

				
					
				#$Response->Code			= ERROR;
				#$Response->ErrorCode	= 1099;
				#$Response->Desc			= "list_id = " . print_r($list_id, true);
				#return $Response;
					
				$status_code = false;
				if ( $CPull->load($iPullIndex) ) {
					$lProcessedDate	= strtotime($CPull->dtProcessed);
					$lPulledDate	= strtotime($CUpload->dtPulled);
					if ( $lProcessedDate > $lPulledDate && $CPull->cProcessing == 'N' ) {
						$status_code = true;
					} elseif ( strlen($CPull->sTempTableName) > 0 && $CPull->sMode ) {
						# Not moved from temp just yet
						$Response->Code			= ERROR;
						$Response->ErrorCode	= 1036;
						$Response->Desc			= ERROR_1036_DESC;
						return $Response;
					} elseif ( $CPull->dtProcessed == '0000-00-00 00:00:00' ) {
						# Not procesed yet
						$Response->Code			= ERROR;
						$Response->ErrorCode	= 1035;
						$Response->Desc			= ERROR_1035_DESC;
						return $Response;
					}
				} else {
					# Oops - can't load the record.
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1034;
					$Response->Desc			= ERROR_1034_DESC;
					return $Response;
				}
			
				echo "iPullIndex = $iPullIndex<br />";
				$count = $CPulled->GetAllIndexesByPull('sZip', 'asc', 0, 100000, $iPullIndex);
				echo "count = $count<br />";
				if ( $count > 0 ) {
					foreach($CPulled->_a_allIndex as $iKey => $iPulledIndex) {
						$CPulled->load($iPulledIndex);
						$iUploadIndex 		= $CPulled->iPulledIndex;
						$iUploadDataIndex 	= $CPulled->iUploadDataIndex;
						
						#$CUploadData->GetByUploadRecord($iUploadIndex, $row_id);
						$CUploadData->load($iUploadDataIndex);					
						$row_id = $CUploadData->iUploadRecordIndex;
						
				
						$CUploadData->GetByUploadRecord($iUploadIndex, $row_id);
						
						
						if ( $CUploadData->iNameMasterIndex > 0 ) {
							$address = new AmmsPullOut();
							$address->RowId		= $row_id;
							$address->Prefix	= $CUploadData->sPrefix;
							$address->First		= $CUploadData->sFirst;
							$address->Middle	= $CUploadData->sMiddle;
							$address->Last		= $CUploadData->sLast;
							$address->Suffix	= $CUploadData->sSuffix;
							
							$CNameMaster->load($CPulled->iNameMasterIndex);
							
							# Is this a move? (ignore address suffix because of normalization (Drive -> DR))
							$src_addr = explode(" ", strtoupper(trim($CUploadData->sAddress)));
							$new_addr = explode(" ", strtoupper(trim($CNameMaster->sAddress)));
							$address->MoveYn = 'N';
							if ( count($src_addr) >= 1 ) {
								for($i = 0; $i < count($src_addr) -1; $i++) {
									if ( $src_addr[$i] != $new_addr[$i] ) $address->MoveYn = 'Y';
								}
							}
							$address->ValidYn		= "Y";
							$address->Address		= $CNameMaster->sAddress;
							$address->Suite			= $CNameMaster->sSuite;
							$address->City			= $CNameMaster->sCity;
							$address->State			= $CNameMaster->sState;
							$address->Zip			= $CNameMaster->sZip;
							$address->PostalBarcode = $CNameMaster->sZipBarcode;
							$address->PostalCRRT	= $CNameMaster->sCRRT;
							$address->PostalSCF		= $CNameMaster->sSCF;
							$address->PostalDPBC	= $CNameMaster->sDPBC;
							$address->PostalDPC		= $CNameMaster->sDPC;
							$address->Zip5			= $CNameMaster->sZip5;
							$address->Zip4			= $CNameMaster->sZip4;
							$address->CountyNumber	= $CNameMaster->sCountyNumber;
							$address->CountyName	= $CNameMaster->sCountyName;
							$address->Lat			= $CNameMaster->sLat;
							$address->Lon			= $CNameMaster->sLon;
							$address->iNameMasterIndex	= $CNameMaster->iNameMasterIndex;
						} 
						$address->FullBarcode	= $CPulled->sFullBarcode;
						$address->Extra			= $extra;
						
						$address_list->AmmsPullOut[] = $address;
					} # Foeach
					
					$Response->Code			= SUCCESS;
					$Response->PullOut		= $address_list;
					return $Response;
				} else {
					# Nothing returned
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1101;
					$Response->Desc			= ERROR_1101_DESC;
					return $Response;
				}
				
			} else {
				# List ID not found
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1102;
				$Response->Desc			= ERROR_1102_DESC;
				return $Response;
			}
		}
		
		
		/**
		* Private Method Function: processGetListStatus
		*********************************************************************************/
		private function processGetPullByPull ($client_id=0, $customer_id=0, $user_id = 0, $pull_id = 0)
		{
			
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			$CNameMaster	= new NameMaster($this->database);
			$CPull			= new Pull($this->database);
			$CPulled		= new Pulled($this->database);
			
			$address_list	= new ArrayOfAmmsPullOut();
			
			# Is the user permitted this service?
			$valid_user = false;
			foreach($valid_users as $valid_user_id) {
				if ( $user_id == $valid_user_id ) $valid_user = true;
			}
			if ( !$valid_user ) {
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1007;
					$Response->Desc			= ERROR_1007_DESC;
					return $Response;
			
			}
			
//				$Response->Code			= ERROR;
//				$Response->ErrorCode	= 1099;
//				$Response->Desc			= "pull_id = " . print_r($pull_id, true);
//				return $Response;
			if ( $pull_id > 0 ) {
			
				$iPullIndex		= $pull_id;
				
					
					
				$status_code = false;
				if ( $CPull->load($iPullIndex) ) {
					$lProcessedDate	= strtotime($CPull->dtProcessed);
					$lPulledDate	= strtotime($CUpload->dtPulled);
					if ( $lProcessedDate > $lPulledDate && $CPull->cProcessing == 'N' ) {
						$status_code = true;
					} elseif ( strlen($CPull->sTempTableName) > 0 && $CPull->sMode ) {
						# Not moved from temp just yet
						$Response->Code			= ERROR;
						$Response->ErrorCode	= 1036;
						$Response->Desc			= ERROR_1036_DESC;
						return $Response;
					} elseif ( $CPull->dtProcessed == '0000-00-00 00:00:00' ) {
						# Not procesed yet
						$Response->Code			= ERROR;
						$Response->ErrorCode	= 1035;
						$Response->Desc			= ERROR_1035_DESC;
						return $Response;
					}
				} else {
					# Oops - can't load the record.
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1034;
					$Response->Desc			= ERROR_1034_DESC;
					return $Response;
				}
			
			
				$count = $CPulled->GetAllIndexesByPull('sZip', 'asc', 0, 100000, $iPullIndex);
				if ( $count > 0 ) {
					foreach($CPulled->_a_allIndex as $iKey => $iPulledIndex) {
						$CPulled->load($iPulledIndex);
						$iUploadIndex 		= $CPulled->iPulledIndex;
						$iUploadDataIndex 	= $CPulled->iUploadDataIndex;
						
						#$CUploadData->GetByUploadRecord($iUploadIndex, $row_id);
						$CUploadData->load($iUploadDataIndex);					
						$row_id = $CUploadData->iUploadRecordIndex;
						
				
						$CUploadData->GetByUploadRecord($iUploadIndex, $row_id);
						
						
						if ( $CUploadData->iNameMasterIndex > 0 ) {
							$address = new AmmsPullOut();
							$address->RowId		= $row_id;
							$address->Prefix	= $CUploadData->sPrefix;
							$address->First		= $CUploadData->sFirst;
							$address->Middle	= $CUploadData->sMiddle;
							$address->Last		= $CUploadData->sLast;
							$address->Suffix	= $CUploadData->sSuffix;
							
							$CNameMaster->load($CPulled->iNameMasterIndex);
							
							# Is this a move? (ignore address suffix because of normalization (Drive -> DR))
							$src_addr = explode(" ", strtoupper(trim($CUploadData->sAddress)));
							$new_addr = explode(" ", strtoupper(trim($CNameMaster->sAddress)));
							$address->MoveYn = 'N';
							if ( count($src_addr) >= 1 ) {
								for($i = 0; $i < count($src_addr) -1; $i++) {
									if ( $src_addr[$i] != $new_addr[$i] ) $address->MoveYn = 'Y';
								}
							}
							$address->ValidYn		= "Y";
							$address->Address		= $CNameMaster->sAddress;
							$address->Suite			= $CNameMaster->sSuite;
							$address->City			= $CNameMaster->sCity;
							$address->State			= $CNameMaster->sState;
							$address->Zip			= $CNameMaster->sZip;
							$address->PostalBarcode = $CNameMaster->sZipBarcode;
							$address->PostalCRRT	= $CNameMaster->sCRRT;
							$address->PostalSCF		= $CNameMaster->sSCF;
							$address->PostalDPBC	= $CNameMaster->sDPBC;
							$address->PostalDPC		= $CNameMaster->sDPC;
							$address->Zip5			= $CNameMaster->sZip5;
							$address->Zip4			= $CNameMaster->sZip4;
							$address->CountyNumber	= $CNameMaster->sCountyNumber;
							$address->CountyName	= $CNameMaster->sCountyName;
							$address->Lat			= $CNameMaster->sLat;
							$address->Lon			= $CNameMaster->sLon;
							$address->iNameMasterIndex	= $CNameMaster->iNameMasterIndex;
						} 
						$address->FullBarcode	= $CPulled->sFullBarcode;
						$address->Extra			= $extra;
						
						$address_list->AmmsPullOut[] = $address;
					} # Foeach
					
					$Response->Code			= SUCCESS;
					$Response->PullOut		= $address_list;
					return $Response;
				} else {
					# Nothing returned
					$Response->Code			= ERROR;
					$Response->ErrorCode	= 1101;
					$Response->Desc			= ERROR_1101_DESC;
					return $Response;
				}
				
			} else {
				# List ID not found
				$Response->Code			= ERROR;
				$Response->ErrorCode	= 1102;
				$Response->Desc			= ERROR_1102_DESC;
				return $Response;
			}
			
		
		
		
		}
		
		
		/**
		* Private Method Function: processImportFromPander
		*********************************************************************************/
		public function processImportFromPander ()
		{	
			# Does the user have rights to add the value in the first place?
			
			$valid_users = array( 4 );
			
			echo "Inside processImportFromPander() \r\n";
			$C = new Criteria();
			$C->add(AmmsListPanderPeer::IMPORT_ID, 0);
			$C->add(AmmsListPanderPeer::ROW_ID, 0);
			$C->add(AmmsListPanderPeer::ADDRESS_ID, 0);
			$C->add(AmmsListPanderPeer::NAME_MASTER_INDEX, 0);
			
			$new_pander_list = AmmsListPanderPeer::doSelect($C);
			$list_count = count($new_pander_list);
			echo "new_pander_list count = $list_count\r\n";
			
			if ( $list_count > 0 ) {
			
				# Create new import
				$import = new Import();
				$import->setClientId(0);
				$import->setCustomerId(0);
				$import->setImportDate(date("Y-m-d H:i:s"));
				$import->setImportUser(4);
				$import->setKnownFormatId(39);
				$import->setDataVendorId(0);
				$import->setFileName("");
				$import->setFileMd5("");
				$import->setFileSize(0);
				$import->setImportType("pander");
				$import->setImportSystem("pander");
				$import->setNcoaYn("N");
				
				$import->save();
				
				$import_id = $import->getImportId();
				
				# Create import header rows
				$fields = array('0' => array('field_name' => 'name', 		'maps_to' => 'FULLNAME'),
								'1' => array('field_name' => 'address',  	'maps_to' => 'ADDRESS'),
								'2' => array('field_name' => 'suite',  		'maps_to' => 'SUITE'),
								'3' => array('field_name' => 'city',  		'maps_to' => 'CITY'),
								'4' => array('field_name' => 'state',  		'maps_to' => 'STATE'),
								'5' => array('field_name' => 'zip', 		'maps_to' => 'ZIP')
								);
				
				foreach($fields as $field_id => $field_data) {
					$field_name = $field_data['field_name'];
					$maps_to	= $field_data['maps_to'];
					$import_data_header = new ImportDataHeader();
					$import_data_header->setImportId($import_id);
					$import_data_header->setFieldName($field_name);
					$import_data_header->setFieldId($field_id);
					$import_data_header->setFieldType('string');
					$import_data_header->setMapsTo($maps_to);
					$import_data_header->setFieldOrderId($field_id);
					$import_data_header->save();
					
				}
				
				$row = 0;
				foreach($new_pander_list as $pander) {
					$data_row = new ImportDataRow();
					
					$data_row->setImportId($import_id);
					$data_row->setRowId($row);
					$data_row->setUploadedDate(date("Y-m-d H:i:s"));
					$data_row->setAddressId(0);
					$data_row->setPrevAddressId(0);
					$data_row->setAddressErrors("");
					$data_row->setDistMiles(0);
					$data_row->setRadialDeg(0);
					$data_row->setStr('');
					$data_row->setStr1($pander->getAddress());
					$data_row->setStr2($pander->getSuite());
					$data_row->setStr3($pander->getCity());
					$data_row->setStr4($pander->getState());
					$data_row->setStr5($pander->getZip());
					
					$data_row->save();
					
					$pander->setImportId($import_id);
					$pander->setRowId($row);
					$pander->save();
					
					$row++;
				}
			}
			
			return count($new_pander_list);
		}
		
		
		
		
		public function processSyncCustomerToPander()
		{
			# select * from customer where customer_id not in amms_list_pander
			
			echo "inside processSyncCustomerToPander() \r\n";
			
			$C = new Criteria();
			$C->clearSelectColumns(); 
			$C->addSelectColumn(AmmsListPanderPeer::CUSTOMER_ID);
			$C->setDistinct();
			$pander_customer_record = AmmsListPanderPeer::doSelectRS($C);
			while($pander_customer_record->next()) {
				$pander_customer_list[] = $pander_customer_record->getInt(1);
			}
			echo "pander_customer_list = " . print_r($pander_customer_list, true) . "\r\n";
			
			
			$C = new Criteria();
			$C->clearSelectColumns(); 
			$C->add(CustomerPeer::CUSTOMER_ID, $pander_customer_list, Criteria::NOT_IN);
			$customer_list = CustomerPeer::doSelect($C);
			echo "customer_list = " . count($customer_list) . " records\r\n";
			
			if ( count($customer_list) > 0 ) {
				foreach($customer_list as $customer) {
					$pander = new AmmsListPander();
					$pander->setClientId($customer->getClientId());
					$pander->setCustomerId($customer->getCustomerId());
					$pander->setAddressId(0);
					$pander->setNameMasterIndex(0);
					$pander->setImportId(0);
					$pander->setRowId(0);
					$pander->setAddress($customer->getAddress());
					$pander->setCity($customer->getCity());
					$pander->setState($customer->getState());
					$pander->setZip($customer->getZip());
					
					$pander->save();
				}
			}
			
			return count($customer_list);
			
		}
		
		
		private function processDupeProductConsumerCheck($client_id=0, $customer_id=0, $us2_product_id=0, $consumer_id=0)
		{
			
		
		}
		
		private function processDupeProductCheckDate($client_id=0, $customer_id=0, $consumer_id=0, $us2_product_id=0, $mail_after_date='0000-00-00')
		{
			# processDuepProductCheck
			# =====================================
			# 2008-07-10 - Rick
			# Checks to see if the product was mailed to a consumer after a given day.
			
			$dupe_found = false;
			
			$C = new Criteria();
			$C->add(MailHistoryPeer::CLIENT_ID, $client_id);
			$C->add(MailHistoryPeer::CUSTOMER_ID, $customer_id);
			$C->add(MailHistoryPeer::MAIL_DATE, $mail_after_date, Criteria::GREATER_THAN);
			
			$result_list = MailHistoryPeer::doSelect($C);
			if ( is_array($result_list) ) $dupe_found = true;
			if ( is_object($result_list) ) $dupe_found = true;
			
			return $dupe_found;
			
		}
	
		/**
		* Private Method Function: GetUserByIP
		*********************************************************************************/
		private function GetUserByIp ()
		{
			#$WebserviceUserIp = new WebserviceUserIpPeer();
			#return $WebserviceUserIp->GetUserByIp( $_SERVER['REMOTE_ADDR'] );
			return true;
		}
		
		private function LogOut($sMsg='', $sObj) {
		
			#$fh = fopen('E:/Program Files/Apache Software Foundation/Apache2.2/htdocs/us2_inm/inmproject/log/amms_list.log', 'a+');
			$fh = fopen(SF_ROOT_DIR.'/log/amms_list.log', 'a+');
			fwrite($fh, date("m/d/Y H:i:s") . "\t$sMsg\n");   
			if ( is_object($sObj) || is_array($sObj) ) {
				fwrite($fh, print_r($sObj, true) . "\n");   
			}
			
			fclose($fh);	
		}
		
		
		
		# AssignPullToWorkOrder
		# ======================================================================================================
		public function AssignPullToWorkOrder($pull_id=0, $work_order_number='', $test_mode = false)
		{
			# 8/1/2008 - Rick
		
			$CUpload 		= new Upload($this->database);
			$CUploadData 	= new UploadData($this->database);
			$CNameMaster	= new NameMaster($this->database);
			$CPull			= new Pull($this->database);
			$CPulled		= new Pulled($this->database);
			$Response		= array('Code' => '', 'Desc' => '');
			
			echo "pull_id = $pull_id<br />work_order_number=$work_order_number<br />";
			if ( $pull_id > 0 )
			{
				if ( strlen($work_order_number) >= 12 ) 
				{
					if ( $CPull->load($pull_id) )
					{
						$existing_wo_num	= $CPull->sWorkOrderNum;
						$existing_status	= $CPull->sStatus;
						$existing_mode		= $CPull->sMode;
						
						if ( $existing_wo_num == '')
						{
							if ( $existing_status == 'Pending' )
							{
								# Clean up the work order
								# Get the last character of the string
								$last_char = substr($work_order_number, strlen($work_order_number) -1, 1);
								$last_char_ascii = ord($last_char);
								
								# Do we want to trim the last character off of the string?
								$trim = true;	
								
								# if last char is in [0-9] - then don't trim
								if ( $last_char_ascii >= 48 && $last_char_ascii <= 57 ) $trim = false;	
								
								$sWorkOrderNum = $work_order_number;
								if ( $trim ) 
								{
									$sWorkOrderNum = substr($work_order_number, 0, strlen($work_order_number) -1);
								}
								
								# What mode is the pull in? - Adjust the mode so it'll process correctly
								switch($existing_mode)
								{
									case 'Saved':
										$sMode = $existing_mode;
										break;
									case 'ToSave':
										$sMode = $existing_mode;
										break;
									case 'New';
										$sMode = 'ToSave';
										break;
									case 'Edit';
										$sMode = 'ToSave';
										break;
									default:
										$sMode = $existing_mode;
										break;
								}
								# set the flags to 'assigned'
								$CPull->sWorkOrderNum 	= $sWorkOrderNum;
								$CPull->sMode			= $sMode;
								$CPull->sStatus			= "Assigned";
								if ( !$test_mode ) {
									# Actual work
									if ( $CPull->store() )
									{
										$Response['Code']	= SUCCESS;
										$Response['Desc']	= '';
									} else {
										$Response['Code']	= ERROR;
										$Response['Desc']	= 'Save failed with' . $CPull->getError();
									}
								} else {
									# Test mode report
									echo "Would assign...\r\n";
									echo "  sWorkOrderNum	= $sWorkOrderNum\r\n";
									echo "  sMode	= $sMode\r\n";
									echo "  sStatus	= $CPull->sStatus\r\n";
									$Response['Code'] = ERROR;
									$Response['Desc']	= 'Test mode = true';
								}
							} else {
								$Response['Code']	= ERROR;
								$Response['Desc']	= 'Pull Status is not assignable.  Current status = ' . $existing_status;
							}
						} else {
							$Response['Code']	= ERROR;
							$Response['Desc']	= 'Already has work order assigned';
						}
					}
				} else {
					$Response['Code']	= ERROR;
					$Response['Desc']	= "work_order_number ($work_order_num) must be a valid work order number";			
				}
			} else {
				$Response['Code']	= ERROR;
				$Response['Desc']	= 'pull_id must be > 0';
			}
			return $Response;
		}
		
		
		
		# GetNewBarcodePrefix
		# ======================================================================================================
		public function GetNewBarcodePrefix()
		{
		
			$CDropCodes 		= new DropCodes($this->database);
			
			unset($CDropCodes->iDropCodeIndex);
			$CDropCodes->iPullIndex			= 0;
			$CDropCodes->iPullOutputIndex	= 0;
			$CDropCodes->cActive			= 'Y';
			$CDropCodes->store();
			$iDropCodeIndex = $CDropCodes->iDropCodeIndex;
			
			$prefix = strtoupper(dechex($iDropCodeIndex));
			
			return $prefix;
		}
		
		
	}
	
	
	
	
	//Daniel -07/14/08
	class AccuzipMakeCSV
	{
		public $UploadId;
	}
	//Daniel -07/14/08
	class AccuzipMakeCSVResponse
	{
		public $Code;
		#public $ErrorCode;
		#public $Desc;
	}
	


?>