<?php

	/***********************************************************************************
	*   Filename    : indexsearchresults.php
	*   Description : Petsafe Search Results from Index page
	*
	*   Date        Modification By      Description
	*   25/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 - Microchip Results';
	$gaPage['root_directory'] = '..';

	/********************* Page Defaults *********************/
	fDefaultParameter('searchtype', $_POST, 'chip');
	fDefaultParameter('searchtype', $_GET, '');
	fDefaultParameter('query', $_POST, '');
	fDefaultParameter('query1', $_POST, '');
	fDefaultParameter('query2', $_POST, '');
	fDefaultParameter('query3', $_POST, '');
	fDefaultParameter('query4', $_POST, '');
	fDefaultParameter('query5', $_POST, '');
	fDefaultParameter('query6', $_POST, '');
	fDefaultParameter('query7', $_POST, '');
	fDefaultParameter('query8', $_POST, '');
	fDefaultParameter('query9', $_POST, '');
	fDefaultParameter('query10', $_POST, '');
	fDefaultParameter('query11', $_POST, '');
	fDefaultParameter('query12', $_POST, '');
	fDefaultParameter('query13', $_POST, '');
	fDefaultParameter('query14', $_POST, '');
	fDefaultParameter('query15', $_POST, '');
	fDefaultParameter('err_code', $_GET, '');
	fDefaultParameter('getquery', $_GET, '');

	/********************* Page Functions *********************/
	
	// default - when submitted from index
	$getQueryValue = $_POST['query'];
	$getSearchType = $_GET['searchtype'];
	if ($getSearchType == '') {
		$getSearchType = $_POST['searchtype'];
	}

    //Unknown if this next block is used
	if ($_POST['query'] == '') {
		// if JS doesnt work
	    $getQueryValue = $_POST['query1'] . $_POST['query2'] . $_POST['query3'] . $_POST['query4'] . $_POST['query5'] . 
			$_POST['query6'] . $_POST['query7'] . $_POST['query8'] . $_POST['query9'] . $_POST['query10'] . 
			$_POST['query11'] . $_POST['query12'] . $_POST['query13'] . $_POST['query14'] . $_POST['query15'];
	}

	if ($_GET['getquery'] != '') {
		// after logging in
	    $getQueryValue = $_GET['getquery'];
	}

	// If Search type is chip, check a valid chip has been entered for search
	if($getSearchType == "chip" && $getQueryValue != '' && ( !( strlen($getQueryValue) == 15 && is_numeric($getQueryValue) ) && !( strlen($getQueryValue) == 10 && ctype_alnum($getQueryValue))) ){
        //15 digit numeric or older-style 10 digit alphanumeric
		fRedirect('index.php?err_code=InvalidChip#chipsearch');
		fCleanup();
	}
	
	
	// If Search type is tag, check a valid tag has been entered for search
	if(	$getSearchType == "tag" && $getQueryValue != '' && strlen($getQueryValue) != 6 ){
		fRedirect('index.php?err_code=InvalidTag#tagsearch');
		fCleanup();
	}
	
	
    /************ Fetch details from FileMaker when posted ************/


	// ADD TO LOG: search action
	if ($_SESSION['LoggedIn'] == 1){
		// if vet and NOT allowed to search, then throw off.
		if ($_SESSION['VetID'] != '' and strtoupper($_SESSION['VetAllowSearch']) != 'YES') {
			fRedirect('index.php?err_code=NotAuthorised#chipsearch');
			fCleanup();
		}

		if ($_SESSION['MemberID'] != ''){
			$aInsert['_sk_member_id'] = $_SESSION['MemberID'];
		} else {
			$aInsert['_sk_vet_id'] = $_SESSION['VetID'];
		}
			
		if ($getSearchType == 'chip'){
			$aInsert['description'] = 'Searched for Chip: ' . $getQueryValue;
			$aInsert['_sk_chip_no'] = $getQueryValue;
		} else {
			$aInsert['description'] = 'Searched for Tag: ' . $getQueryValue;
			$aInsert['_sk_tag_no'] = $getQueryValue;
		}
			
		$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
			
		$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
	}
		
	if ($getSearchType == 'chip'){

		// search microchips
		$aRequest = array();
		$aRequest['Chip No'] = '="' . $getQueryValue . '"';


		$fmrMicrochip = fFMPerformFind('petsafe', 'All Fields - Chips', $aRequest);

		//Check for not found or duplicate
		if ($fmrMicrochip === FALSE || $fmrMicrochip["messages"]["0"]["code"] == "401") {
			// Redirect
		    fRedirect('index.php?err_code=PetAddress#chipsearch');
			fCleanup();
		} else if ($fmrMicrochip["response"]["dataInfo"]["foundCount"] > 1) {
			// Redirect
			fRedirect('index.php?err_code=MicrochipDuplicate#chipsearch');
			fCleanup();
		} else {
		    // check if user is logged in
		    if ($_SESSION['LoggedIn'] == 0){
            	// Redirect if not logged in
            	fRedirect('indexsearchlogin.php?getquery=' . $getQueryValue . '&searchtype=' . $getSearchType);
            	fCleanup();
        	}
        	
			// found chip
			$fmcMicrochip = $fmrMicrochip["response"]["data"][0]["fieldData"];

			// Store all details into $microchip array
			$microchip['Chip'] = array();
			$microchip['Chip']['ID'] = $fmcMicrochip['_pk_chip_id'];
			$microchip['Chip']['Number'] = $fmcMicrochip['Chip No'];
			$microchip['Chip']['PetName'] = '';
			$microchip['Chip']['PetType'] = '';
			$microchip['Chip']['PetBreed'] = '';
			$microchip['Chip']['PetColour'] = '';
			$microchip['Chip']['PetSex'] = '';
			$microchip['Chip']['PetDOB'] = '';
			$microchip['Chip']['PetSavage'] = '';
			
			$microchip['Chip']['BreederID'] = '';
			$microchip['Chip']['DistinguishingMarks'] = '';
			$microchip['Chip']['ImplantDate'] = $fmcMicrochip['implanted_date'];
			$microchip['Chip']['CreateDate'] = $fmcMicrochip['c_Pet_Initial_Registration'];

			$microchip['Chip']['Pet'] = $fmcMicrochip['_sk_pet_id'];
			$microchip['Chip']['PetTag'] = '';
			$microchip['Chip']['MemberID'] = '';
			$microchip['Chip']['OwnerName'] = '';
			$microchip['Chip']['OwnerEmail'] = '';
			$microchip['Chip']['OwnerSuburb'] = '';
			$microchip['Chip']['OwnerHP'] = '';
			$microchip['Chip']['OwnerWP'] = '';
			$microchip['Chip']['OwnerMP'] = '';
			$microchip['Chip']['OwnerAltA'] = '';
			$microchip['Chip']['OwnerAltB'] = '';

			/******** If PetID, then search for its collar tag no. ********/
			if ($microchip['Chip']['Pet'] != '') {
				$aRequest = array();
				$aRequest['_pk_pet_id'] = '="' . $microchip['Chip']['Pet'] . '"';

				$fmrPetTag = fFMPerformFind('petsafe', 'All Fields - Pets', $aRequest);

				/************ Check for not found or duplicate ************/
				if ($fmrPetTag === FALSE || $fmrPetTag["response"]["dataInfo"]["foundCount"] != 1)
				{
					// Redirect if chip found but not linked to pet
					fRedirect('index.php?err_code=PetNotFound#chipsearch');
					fCleanup();
				}
				else if ($fmrPetTag["response"]["dataInfo"]["foundCount"] > 1)
				{
					// Redirect if chip found on more than 1 pet
					fRedirect('index.php?err_code=PetDuplicate#chipsearch');
					fCleanup();
				}

				$fmcPetTag = $fmrPetTag["response"]["data"][0]["fieldData"];

				// Store the Pet Tag No. into $microchip array
				$microchip['Chip']['PetTag'] = $fmcPetTag['Tag'];
				$microchip['Chip']['MemberID'] = $fmcPetTag['_sk_member_id'];
				$microchip['Chip']['PetName'] = $fmcPetTag['Name'];
				$microchip['Chip']['PetType'] = $fmcPetTag['Type'];
				$microchip['Chip']['PetSex'] = $fmcPetTag['Sex'];
				$microchip['Chip']['PetDesexed'] = $fmcPetTag['Desexed'];
				$microchip['Chip']['PetDOB'] = $fmcPetTag['DOB'];
				$microchip['Chip']['PetBreed'] = $fmcPetTag['Breed'];
				$microchip['Chip']['PetColour'] = $fmcPetTag['Colour'];
				$microchip['Chip']['PetSavage'] = $fmcPetTag['Savage'];

				$microchip['Chip']['BreederID'] = $fmcPetTag['Breeder ID'];
				$microchip['Chip']['DistinguishingMarks'] = $fmcPetTag['Distinguishing Marks'];
				

				// if owner, then proceed only if owner/member is linked to the pet found
				if ($_SESSION['MemberID'] != '' and $fmcPetTag['_sk_member_id'] != $_SESSION['MemberID']){
					// user is a member but not linked to the pet
					fRedirect('index.php?err_code=NotAuthorised#chipsearch');
					fCleanup();
				}

				/******** If MemberID, then search for its Owner ********/
				if ($microchip['Chip']['MemberID'] != '') {

						$aRequest = array();
						$aRequest['_pk_member_id'] = '="' . $microchip['Chip']['MemberID'] . '"';

						$fmrOwner = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);

						$fmcOwner = $fmrOwner["response"]["data"][0]["fieldData"];

						// Store the Owner details into $microchip array
						$microchip['Chip']['OwnerName'] = $fmcOwner['Title'] . ' ' . $fmcOwner['Given Name'] . ' ' . $fmcOwner['Last Name'];
						$microchip['Chip']['OwnerEmail'] = $fmcOwner['Email'];
						$microchip['Chip']['OwnerSuburb'] = $fmcOwner['Suburb'];
						$microchip['Chip']['OwnerState'] = $fmcOwner['State'];
						$microchip['Chip']['OwnerHP'] = $fmcOwner['Home Phone'];
						$microchip['Chip']['OwnerWP'] = $fmcOwner['Work Phone'];
						$microchip['Chip']['OwnerMP'] = $fmcOwner['Mobile'];
						$microchip['Chip']['OwnerAltA'] = $fmcOwner['Alt Person A'] . ' / ' . $fmcOwner['Phone A'];
						$microchip['Chip']['OwnerAltB'] = $fmcOwner['Alt Person B'] . ' / ' . $fmcOwner['Phone B'];
					}

			} 
			else {
					// Redirect if chip found but no linked pet found
					fRedirect('index.php?err_code=PetNotFound#chipsearch');
					fCleanup();
			}

			// Store output results into common variable
			$showChipID = $microchip['Chip']['ID'];
			$showChipNumber = $microchip['Chip']['Number'];
			//$showChipRegister = $microchip['Chip']['Register'];
			$showPetTag = $microchip['Chip']['PetTag'];
			$showOwnerID = $microchip['Chip']['MemberID'];
			$showOwnerName = $microchip['Chip']['OwnerName'];
			$showOwnerEmail = $microchip['Chip']['OwnerEmail'];
			$showOwnerSuburb = $microchip['Chip']['OwnerSuburb'];
			$showOwnerState = $microchip['Chip']['OwnerState'];
			$showOwnerHP = $microchip['Chip']['OwnerHP'];
			$showOwnerWP = $microchip['Chip']['OwnerWP'];
			$showOwnerMP = $microchip['Chip']['OwnerMP'];
			$showOwnerAltA = $microchip['Chip']['OwnerAltA'];
			$showOwnerAltB = $microchip['Chip']['OwnerAltB'];
			$showPetName = $microchip['Chip']['PetName'];
			$showPetType = $microchip['Chip']['PetType'];
			$showPetSex = $microchip['Chip']['PetSex'];
			$showPetDesexed = $microchip['Chip']['PetDesexed'];
			$showPetDOB = $microchip['Chip']['PetDOB'];
			$showPetBreed = $microchip['Chip']['PetBreed'];
			$showPetColour = $microchip['Chip']['PetColour'];
			$showPetSavage = $microchip['Chip']['PetSavage'];

			$showPetBreederID = $microchip['Chip']['BreederID'];
			$showPetDistinguishingMarks = $microchip['Chip']['DistinguishingMarks'];
			$showPetImplantDate = $microchip['Chip']['ImplantDate'];
			$showCreateDate = $microchip['Chip']['CreateDate'];
		}

	} 
	else {
		// search Tags
		$aRequest = array();
		$aRequest['Tag'] = '="' . $getQueryValue . '"';

		$fmrPetTag = fFMPerformFind('petsafe', 'All Fields - Pets', $aRequest);

		if ($fmrPetTag === FALSE || $fmrPetTag["messages"]["0"]["code"] == "401"){
			// tag not found
			fRedirect('index.php?err_code=TagNotFound#chipsearch');
			fCleanup();
		}
		else {
			// check if user is logged in
			if ($_SESSION['LoggedIn'] == 0){
				// Redirect if not logged in
				fRedirect('indexsearchlogin.php?getquery=' . $getQueryValue . '&searchtype=' . $getSearchType);
				fCleanup();
			}

			// get result - Tag found
			$fmcPetTag = $fmrPetTag["response"]["data"][0]["fieldData"];

			// if owner, then proceed only if owner/member is linked to the pet found
			if ($_SESSION['MemberID'] != '' and $fmcPetTag['_sk_member_id'] != $_SESSION['MemberID']){
				// user is a member but not linked to the pet
				fRedirect('index.php?err_code=NotAuthorised#chipsearch');
				fCleanup();
			}

			// Store all details into $microchip array
			$microchip['Chip'] = array();
			$microchip['Chip']['ID'] = '';
			$microchip['Chip']['Number'] = '';
			$microchip['Chip']['PetName'] = $fmcPetTag['Name'];
			$microchip['Chip']['PetType'] = $fmcPetTag['Type'];
			$microchip['Chip']['PetBreed'] = $fmcPetTag['Breed'];
			$microchip['Chip']['PetColour'] = $fmcPetTag['Colour'];
			$microchip['Chip']['PetSavage'] = $fmcPetTag['Savage'];
			$microchip['Chip']['PetDOB'] = $fmcPetTag['DOB'];
			$microchip['Chip']['PetSex'] = $fmcPetTag['Sex'];
			$microchip['Chip']['PetDesexed'] = $fmcPetTag['Desexed'];
			
			$microchip['Chip']['BreederID'] = $fmcPetTag['Breeder ID'];
			$microchip['Chip']['DistinguishingMarks'] = $fmcPetTag['Distinguishing Marks'];
			$microchip['Chip']['ImplantDate'] = $fmcPetTag['Implant Date'];
			
			$microchip['Chip']['Pet'] = $fmcPetTag['_pk_pet_id'];
			$microchip['Chip']['PetTag'] = $fmcPetTag['Tag'];
			$microchip['Chip']['MemberID'] = $fmcPetTag['_sk_member_id'];
			$microchip['Chip']['OwnerName'] = '';
			$microchip['Chip']['OwnerEmail'] = '';
			$microchip['Chip']['OwnerSuburb'] = '';
			$microchip['Chip']['OwnerHP'] = '';
			$microchip['Chip']['OwnerWP'] = '';
			$microchip['Chip']['OwnerMP'] = '';
			$microchip['Chip']['OwnerAltA'] = '';
			$microchip['Chip']['OwnerAltB'] = '';

			/******** If PetID is linked, then search for its chip no. ********/
			if ($microchip['Chip']['Pet'] != '') {
				$aRequest = array();
				$aRequest['_sk_pet_id'] = '="' . $microchip['Chip']['Pet'] . '"';

				$fmrChip = fFMPerformFind('petsafe', 'All Fields - Chips', $aRequest);

				/************ Check for not found or duplicate ************/
	//			if ($fmrChip === FALSE || $fmrChip["response"]["dataInfo"]["foundCount"] != 1)
            	if ($fmrChip === FALSE || $fmrChip["messages"]["0"]["code"] == "401")  
				{
					// Redirect if tag found but linked chip not found
					fRedirect('index.php?err_code=ChipNotFound#chipsearch');
					fCleanup();
				}

				$fmcChip = $fmrChip["response"]["data"][0]["fieldData"];

				// Store the Chip No. into $microchip array
				$microchip['Chip']['ID'] = $fmcChip['_pk_chip_id'];
				$microchip['Chip']['Number'] = $fmcChip['Chip No'];

			}

			/******** If MemberID is linked, then search for its Owner ********/
			if ($microchip['Chip']['MemberID'] != '') {
				$aRequest = array();
				$aRequest['_pk_member_id'] = '="' . $microchip['Chip']['MemberID'] . '"';

				$fmrOwner = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);

				$fmcOwner = $fmrOwner["response"]["data"][0]["fieldData"];

				// Store the Owner details into $microchip array
				$microchip['Chip']['OwnerName'] = $fmcOwner['Title'] . ' ' . $fmcOwner['Given Name'] . ' ' . $fmcOwner['Last Name'];
				$microchip['Chip']['OwnerEmail'] = $fmcOwner['Email'];
				$microchip['Chip']['OwnerSuburb'] = $fmcOwner['Suburb'];
				$microchip['Chip']['OwnerState'] = $fmcOwner['State'];
				$microchip['Chip']['OwnerHP'] = $fmcOwner['Home Phone'];
				$microchip['Chip']['OwnerWP'] = $fmcOwner['Work Phone'];
				$microchip['Chip']['OwnerMP'] = $fmcOwner['Mobile'];
				$microchip['Chip']['OwnerAltA'] = $fmcOwner['Alt Person A'] . ' / ' . $fmcOwner['Phone A'];
				$microchip['Chip']['OwnerAltB'] = $fmcOwner['Alt Person B'] . ' / ' . $fmcOwner['Phone B'];

			}

			// Store output results into common variable
			$showChipID = $microchip['Chip']['ID'];
			$showChipNumber = $microchip['Chip']['Number'];
			$showPetTag = $microchip['Chip']['PetTag'];
			$showOwnerID = $microchip['Chip']['MemberID'];
			$showOwnerName = $microchip['Chip']['OwnerName'];
			$showOwnerEmail = $microchip['Chip']['OwnerEmail'];
			$showOwnerSuburb = $microchip['Chip']['OwnerSuburb'];
			$showOwnerState = $microchip['Chip']['OwnerState'];
			$showOwnerHP = $microchip['Chip']['OwnerHP'];
			$showOwnerWP = $microchip['Chip']['OwnerWP'];
			$showOwnerMP = $microchip['Chip']['OwnerMP'];
			$showOwnerAltA = $microchip['Chip']['OwnerAltA'];
			$showOwnerAltB = $microchip['Chip']['OwnerAltB'];
			$showPetName = $microchip['Chip']['PetName'];
			$showPetType = $microchip['Chip']['PetType'];
			$showPetSex = $microchip['Chip']['PetSex'];
			$showPetDOB = $microchip['Chip']['PetDOB'];
			$showPetBreed = $microchip['Chip']['PetBreed'];
			$showPetDesexed = $microchip['Chip']['PetDesexed'];
			$showPetColour = $microchip['Chip']['PetColour'];
			$showPetColour = $microchip['Chip']['PetSavage'];

			$showPetBreederID = $microchip['Chip']['BreederID'];
			$showPetDistinguishingMarks = $microchip['Chip']['DistinguishingMarks'];
			$showPetImplantDate = $microchip['Chip']['ImplantDate'];
			$showCreateDate = $microchip['Chip']['CreateDate'];

			}
	}

