<?php
	/***********************************************************************************
	*   Filename    : editvet.php
	*   Description : Petsafe Index/Home page
	*
	*   Date        Modification By      Description
	*   23/01/2009  Kenneth Ho           Initial Creation
	*   22/08/2022  John Muffett         Reworked for Data API
   	*
	*   Copyright Keysoft Pty Ltd 2022
	***********************************************************************************/

	/******************** Global Settings ********************/
	require_once '../phpobjects/common/global.php';

	/********************* Page Settings *********************/
	$gaPage['title'] = 'Petsafe.com.au';
	$gaPage['root_directory'] = '..';
	$gaPage['colour'] = 'orange';


	// check email - ajax call
	if (isset($_GET['ajax_check_email'])) {
		$email_error = '';


		if ( empty($_GET['email']) or $_GET['email'] == '' ) {
			$email_error = '<span style="color:red">Email address is mandatory!</span>';

		} else {

			$aRequest = array();
			$aRequest['vet_Email'] = '="' . $_GET['email'] . '"';
			$fmrVet = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest);

			// Check to see if any records were found first.
			if ($fmrVet === FALSE) {
			$countVetEmails = 0;
			} else {
			$fmcVet = $fmrVet["response"]["data"];
			$countVetEmails = count($fmcVet);
			}


			if (strtolower($_GET['email']) == strtolower($_GET['original_email'])){
				$validCount = 1; // email not being updated
			} else {
				$validCount = 0; // email being updated - there should be no other email like the updated value
			}

			if ($countVetEmails > $validCount){
				$email_error = '<span style="color:red">This email address already exists on our records!<br/>Please enter a valid and unique email address.</span>';
			}
		}
		echo $email_error;
		die;
	}

    /************ Only allow logged in vets to this area ************/

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['VetID'] == ''){
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}
	
	/********************* Page Defaults *********************/
	fDefaultParameter('err_code', $_GET, '');
	fDefaultParameter('vetid', $_GET, '');
	fDefaultParameter('vet_state', $_GET, '');
	fDefaultParameter('vet_suburb', $_GET, '');

	// ensure logged-in user is updating their own details
	$vetid = $_GET['vetid'];
	if ($_SESSION['VetID'] != $vetid){
		// Redirect if not authorised to update
		fRedirect('myaccount.php');
		fCleanup();
	}

	// get vet details
	$aRequest = array();
	$aRequest['_pk_vet_id'] = '="' . $vetid . '"';

	$fmrVet = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest);
	$recordID = $fmrVet["response"]["data"][0]["recordId"];
	$fmcVet = $fmrVet["response"]["data"][0]["fieldData"];
	$vetTitle = $fmcVet['vet_title'];
	$vetFirstName = $fmcVet['vet_first_name'];
	$vetLastName = $fmcVet['vet_last_name'];
	$vetDirect = $fmcVet['vet_phone'];
	$vetFax = $fmcVet['vet_fax'];
	$vetEmergency = $fmcVet['vet_emergency'];
	$vetPassword = $fmcVet['vet_password'];
	$vetEmail = $fmcVet['vet_email'];
	$vetLicense = $fmcVet['vet_license_number'];
	$vetImplanter = $fmcVet['implanter_number'];
	$street = $fmcVet['vet_street'];
	$suburb = $fmcVet['vet_suburb'];
	$state = $fmcVet['vet_state'];
	$postcode = $fmcVet['vet_postcode'];
	$vetid = $fmcVet["_pk_vet_id"];

	// check if there is state
	// if yes, then prefill state
	// if no, get out
	// check if there is suburb
	// if yes, then prefill/select suburb
	// if no, get out
	// initialise the popups, so they can be echoed further down
	$states = ["ACT","NSW","NT","QLD","SA","TAS","WA","VIC"];
	$state_popup = popup($states, 'vet_state', $state,'onchange="setSuburbValueList()"');

	if (trim($state) != ""){
		// retrieve states and preselect

		if (trim($suburb) != ""){
			// preselect suburb
			$aRequest = array();
	        $aRequest['State'] = '="' . $state . '"';
	        $suburbsResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
            $suburbsData=$suburbsResult ['response']['data'];
            $suburbs = array();
            foreach ($suburbsData as $suburbsLine)
            {
                $suburbs[]= $suburbsLine["fieldData"]['Suburb'];  
               
            }
            asort($suburbs);
			$suburb_popup = popup($suburbs, 'vet_suburb', $suburb,'onchange="setPostcodeValueList()"');


			if (trim($postcode) != ""){

				// preselect postcode
		        $aRequest = array();
	            $aRequest['State'] = '=="' . $state . '"';
	            $aRequest['Suburb'] = '=="' . $suburb . '"';
	            $postcodesResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
                $postcodeData=$postcodesResult['response']['data'];
                $postcodes = array();
                foreach ($postcodeData as $postcodeLine){
                    $postcodes[]= $postcodeLine["fieldData"]['Postcode'];  
                }
                asort($postcodes);
		    	$postcode_popup = popup($postcodes, 'vet_postcode', $postcode);
			}
		}

	}

	// fill suburbs
	if (isset($_GET['hello_from_ajax1'])) {
		if ( empty($_GET['vet_state']) ) {
			$suburb_popup = '<select name="vet_suburb" disabled="disabled"></select>';
		} else {
			$aRequest = array();
	        $aRequest['State'] = '="' . $_GET['vet_state'] . '"';
	        $suburbsResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
            $suburbsData=$suburbsResult ['response']['data'];
            $suburbs = array();
            foreach ($suburbsData as $suburbsLine)
            {
                $suburbs[]= $suburbsLine["fieldData"]['Suburb'];  
               
            }
            asort($suburbs);
			$suburb_popup = popup($suburbs, 'vet_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');

		}
		echo $suburb_popup;
		die;
	}

	// fill postcodes
	if (isset($_GET['hello_from_ajax2'])) {
		if ( empty($_GET['vet_suburb']) ) {
			$postcode_popup = '<select name="vet_postcode" disabled="disabled"></select>';
		} else {

			$aRequest = array();
	        $aRequest['State'] = '="' . $_GET['vet_state'] . '"';
            $aRequest['Suburb'] = '="' . $_GET['vet_suburb'] . '"';
	        $postcodesResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
            $postcodeData=$postcodesResult['response']['data'];
            $postcodes = array();
            foreach ($postcodeData as $postcodeLine){
                $postcodes[]= $postcodeLine["fieldData"]['Postcode'];  
            }
            asort($postcodes);
            
            if (count($postcodes) == 1){
				$selected_postcode = $postcodes[0];
			}
	    	$postcode_popup = popup($postcodes, 'vet_postcode', $selected_postcode);

		}
		echo $postcode_popup;
		die;
	}

	// default values
	if (empty($_POST['vet_state'])) {
		$selected_state = '';
    } else {
		$selected_state = $_POST['vet_state'];
	}
	if (empty($_POST['vet_suburb'])) {
		$selected_suburb = '';
	} else {
		$selected_suburb = $_POST['vet_suburb'];
	}
	if (empty($_POST['vet_postcode'])) {
		$selected_postcode = '';
	} else {
		$selected_postcode = $_POST['vet_postcode'];
	}


	// initialise lists on first load - if empty
	if (trim($state) == ''){
		$state_popup = popup($states, 'vet_state', $selected_state,'onchange="setTypeValueList()"');
	}
	if (trim($suburb) == ''){
		$suburb_popup = '<select name="vet_suburb" disabled="disabled"></select>';
	}
	if (trim($postcode) == ''){
		$postcode_popup = '<select name="vet_postcode" disabled="disabled"></select>';
	}

	// function to create select list dynamically
	function popup($values, $name, $selected_value = '', $extras = '') {
		$popup = '<select name="' . $name . '" ' . $extras . '>';
		$popup.= '<option value="">- Please select -</option>';
		foreach($values as $value) {
			if (strtoupper($value) == strtoupper($selected_value)) {
				$selected = 'selected="selected"';
			} else {
				$selected = '';
			}
			$popup.= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>';
		}
		$popup.= '</select>';
		return $popup;
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<?php require '../phpobjects/templates/common/page_head.php'; ?>

<script type="text/javascript" src="../javascripts/prototype.js"></script>
<script type="text/javascript" src="../javascripts/common.js"></script>

<script language="javascript">
	// handler to fill suburbs
	function setSuburbValueList(){
		var state_popup = document.forms[0].elements['vet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['vet_suburb'];
		var postcode_popup = document.forms[0].elements['vet_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;
		var url = 'editvet.php?vetid=' + '<?php echo $vetid; ?>' + '&hello_from_ajax1=true&vet_state='+selected_state;
		var target = 'suburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes
	function setPostcodeValueList(){
		var state_popup = document.forms[0].elements['vet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['vet_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['vet_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'editvet.php?vetid=' + '<?php echo $vetid; ?>' + '&hello_from_ajax2=true&vet_suburb='+selected_suburb+'&vet_state='+selected_state;
		var target = 'postcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	function trim(mystring){
		return mystring.replace(/^\s+|\s+$/g, '') ;
	}

	function validateForm(myform) {
		var error1 = 'Please complete the following mandatory field(s):\n';
		var error2 = 'Your password is too short.\nPlease re-enter your password - at least 3 characters.';
		var error3 = 'The two Petsafe Password fields do not match!\nPlease re-enter your password.';
		var error4 = 'Please enter a valid email address.';
		var mandatory_err = 0;

		// check mandatory fields
		// vet_firstname, vet_lastname, vet_email, 
		// vet_password1, vet_password2
		if (trim(myform.vet_firstname.value) == ''){
			myform.vet_firstname.value = '';
			error1 = error1 + '\n- First Name';
			mandatory_err = 1;
		}
		if (trim(myform.vet_lastname.value) == ''){
			myform.vet_lastname.value = '';
			error1 = error1 + '\n- Last Name';
			mandatory_err = 1;
		}

		if (trim(myform.vet_address.value) == ''){
			myform.vet_address.value = '';
			error1 = error1 + '\n- Vet\'s Street Address';
			mandatory_err = 1;
		}
		if (myform.vet_state.selectedIndex == 0){
			error1 = error1 + '\n- Vet\'s State';
			mandatory_err = 1;
		}
		if (myform.vet_suburb.selectedIndex == 0){
			error1 = error1 + '\n- Vet\'s Suburb';
			mandatory_err = 1;
		}
		if (myform.vet_postcode.selectedIndex == 0){
			error1 = error1 + '\n- Vet\'s Postcode';
			mandatory_err = 1;
		}

		if (trim(myform.vet_email.value) == ''){
			myform.vet_email.value = '';
			error1 = error1 + '\n- E-mail';
			mandatory_err = 1;
		}
		if (trim(myform.vet_password1.value) == '' || trim(myform.vet_password2.value) == ''){
			myform.vet_password1.value = '';
			myform.vet_password2.value = '';
			error1 = error1 + '\n- PetSafe Password';
			mandatory_err = 1;
		}
		
		if (mandatory_err != 0){
			alert(error1);
			return false;
		}

		// check for email address duplication
		if (trim(document.getElementById('email_err').innerHTML) != ''){
			alert(error4);
			myform.vet_email.focus();
			return false;
		}

		// check if password is long enough
		if (myform.vet_password1.value.length < 3) {
			alert(error2);
			myform.vet_password1.value = '';
			myform.vet_password2.value = '';
			myform.vet_password1.focus();
			return false;
		}

		// check if passwords match
		if (myform.vet_password1.value != myform.vet_password2.value){
			alert(error3);
			myform.vet_password1.value = '';
			myform.vet_password2.value = '';
			myform.vet_password1.focus();
			return false;
		}

		return true;
	}

	function checkEmail(){
		var vetemail = document.forms[0].elements['vet_email'];
		var selected_vetemail = vetemail.value;
		if (trim(selected_vetemail) != ''){
			var vetid = document.forms[0].elements['vetid'];
			var selected_vetid = vetid.value;
			//alert('editvet.php?ajax_check_email=true&vetid='+selected_vetid+'&email='+selected_vetemail+'&original_email=<?php echo $vetEmail ?>');
			var url = 'editvet.php?ajax_check_email=true&vetid='+selected_vetid+'&email='+selected_vetemail+'&original_email=<?php echo $vetEmail ?>';
			var target = 'email_err';
			var result = new Ajax.Updater(target, url,{method: 'get'});
		}
	}
</script>

</head>

<?php

require '../phpobjects/templates/common/page_header.php';
/*********************** Page Start **********************/
?>

<td valign="top">

<?php
	echo '<br/><h2 class="orangeheading">Edit Vet Account</h2><br/>';

?>

<form action="editvet_submit.php" method="post" name="frmVet" id="frmVet">
<table border="0" width="90%">
	<tr>
		<td>Vet License Number</td>
		<td valign="top">
			<b><?php echo $vetLicense; ?></b>
		</td>
	</tr>
	<tr>
		<td>Implanter Number</td>
		<td valign="top">
			<b><?php echo $vetImplanter; ?></b>
		</td>
	</tr>
	<tr>
		<td>Name</td>
		<td valign="top">
			<table border="0" cellpadding="1">
				<tr>
					<td>Title</td>
					<td><span style="color:red"><sup>*</sup></span> Given Name</td>
					<td><span style="color:red"><sup>*</sup></span> Last Name</td>
				</tr>
				<tr>
					<td>
						<input type="hidden" name="vet_title" value="<?php echo $vetTitle; ?>" />
						<select disabled>
							<option value=""></option>
							<option value="Dr" <?php if ($vetTitle == 'Dr') echo 'selected="selected"'; ?>>Dr</option>
							<option value="Mr" <?php if ($vetTitle == 'Mr') echo 'selected="selected"'; ?>>Mr</option>
							<option value="Mrs" <?php if ($vetTitle == 'Mrs') echo 'selected="selected"'; ?>>Mrs</option>
							<option value="Ms" <?php if ($vetTitle == 'Ms') echo 'selected="selected"'; ?>>Ms</option>
						</select>
					</td>
					<td><input type="text" size="15" value="<?php echo $vetFirstName; ?>" name="vet_firstname" readonly class="disabled" /></td>
					<td><input type="text" size="15" value="<?php echo $vetLastName; ?>" name="vet_lastname"readonly class="disabled" /></td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Street Address</td>
		<td valign="top">
			Unit/Street No &nbsp;&nbsp;Street Name<br/>
			<input type="text" size="30" value="<?php echo $street; ?>" name="vet_address" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> State</td>
		<td valign="top">
			<?php echo $state_popup ?>
		<td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Suburb</td>
		<td valign="top">
			<div id="suburb_container"><?php echo $suburb_popup ?></div>
		<td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Postcode</td>
		<td valign="top">
			<div id="postcode_container"><?php echo $postcode_popup ?></div>
		<td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td>Direct line</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $vetDirect; ?>" name="vet_direct" />
		</td>
	</tr>
	<tr>
		<td>Fax</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $vetFax; ?>" name="vet_fax" />
		</td>
	</tr>
	<tr>
		<td>Emergency number</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $vetEmergency; ?>" name="vet_emergency" />
		</td>
	</tr>
	<tr>
		<td><span style="color:red"><sup>*</sup></span> E-mail</td>
		<td valign="top">
			<input type="text" size="30" value="<?php echo $vetEmail; ?>" name="vet_email" onblur="checkEmail();" />
			<div id="email_err"></div>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td valign="top" nowrap="nowrap"><span style="color:red"><sup>*</sup></span> Enter your Petsafe Password</td>
		<td valign="top">
			<input type="password" size="15" maxlength="12" value="<?php echo $vetPassword; ?>" name="vet_password1" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Re-Enter Password</td>
		<td valign="top">
			<input type="password" size="15" maxlength="12" value="<?php echo $vetPassword; ?>" name="vet_password2" />
		</td>
	</tr>
	<tr>
		<td valign="top">&nbsp;</td>
		<td valign="top">
			The password can contain a combination of letters & numbers both in lower case
			and upper case.<br/>Please limit password to no more than 12 characters.
		</td>
	</tr>
	<tr>
		<td valign="top">&nbsp;</td>
		<td valign="top">
			<input type="hidden" name="recordID" id="recordID" value="<?php echo $recordID; ?>" />
			<input type="hidden" name="vetid" id="vetid" value="<?php echo $vetid; ?>" />
			<br/><input type="submit" value="Update Details" class="button" onclick="javascript: if(!validateForm(this.form)) return false;" />
			<input type="button" value="Cancel" class="button" onclick="javascript: window.location.href = 'myaccount.php';" />
		</td>
	</tr>
</table>
</form>

<br/><br/>

</td>

<?php
/************************ Page End ***********************/

require '../phpobjects/templates/common/page_footer.php';
?>

</html>
<?php fCleanup(); ?>