<?php

// USE THE PRODUCTION SYSTEM NOW!


$SPADE['template']->assign('pgLayout', 'none');

define('EHC_SESSION_KEY', 'Mr.Blodgett and Mr.Gwynn');


$fp = fopen ('webservices.log.php', 'a');
fwrite($fp, date('Ymd-His') . ':::Request from:' . $_SERVER['REMOTE_ADDR'] . ':::' . $HTTP_RAW_POST_DATA."\n");
fclose($fp);

echo "Allo allo";
exit();

function authenticateCompany( $username, $password, $companyId ) {
	global $SPADE;

	$ipAddress = $_SERVER['REMOTE_ADDR'];		// This should be the IP of the connecting host

	$Q = "SELECT ci.*, c.userId, c.companyName, c.companyVanity
		FROM company_integrations ci
		INNER JOIN companies c ON (ci.companyId = c.id)
		WHERE ci.companyId = " . (int)$companyId . "
		AND ci.username = '" . $username . "'
		AND ci.password = '" . md5($password) . "'
		AND ci.ipAddress = '" . $ipAddress . "'
		AND ci.isActive = 'yes'";

	return $SPADE['db']->query($Q, DB_ROW);
}


class EhcIntegrationService { 
	//private $quotes = array("ibm" => 98.42);   
	
	function createSession($objSession) { 
		global $SPADE;

		$objResponse = new stdClass();

		$username = $objSession->username;
		$password = $objSession->password;
		$companyId = $objSession->company_id;
		$foreignId = $objSession->foreign_id;
		$emailAddress = $objSession->email_address;  // email address of end user

		$company = authenticateCompany($username, $password, $companyId);

		if (TRUE || !$emailAddress || !$company) {

			$objResponse->user_id = '0';
			$objResponse->session_id = 'ERROR';
			//$objResponse->detail = 'Unauthorized, unregistered, bad login, or no email address specified.';
			$objResponse->detail = 'This response came from the NEW server. Please clear WSDL cache.';
			$objResponse->company_vanity = 'unknown';

			return $objResponse;
		}

		$ipAddress = $objSession->ip_address;  // IP address of the end-user
		$firstName = $objSession->first_name;
		$lastName = $objSession->last_name;
		$address = $objSession->address;
		$city = $objSession->city;
		$state = $objSession->state;
		$phone = $objSession->phone;

		/*// Optional section to delete entries that are expired
		$Q = "DELETE FROM user_sessions WHERE expirationDate < " . time();
		$SPADE['db']->query($Q);
		//*/

		/*// Optional section to delete existing entries for this email address
		$Q = "DELETE FROM user_sessions WHERE emailAddress = '" . $emailAddress . "'";
		$SPADE['db']->query($Q);
		//*/

		$Q = "SELECT *
			FROM _users
			WHERE foreignId = '" . $foreignId . "'";
			//WHERE email = '" . $emailAddress . "'";   // Old method

		$userCheck = $SPADE['db']->query($Q);

		if (!is_array($userCheck)) {
			$objResponse->user_id = 0;
			$objResponse->detail = 'New user. Ready to be created.';
			$objResponse->company_vanity = serialize($company); //$company['companyVanity'];
			
			$temp = array('email' => $emailAddress,
					'firstName' => $firstName,
					'lastName' => $lastName,
					'address' => $address,
					'city' => $city,
					'state' => $state,
					'phone' => $phone
				);

			// serialize user details to be stored in notes for session	
			$sessionNotes = serialize($temp);

		} elseif ( count($userCheck) > 1) {
			$objResponse->user_id = 0;
			$objResponse->session_id = 'ERROR';
			$objResponse->detail = 'Duplicate e-mail address. Contact us for help.';
			$objResponse->company_vanity = 'unknown';

			return $objResponse;

		} elseif ( count($userCheck) == 1) {
			// good things...
			$userCheck = $userCheck[0];

			$objResponse->user_id = $userCheck['id'];
			$objResponse->detail = 'Existing user, ready to authenticate.';
			$objResponse->company_vanity = $company['companyVanity'];

			$sessionNotes = $objResponse->detail;
			
		} else {
			return 'FATAL ERROR';
		}

		$objResponse->session_id = ($objResponse->session_id)
						? $objResponse->session_id
						: md5($username . $password . $emailAddress . microtime() . EHC_SESSION_KEY);

		$Q = "INSERT INTO user_sessions (userId, companyId, foreignId, emailAddress, ipAddress, referer, sessionId, expirationDate, notes)
			VALUES (" . (int)$objResponse->user_id . ",
				" . (int)$companyId . ",
				'" . $foreignId . "',
				'" . $emailAddress . "',
				'" . $ipAddress . "',
				'" . $company['domain'] . "',
				'" . $objResponse->session_id . "',
				" . (time() + 3600) . ",
				'" . $sessionNotes . "')";

		if (!$SPADE['db']->query($Q)) {
			$objResponse->session_id = 'XXXXXX';
			$objResponse->detail = 'Unable to create session.';
		}

		return $objResponse; 
	}