?>
<!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'; ?>

<style>
    .results-table{
        border: 1px solid #999;
        border-radius:2px
    }
    
    .results-table tr:first-child td{
        padding: 5px;
    }
    
    .separator{
		height:4px;	
	}
	
	.table-header td{
		font-size:15px;
	}
</style>
</head>

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

<td>

<br/><h2 class="greenheading">Microchip / PetSafe Tag Results</h2>

<!--- Table template --->
<br />
<table width="100%" border="0" cellspacing="1" style=";" cellpadding="5" class="results-table">
  <tr class="table-header">
    <td><b>Microchip No</b></td>
    <td><b>Pet Details</b></td>
    <td><b>Petsafe Collar Tag</b></td>
    <td><b>Owner Details</b></td>
    <td><b>Alternate Contacts (Name/Phone)</b></td>
  </tr>
  <tr>
    <td colspan="5">&nbsp;</td>
  </tr>

<?php
		if ($_SESSION['VetID'] != '' and $_SESSION['vetState'] != 'VIC' and $showOwnerState == 'VIC' ){
		        /********************* Suppress the details *********************/
	        	$sep = '<div class="separator"></div>';
                echo '<tr><td valign="top">' . $showChipNumber . '</td>';
                echo '<td valign="top" style="width:200px;">Victorian Registration - Contact Petsafe</td></td></td></td>';
		} else {
		
		
        /********************* Output the details *********************/
		$sep = '<div class="separator"></div>';
        echo '<tr><td valign="top">' . $showChipNumber . '<br/><br/>' .
			 $sep .'<b>Created:</b><br/>' .
			 $sep . fReformatDate($showCreateDate) . '</td>';
        echo '<td valign="top" style="width:200px;"><b>Name:</b> ' . strtoupper($showPetName) . 
            $sep .'<b>Type / Breed:</b> ' . $showPetType . ' / ' . $showPetBreed . 
            $sep . '<b>Colour:</b> ' . $showPetColour . 
            $sep . '<b>Sex:</b> ' . $showPetSex .
            $sep . '<b>Desexed:</b> ' . $showPetDesexed . 
            $sep . '<b>DOB:</b> ' . $showPetDOB . 
            $sep . '<b>Savage Status:</b> ' . $showPetSavage . 
            $sep . '<b>Breeder ID:</b> ' . $showPetBreederID . 
            $sep . '<b>Implant Date:</b> ' . fReformatDate($showPetImplantDate) . 
            $sep . '<b>Distinguishing Marks:</b> ' . $showPetDistinguishingMarks .'</td>';

        echo '<td valign="top">' . $showPetTag . '</td>';
        echo '<td valign="top"><b>Member ID:</b> ' . strtoupper($showOwnerID) . $sep . '<b>Name:</b> ' . strtoupper($showOwnerName) . $sep . '<b>Suburb:</b> ' . $showOwnerSuburb .  $sep . '<b>Tel (H):</b> ' . $showOwnerHP .  $sep . '<b>Tel (W):</b> ' . $showOwnerWP . $sep . '<b>Mobile:</b> ' . $showOwnerMP . $sep . '<b>Email:</b> <a href="mailto:' . $showOwnerEmail . '">' . $showOwnerEmail . '</a></td>';
        echo '<td valign="top"><b>Contact 1:</b> ' . $showOwnerAltA . $sep . '<b>Contact 2:</b> ' . $showOwnerAltB . '</td>';
		}
        echo '</tr></table>';

		if ($_SESSION['IsAdminLogin'] == 1)
		{
			echo '<br/>';
			echo '<form name="frmInvoices" action="chip_owner_change.php" method="POST">';
			echo '<input type="hidden" name="chip_id"; value="'.$showChipID.'">';
			echo '<input type="submit" name="changeOwner" value=" Change Owner / Details" />';
			echo '</form>';
		}
?>

<br/><br/>
</td>

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

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

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