<?php
	/***********************************************************************************
	*   Filename    : index.php
	*   Description : Petsafe Index/Home page
	*
	*   Date        Modification By      Description
	*   20/10/2008  Shane Schokman       Initial Creation
	*   23/01/2009  Kenneth Ho           Adaptation to Digivet-Petsafe
 	*   23/08/2022  John Muffett         Rework to support 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'] = 'purple';

	/******************* Create the toolbar ******************/


    /********************* Page Defaults *********************/
	fDefaultParameter('err_code', $_GET, '');
	fDefaultParameter('petid', $_GET, '');
	fDefaultParameter('pet_state', $_GET, '');
	fDefaultParameter('pet_suburb', $_GET, '');

	$petid = $_GET['petid'];

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

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['MemberID'] == ''){
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}

    /************ AJAX calls ************/

	// connection to db
	$editinfo = true;

	// fill suburbs
	// if (isset($_GET['hello_from_ajax1'])) {
	// 	if ( empty($_GET['pet_state']) ) {
	// 		$suburb_popup = '<select name="pet_suburb" disabled="disabled"></select>';
	// 	} else {
	// 		$odataQuery = $fm->buildODataQuery([
	// 			'filter' => "State eq '{$_GET['pet_state']}'",
	// 			'count' => true
	// 		]);
	// 		$fmrChip = $fm->get('Suburbs', $odataQuery ,$allPages = true );

	// 		// $aRequest = array();
	//         // $aRequest['State'] = '="' . $_GET['pet_state'] . '"';
	//         //$suburbsResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
    //         $suburbsData=$suburbsResult['data']['value'];
    //         $suburbs = array();
    //         foreach ($suburbsData as $suburbsLine)
    //         {
    //             $suburbs[]= $suburbsLine['Suburb'];  
               
    //         }
    //         asort($suburbs);
	// 		$suburb_popup = popup($suburbs, 'pet_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');

	// 	}
	// 	echo $suburb_popup;
	// 	die;
	// }

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

	// 		$odataQuery = $fm->buildODataQuery([
	// 			'filter' => "State eq '{$_GET['pet_state']}' and Suburb eq '{$_GET['pet_suburb']}'",
	// 			'count' => true
	// 		]);
	// 		$postcodesResult = $fm->get('Suburbs', $odataQuery ,$allPages = true );


	// 		// $aRequest = array();
	//         // $aRequest['State'] = '="' . $_GET['pet_state'] . '"';
    //         // $aRequest['Suburb'] = '="' . $_GET['pet_suburb'] . '"';
	//         // $postcodesResult = fFMPerformFind('petsafe', 'Web - Dynamic Suburbs', $aRequest);
    //         $postcodeData=$postcodesResult['data']['value'];
    //         $postcodes = array();
    //         foreach ($postcodeData as $postcodeLine){
    //             $postcodes[]= $postcodeLine['Postcode'];  
    //         }
    //         asort($postcodes);
            
    //         if (count($postcodes) == 1){
	// 			$selected_postcode = $postcodes[0];
	// 		}
	//     	$postcode_popup = popup($postcodes, 'pet_postcode', $selected_postcode);
	// 	}
	// 	echo $postcode_popup;
	// 	die;
	// }

	if (isset($_GET['hello_from_ajax1'])) {
		if ( empty($_GET['pet_state']) ) {
			$suburb_popup = '<select name="pet_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['pet_state']);
			$suburb_popup = popup($suburbs, 'pet_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');
		}
		echo $suburb_popup;
		die;
	}

	// fill postcodes
	if (isset($_GET['hello_from_ajax2'])) {
		if ( empty($_GET['pet_suburb']) ) {
			$postcode_popup = '<select name="pet_postcode" disabled="disabled"></select>';
		} else {
			$postcodes = getPostCodes($_GET['pet_state'], $_GET['pet_suburb']);
			if (count($postcodes) == 1){
				$selected_postcode = $postcodes[0];
			}
			$postcode_popup = popup($postcodes, 'pet_postcode', $selected_postcode);
		}
		echo $postcode_popup;
		die;
	}

    /****************** Fetch Savage list ******************/
    //$fmrSavage = fFMFindAll('petsafe', 'Web - Savage List');

	
	$fmrSavage = $fm->get('List Savage', [] ,$allPages = true );

    // Fetch all savage types into array
	$fmcSavage = $fmrSavage["data"]["value"];

	/****************** Fetch Pet details if logged in ******************/
	// $aRequest = array();
	// $aRequest['_sk_member_id'] = '="' . $_SESSION['MemberID'] . '"';
	// $aRequest['_pk_pet_id'] = '="' . $petid . '"';

	$odataQuery = $fm->buildODataQuery([
		'filter' => "_sk_member_id eq {$_SESSION['MemberID']} and _pk_pet_id eq {$petid}",
		'count' => true
	]);
	$fmrPet = $fm->get('Pets', $odataQuery ,$allPages = true );

	//$fmrPet = fFMPerformFind('petsafe', 'Web - Pets', $aRequest, null, null, FALSE);
	$fmcPet = $fmrPet["data"]["value"][0];

	// get values
	$petname = $fmcPet['Name'];
	$species = $fmcPet['Type'];
	$colour = $fmcPet['Colour'];
	$breed = $fmcPet['Breed'];
	$dob = $fmcPet['DOB'];
	$sex = $fmcPet['Sex'];
	$desexed = $fmcPet['Desexed'];
	$savage = $fmcPet['Savage'];
	
	$BreederID = $fmcPet['breederID'];
	$DistinguishingMarks = $fmcPet['distinguishingMarks'];
	//$ImplantDate = $fmcPet['Implant Date'];

	$petsafetag = $fmcPet['Tag'];
	$street = $fmcPet['displayStreet'];
	$suburb = $fmcPet['displaySuburb'];
	$state = $fmcPet['displayState'];
	$postcode = $fmcPet['displayPostcode'];

	// get associated chip details
	// $aRequest = array();
	// $aRequest['_sk_pet_id'] = '="' . $petid . '"';
	//$aRequest['Registered'] = '="Yes"';
	$aSort = array();
	$Sort[0] = 'implanted_date';

	$odataQuery = $fm->buildODataQuery([
		'filter' => "_sk_pet_id eq {$petid}",
		'count' => true,
		'orderby' => 'implanted_date asc',
	]);
	$fmrChip = $fm->get('Chips', $odataQuery ,$allPages = true );

	//$fmrChip = fFMPerformFind('petsafe', 'Web - Chips', $aRequest, $aSort, null, FALSE);
	if (!$fmrChip['success'] || $fmrChip["data"]["count"] < 1){
		$microchip = '';
		$microchip2 = '';
		$clinicID = '';
		$clinicname = '';
		$accountnumber = '';

	} else {
		$fmcChip = $fmrChip["data"]["value"];
		$i = 0;
		$microchip2 = '';
		foreach ($fmcChip as $chip_record){
			$i++;
			if ($i == 1){
				$microchip = $chip_record['Chip No'];
				$clinicID = $chip_record['_sk_implanter_clinic_id'];
				$clinicname = $chip_record['clinicName'];
				$accountnumber = $chip_record['clinicAccountNumber'];
				$ImplantDate = $chip_record['implanted_date'];
			} else {
				$microchip2 = $chip_record['Chip No']; 	
				break;
			}
		}
	}
    
  /****** Get Extra page info ******/

    // $aRequest = array();
    // $aRequest['code'] = '="PetUpdateDetails"';

    $extraInfo = getWebContent("PetUpdateDetails");

	// $fmcMemberInfo = $fmrMemberInfo["data"]["value"][0];
	// $extraInfo = $fmcMemberInfo['content'];		

	// 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
	if (trim($state) != ""){
		// retrieve states and preselect

	    $states = ["ACT","NSW","NT","QLD","SA","TAS","WA","VIC"];
	    $state_popup = popup($states, 'pet_state', $state,'onchange="setSuburbValueList()"');
		//$mailstate_popup = popup($states, 'mail_state', $mailstate,'onchange="setSuburbValueListMail()"');
	
		if (trim($suburb) != ""){
			$suburbs = getSuburbs($state);
			$suburb_popup = popup($suburbs, 'pet_suburb', $suburb,'onchange="setPostcodeValueList()"');

			if (trim($postcode) != ""){
				// preselect postcode
                $postcodes = getPostCodes($state, $suburb);
				$postcode_popup = popup($postcodes, 'pet_postcode', $postcode);
			}
		}
	}

	// // fill suburbs
	// if (isset($_GET['hello_from_ajax1'])) {
	// 	if ( empty($_GET['pet_state']) ) {
	// 		$suburb_popup = '<select name="pet_suburb" disabled="disabled"></select>';
	// 	} else {
	// 		$suburbs = getSuburbs($_GET['pet_state']);
	// 		$suburb_popup = popup($suburbs, 'pet_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');
	// 	}
	// 	echo $suburb_popup;
	// 	die;
	// }

	// // fill postcodes
	// if (isset($_GET['hello_from_ajax2'])) {
	// 	if ( empty($_GET['pet_suburb']) ) {
	// 		$postcode_popup = '<select name="pet_postcode" disabled="disabled"></select>';
	// 	} else {
	// 		$postcodes = getPostCodes($_GET['pet_state'], $_GET['pet_suburb']);
	// 		if (count($postcodes) == 1){
	// 			$selected_postcode = $postcodes[0];
	// 		}
	// 		$postcode_popup = popup($postcodes, 'pet_postcode', $selected_postcode);
	// 	}
	// 	echo $postcode_popup;
	// 	die;
	// }

	// default values
	if (empty($_POST['pet_state'])) {
		$selected_state = '';
	} else {
		$selected_state = $_POST['pet_state'];
	}
	if (empty($_POST['pet_suburb'])) {
		$selected_suburb = '';
	} else {
		$selected_suburb = $_POST['pet_suburb'];
	}
	if (empty($_POST['pet_postcode'])) {
		$selected_postcode = '';
	} else {
		$selected_postcode = $_POST['pet_postcode'];
	}


	// initialise lists on first load - if empty
	if (trim($state) == ''){
		$state_popup = popup($states, 'pet_state', $selected_state,'onchange="setSuburbValueList()"');
	}
	if (trim($suburb) == ''){
		$suburb_popup = '<select name="pet_suburb" disabled="disabled"></select>';
	}
	if (trim($postcode) == ''){
		$postcode_popup = '<select name="pet_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 type="text/javascript">
	// handler to fill suburbs
	function setSuburbValueList(){
		var state_popup = document.forms[0].elements['pet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['pet_suburb'];
		var postcode_popup = document.forms[0].elements['pet_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 = 'pets_detail.php?hello_from_ajax1=true&pet_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['pet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['pet_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['pet_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'pets_detail.php?hello_from_ajax2=true&pet_suburb='+selected_suburb+'&pet_state='+selected_state;
		var target = 'postcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	function validateForm(myform) {
		var error1 = 'Please complete the following mandatory field(s):\n';
		var mandatory_err = 0;

		// check mandatory fields
		// pet_name, pet_desexed, pet_suburb, pet_state, pet_postcode
		if (trim(myform.pet_name.value) == ''){
			myform.pet_name.value = '';
			error1 = error1 + '\n- Pet\'s Name';
			mandatory_err = 1;
		}
		if (myform.pet_state.selectedIndex == 0){
			error1 = error1 + '\n- State';
			mandatory_err = 1;
		}
		if (myform.pet_suburb.selectedIndex == 0){
			error1 = error1 + '\n- Suburb';
			mandatory_err = 1;
		}
		if (myform.pet_postcode.selectedIndex == 0){
			error1 = error1 + '\n- Postcode';
			mandatory_err = 1;
		}

		if (mandatory_err != 0){
			alert(error1);
			return false;
		}

		return true;
	}

</script>

<style>
.instructions{display:block}
.instructions *{
  display:block;
  height:1px;
  overflow:hidden;
  font-size:.01em;
  background:#CC99FF}
.instructions1{
  margin-left:3px;
  margin-right:3px;
  padding-left:1px;
  padding-right:1px;
  border-left:1px solid #e9d3ff;
  border-right:1px solid #e9d3ff;
  background:#d8b2ff}
.instructions2{
  margin-left:1px;
  margin-right:1px;
  padding-right:1px;
  padding-left:1px;
  border-left:1px solid #f9f4ff;
  border-right:1px solid #f9f4ff;
  background:#d5acff}
.instructions3{
  margin-left:1px;
  margin-right:1px;
  border-left:1px solid #d5acff;
  border-right:1px solid #d5acff;}
.instructions4{
  border-left:1px solid #e9d3ff;
  border-right:1px solid #e9d3ff}
.instructions5{
  border-left:1px solid #d8b2ff;
  border-right:1px solid #d8b2ff}
.instructionsfg{
  background:#CC99FF;
  padding: 3px;}
  
.table-form tr td{
    padding:2px;
    box-sizing: border-box;
    height: 25px;
    vertical-align: middle;
}

.table-form tr td:first-child{
    padding:2px;
    width: 190px;
}

#petaddr{
margin-top: 10px;
}
</style>

</head>

<?php

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

<td valign="top">

<?php

	echo '<br/><h2 class="purpleheading">Change Pet Details</h2><br/>';

?>

<form action="pets_detail_update.php" method="post" name="frmPet" id="frmPet">
<table border="0" width="100%" cellspacing="0" cellpading="0" class="table-form">
	<tr>
		<td valign="top" class="boldtext">Microchip No:</td>
		<td valign="top"><?php echo $microchip; ?></td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Microchip No (2):</td>
		<td valign="top"><?php echo $microchip2; ?></td>
	</tr>
	<tr>
		<td valign="top" nowrap="nowrap" class="boldtext">Petsafe Collar Tag No:</td>
		<td valign="top"><?php echo $petsafetag; ?></td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Clinic ID / Name:</td>
		<td valign="top">
			<?php echo $accountnumber . ': ' . $clinicname; ?>
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext"><span style="color:red"><sup>*</sup></span> Pet's Name</td>
		<td valign="top">
			<input type="text" size="20" value="<?php echo $petname; ?>" name="pet_name" />
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Species</td>
		<td valign="top">
			<?php echo $species; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Colour</td>
		<td valign="top">
			<?php echo $colour; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Breed</td>
		<td valign="top">
			<?php echo $breed; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">DOB</td>
		<td valign="top">
			<?php echo fReformatDate($dob); ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Sex</td>
		<td valign="top">
			<?php echo $sex; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Desexed</td>
		<td valign="top">
			<input type="radio" name="pet_desexed" value="Yes" <?php if (strtoupper($desexed) == "YES") echo 'checked="checked"'; ?> />Yes
			<input type="radio" name="pet_desexed" value="No" <?php if (strtoupper($desexed) != "YES") echo 'checked="checked"'; ?> />No
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Savage Status</td>
		<td valign="top">
			<?php echo $savage; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Breeder ID</td>
		<td valign="top">
			<?php echo $BreederID; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Implant Date</td>
		<td valign="top">
			<?php echo fReformatDate($ImplantDate); ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td valign="top" class="boldtext">Distinguishing Marks</td>
		<td valign="top">
			<?php echo $DistinguishingMarks; ?>&nbsp;
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="match_petaddr" value="1" <?php echo $fmcPet['fieldData']['Address Same As Owner'] == 'Yes' ? 'checked' : ''; ?> onclick="if (this.checked){document.getElementById('petaddr').style.display = 'none'; document.getElementById('petaddr').style.visibility = 'hidden'; } else { document.getElementById('petaddr').style.display = ''; document.getElementById('petaddr').style.visibility = 'visible'; }" /> Pet's address same as Owner's</td>
    </tr>
	<tr>
		<td colspan="2" style="padding:0;">
			<div id="petaddr" name="petaddr" <?php echo $fmcPet['fieldData']['Address Same As Owner'] == 'Yes' ? 'style="display: none;"' : ''; ?>>
			<table width="100%" border="0" cellpading="0" cellspacing="0">
				<tr>
					<td class="boldtext">Street Address</td>
					<td valign="top">
						Unit/Street No &nbsp;&nbsp;Street Name<br/>
						<input type="text" size="30" value="<?php echo $street; ?>" name="pet_address" />
					</td>
				</tr>
				<tr>
					<td valign="top" class="boldtext"><span style="color:red"><sup>*</sup></span> State</td>
					<td valign="top">
						<?php echo $state_popup ?>
                    </td>
				</tr>
				<tr>
					<td valign="top" class="boldtext"><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" class="boldtext"><span style="color:red"><sup>*</sup></span> Postcode</td>
					<td valign="top">
						<div id="postcode_container"><?php echo $postcode_popup ?></div>
                    </td>
				</tr>
			</table>
			</div>
		</td>
	</tr>
	<tr>
		<td valign="top" colspan="2">
			<input type="hidden" name="petid" value="<?php echo $petid; ?>" />
			<br/><input type="submit" value="Update Pet Details" class="button" onclick="javascript: if(!validateForm(this.form)) return false;" />
			<input type="button" value="Cancel" class="button" onclick="javascript: window.location.href = 'pets.php';" />
		</td>
	</tr>
</table>
</form>

<br/><br/>

</td>

<td valign="top">

<br/><br/>

<div style="width: 400px;">
  <b class="instructions">
  <b class="instructions1"><b></b></b>
  <b class="instructions2"><b></b></b>
  <b class="instructions3"></b>
  <b class="instructions4"></b>
  <b class="instructions5"></b></b>

  <div class="instructionsfg">
    <?php echo html_entity_decode($extraInfo) . '<br />'; ?>
	<div style="position:relative;left:-73px;"><img src="<?php echo $gaPage['root_directory']; ?>/images/dog_ball_sm.png" /></div>
  </div>

  <b class="instructions">
  <b class="instructions5"></b>
  <b class="instructions4"></b>
  <b class="instructions3"></b>
  <b class="instructions2"><b></b></b>
  <b class="instructions1"><b></b></b></b>
</div>

</td>

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

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

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