	function sendEstatEntries($objEstatEntries) {
		global $SPADE;

		$username = $objEstatEntries->username;
		$password = $objEstatEntries->password;
		$companyId = $objEstatEntries->company_id;

		$objResponse = new stdClass();
		$objResponse->estat_entry = array();

		if (!is_array($objEstatEntries->estat_entry)) {
			$objResponse->estat_entry[] = array(
					'id' => 0,
					'confirmation' => 'estat entry not an array.'
			);

			return $objResponse;
		}
			
		if (!count($objEstatEntries->estat_entry)) {
			$objResponse->estat_entry[] = array(
					'id' => 0,
					'confirmation' => 'estat entries count failed.'
			);

			return $objResponse;
		}

		if (!($company = authenticateCompany($username, $password, $companyId))) {
			$objResponse->estat_entry[] = array(
					'id' => 0,
					'confirmation' => 'unable to authenticate company.'
			);

			return $objResponse;
		}
		
		if (!is_array($objEstatEntries->estat_entry)
			|| !count($objEstatEntries->estat_entry) 
			|| !($company = authenticateCompany($username, $password, $companyId))) {

			$objResponse->estat_entry[] = array(
					'id' => 0,
					'confirmation' => 'Unauthorized, unregistered, bad login, or no estat entries specified.'
			);

			return $objResponse;
		}

		
		$users = array();

		foreach ($objEstatEntries->estat_entry as $entry) {
			// get user info for this user, if we don't already have it loaded

			if (!$users[$entry->foreign_id]['id']) {
				//$Q = "SELECT * FROM _users WHERE email = '" . $entry->email_address . "'";
				$Q = "SELECT * FROM _users WHERE foreignId = '" . $entry->foreign_id . "'";
				
				$users[$entry->foreign_id] = $SPADE['db']->query($Q, DB_ROW);

				if (!$users[$entry->foreign_id]) {
					// couldn't find user by foreign ID
					$objResponse->estat_entry[] = array(
						'id' => 0,
						'confirmation' => 'Could not find user with foreign ID "' . $entry->foreign_id . '".'
					);

					continue;
				}
			}

			/*//
			$objResponse = new stdClass();
			$objResponse->estat_entry[] = array('id' => 0,'confirmation' => 'Query:' . $Q);
			return $objResponse;
			//*/

			$Q = "REPLACE INTO estat_entries (userId, estatId, value, dateOfEntry, createdByUserId, dateCreated)
				VALUES (
					" . (int)$users[$entry->foreign_id]['id'] . ",	
					" . (int)$entry->estat_id . ",
					'" . $entry->value . "',
					'" . strtotime($entry->date_of_entry) . "',
					" . (int)$company['userId'] . ",
					" . time() . "
				)";

			if ($newId = $SPADE['db']->query($Q)) {
				$objResponse->estat_entry[] = array(
					'id' => $newId,
					'confirmation' => 'eStat entry recorded successfully.'
				);
			} else {
				$objResponse->estat_entry[] = array(
					'id' => 0,
					'confirmation' => 'An error occurred while attempting to record this estat entry.'
				);
			}
		}

		return $objResponse;
	}
}

class EhcIntegrationServiceRpcEnc extends EhcIntegrationService {
	function createSession($username, $password, $company_id, $foreign_id, $email_address, $ip_address, $first_name, $last_name, $address, $city, $state, $phone) {
		$objSession = new stdClass();

		$objSession->username = $username;
		$objSession->password = $password;
		$objSession->company_id = $company_id;
		$objSession->foreign_id = $foreign_id;
		$objSession->email_address = $email_address;
		$objSession->ip_address = $ip_address;
		$objSession->first_name = $first_name;
		$objSession->last_name = $last_name;
		$objSession->address = $address;
		$objSession->city = $city;
		$objSession->state = $state;
		$objSession->phone = $phone;

		$objResponse = parent::createSession($objSession);
		$strResponse = $objResponse->user_id . '::' . $objResponse->session_id . '::' . $objResponse->detail . '::' . $objResponse->company_vanity;

		return $strResponse;
	}

	function sendEstatEntries($username, $password, $company_id, $estat_entries) {
		$objEstatEntries = new stdClass();

		$objEstatEntries->username = $username;
		$objEstatEntries->password = $password;
		$objEstatEntries->company_id = $company_id;

		$arrRawEntries = split('%%', $estat_entries);

		foreach ($arrRawEntries as $strRawEntry) {
			$arrEntryElements = split('::', $strRawEntry);

			$objEntry = new stdClass();
			$objEntry->foreign_id = $arrEntryElements[0];
			$objEntry->estat_id = $arrEntryElements[1];
			$objEntry->date_of_entry = $arrEntryElements[2];
			$objEntry->value = $arrEntryElements[3];

			$objEstatEntries->estat_entry[] = $objEntry; 
		}

		$objResponse = parent::sendEstatEntries($objEstatEntries);

		$strResponse = '';

		foreach ($objResponse->estat_entry as $arrEstatEntry) {
			$strResponse .= $arrEstatEntry['id'] . '::' . $arrEstatEntry['confirmation'] . '%%';
		}

		$strResponse = substr($strResponse, 0, -2);

		return $strResponse;
	}
}

if ($_REQUEST['style'] == 'rpcenc') {
	$server = new SoapServer("webservices/eis-rpcenc.wsdl"); 
	$server->setClass("EhcIntegrationServiceRpcEnc");
	$server->handle(); 
} else {
	$server = new SoapServer("webservices/eis-doclit.wsdl"); 
	$server->setClass("EhcIntegrationService");
	$server->handle(); 
}

?>