<?php
	/***********************************************************************************
	*   Filename    : pets_certificate.php
	*   Description : Collects required information to generate the certificate
	*
	*   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
	*   30/07/2025  John Muffett         Reworked for oData API
	*
	*   Copyright Keysoft Pty Ltd 2025
	***********************************************************************************/

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

    /********************* Page Defaults *********************/
	fDefaultParameter('petid', $_POST, '');
	fDefaultParameter('mid', $_POST, '');
	fDefaultParameter('email', $_POST, '');

	$petid = $_POST['petid'];
	$memberid = $_POST['mid'];
	$email = $_POST['email'];

	// accept valid input
	if (trim($petid) == '' or trim($memberid) == ''){
		// Redirect
		fRedirect('index.php');
		fCleanup();
	}
    /*************************** Page Functions ***********************/

    function getMemberById($memberid){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => '_pk_member_id eq '. $memberid ,
            'count' => true
        ]);
        $response = $fm->get('Owners', $odataQuery ,$allPages = true );
   
        // Check for not found
        if (!$response['success'] || $response["data"]['count'] < 1)
        {
			var_dump($response);
			die;
        }
        return $response['data']['value'][0];
    }

    function getPetById($petid,$memberid){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => '_pk_pet_id eq '.(int) $petid.' and _sk_member_id eq '. (int) $memberid,
		 	//'filter' => '_pk_pet_id eq '. $petid,
			'select' => ['Name','Type','Colour','Breed','DOB','Sex','Desexed','Savage','breederID','distinguishingMarks','Tag',
							'displayStreet','displaySuburb','displayState','displayPostcode','council'
						],
            'count' => true
        ]);

        $response = $fm->get('Pets', $odataQuery  );

        // Check for not found
        if (!$response['success'] || $response["data"]['count'] < 1)
        {
			var_dump($response);
			die;
        }
	
        return $response['data']['value'][0];
    }

    function getChipById($petid){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
            'filter' => "_sk_pet_id eq ".$petid,
           // 'select' => ['articleName','articleContent'],
			'order' => 'implanted_date desc',
            'count' => true
        ]);
        $response = $fm->get('Chips', $odataQuery ,$allPages = true );

        // Check for not found
        if (!$response['success'] || $response["data"]['count'] < 1)
        {
			var_dump($response);
			die;
        }
        return $response;
    }

    /*************************** Page Start ***************************/

	/****************** Fetch Member details if logged in ******************/
	
		$fmcOwner = getMemberById($memberid);
		// get fields

		$owner_id = $fmcOwner['_pk_member_id'];
		$owner_title = $fmcOwner['Title'];
		$owner_firstname = $fmcOwner['Given Name'];
		$owner_lastname = $fmcOwner['Last Name'];
		$owner_homephone = $fmcOwner['Home Phone'];
		$owner_workphone = $fmcOwner['Work Phone'];
		$owner_mobilephone = $fmcOwner['Mobile'];
		$owner_email = 	$fmcOwner['Email'];
		$owner_password = $fmcOwner['Password'];
		$owner_altperson1 = $fmcOwner['Alt Person A'];
		$owner_altphone1 = $fmcOwner['Phone A'];
		$owner_altperson2 = $fmcOwner['Alt Person B'];
		$owner_altphone2 = $fmcOwner['Phone B'];
		$owner_street = $fmcOwner['Street'];
		$owner_suburb = $fmcOwner['Suburb'];
		$owner_state = $fmcOwner['State'];
		$owner_postcode = $fmcOwner['Postcode'];
		$mailstreet = $fmcOwner['Mailing Street'];
		$mailsuburb = $fmcOwner['Mailing Suburb'];
		$mailstate = $fmcOwner['Mailing State'];
		$mailpostcode = $fmcOwner['Mailing Postcode'];
		$mailinglist = $fmcOwner['Mail List'];


	/******************** Retrieve Pet Information ********************/

		$fmcPet = getPetById($petid,$memberid);
		// 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'];
		$petsafetag = $fmcPet['Tag'];
		$street = $fmcPet['displayStreet'];
		$suburb = $fmcPet['displaySuburb'];
		$state = $fmcPet['displayState'];
		$postcode = $fmcPet['displayPostcode'];
		$council = $fmcPet['council'];

	// get associated chip details
//--->>
	//$aRequest = array();
	//$aRequest['_sk_pet_id'] = '="' . $petid . '"';

	//$aSort = array();
	//$Sort[0] = 'implanted_date';

	//$fmrChip = fFMPerformFind('petsafe', 'Web - Chips', $aRequest);
	$fmrChip = getChipById($petid);

	if (!$fmrChip['success'] || $fmrChip["data"]['count'] < 1){

		$microchip = '';
		$microchip2 = '';
		$clinicID = '';
		$clinicname = '';
		$accountnumber = '';
		$vetname = '';
		$vetaddr = '';
		$implantdate = '';
		$clinicaddr = '';

	} else {

		$fmcChip = $fmrChip["data"]['value'][0];

		$microchip = $fmcChip['Chip No'];
		$clinicID = $fmcChip['_sk_implanter_clinic_id'];
		$clinicname = $fmcChip['clinicName'];
		$clinicaddr = $fmcChip['clinicAddress'];
		$implantdate = fReformatDate($fmcChip['implanted_date']);
		$registereddate = fReformatDate($fmcChip['registeredDate']);
		$vetname = $fmcChip['vetName'];
		$vetaddr = $fmcChip['vetAddress'];
		$accountnumber = $fmcChip['clinicAccountNumber'];



		// get 2nd chip, if any
		$fmcChips = $fmrChip["data"]['value'][1];

		$microchip2 = $chip['Chip No'];

		if ($microchip == $microchip2){
			$microchip2 = '';
		}
	}

	/******************** Print Settings ********************/
	$gaPrintDir = fMakeUniqueDir($gaPrintSettings['base_dir']);
	if ($gaPrintDir === false) fReturnError('Unable to create a unique temporary directory to print from.');

	/********************** Start Output Buffering ***********/
	ob_start();
?>

<html>

<head>
	<style>
		.mainheading {
			font-family: Arial;
			font-weight: bold;
			font-size: 25;
		}
		.heading {
			font-family: Arial;
			font-weight: bold;
			font-size: 13;
		}
		p {
			font-family: Arial;
			font-weight: normal;
			font-size: 8;
		}
		td {
			font-family: Arial;
			font-weight: normal;
			font-size: 8;
		}
		.smalltext {
			font-family: Arial;
			font-weight: normal;
			font-size: 7;
		}
		.details {
			font-family: Arial;
			font-weight: bold;
			font-size: 10;
		}
	</style>
</head>

<body>

	<pageheader>
		<table border="0" cellpadding="0" cellspacing="0" colswidth="270,270">

			<tr><td colspan="2"><p class="mainheading">Petsafe<sup>&reg;</sup> Lifetime Registration Certificate</p><br/><br/></td></tr>

			<tr>
				<!-- add breaks above to move picture-->

				<td align="left" valign="middle">
					<!-- add breaks on next line to move address --->

					<p class="details"><br/><br/>

					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

					<?php echo $owner_title . ' ' . $owner_firstname . ' ' . $owner_lastname; ?><br/>

					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

					<?php echo $mailstreet; ?><br/>

					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

					<?php echo $mailsuburb . ' ' . $mailstate . ' ' . $mailpostcode; ?><br/>

					</p>

				</td>

				<td>

					<p><img src="/images/girl_puppy_sm.jpg" align="right" /></p>

				</td>

			</tr>

		</table>
		<br/>
	</pageheader>

	<table border="0" cellspacing="0" cellpadding="0" colswidth="100,170,70,200">

		<tr><td colspan="4"><br/><p>

			Congratulations on registering your pet with the Petsafe National Recovery Network. Your pet's unique microchip number and or a Petsafe 
			Collar Tag are now securely recorded. These number/s are permanently linked on the Petsafe database giving your pet the best chance for 
			a quick return home should he/she stray.<br/><br/>
			This certificate is for your records. You should consider logging onto Petsafe and changing your password and re-printing this certificate. 
			For future access to the Petsafe database you will need your Member ID and password so keep them safe. Add an email address for password recovery.

		</p></td></tr>
		<tr>
			<td colspan="4"><p>&nbsp;</p></td>
		</tr>
		<tr>
			<td colspan="2"><p class="heading">Membership Details</p></td>
			<td colspan="2"><p class="heading">Pet Details</p></td>
		</tr>
		<tr>
			<td><b>Member ID</b></td>
			<td>PS<?php echo $owner_id; ?></td>
			<td><b>Microchip</b></td>
			<td><?php echo $microchip; ?></td>
		</tr>
		<tr>
			<td><b>Password</b></td>
			<td><?php echo $owner_password; ?></td>
			<td><b>Petsafe Tag</b></td>
			<td><?php echo $petsafetag; ?></td>
		</tr>
		<tr>
			<td><b>Owner Name</b></td>
			<td><?php echo $owner_title . ' ' . $owner_firstname . ' ' . $owner_lastname; ?></td>
			<td><b>2nd Microchip</b></td>
			<td><?php echo $microchip2; ?></td>
		</tr>
		<tr>
			<td colspan="4">________________________________________________________________________________________________________________________<br/></td>
		</tr>
		<tr>
			<td><b>Home Tel</b></td>
			<td><?php echo $owner_homephone; ?></td>
			<td><b>Animal Name</b></td>
			<td><?php echo $petname; ?></td>
		</tr>
		<tr>
			<td><b>Work Tel</b></td>
			<td><?php echo $owner_workphone; ?></td>
			<td><b>Species</b></td>
			<td><?php echo $species; ?></td>
		</tr>
		<tr>
			<td><b>Mobile</b></td>
			<td><?php echo $owner_mobilephone; ?></td>
			<td><b>Breed</b></td>
			<td><?php echo $breed; ?></td>
		</tr>
		<tr>
			<td><b>Email</b></td>
			<td><?php echo $owner_email; ?></td>
			<td><b>Colour</b></td>
			<td><?php echo $colour; ?></td>
		</tr>
		<tr>
			<td><b>Alternative Contact</b></td>
			<td><?php echo $owner_altperson1; ?></td>
			<td><b>Sex</b></td>
			<td><?php echo $sex; ?></td>
		</tr>
		<tr>
			<td><b>Alternative Number</b></td>
			<td><?php echo $owner_altphone1; ?></td>
			<td><b>Desexed</b></td>
			<td><?php echo $desexed; ?></td>
		</tr>
		<tr>
			<td nowrap="nowrap"><b>Alternative Contact 2</b></td>
			<td><?php echo $owner_altperson2; ?></td>
			<td><b>D.O.B</b></td>
			<td><?php echo fReformatDate($dob); ?></td>
		</tr>
		<tr>
			<td nowrap="nowrap"><b>Alternative Number 2</b></td>
			<td><?php echo $owner_altphone2; ?></td>
			<td><b>Classification</b></td>
			<td><?php echo $savage; ?></td>
		</tr>
		<tr>
			<td colspan="2">&nbsp;</td>
			<td><b>Council</b></td>
			<td><?php echo $council; ?></td>
		</tr>
		<tr>
			<td nowrap="nowrap"><b>Breeder ID</b></td>
			<td><?php echo $BreederID; ?></td>
			<td><b>Implant Date</b></td>
			<td><?php echo fReformatDate($implantdate); ?></td>
		</tr>
		<tr>
			<td><b>Distinguishing Marks</b></td>
			<td colspan="3"><?php echo $DistinguishingMarks; ?></td>
		</tr>
		<tr>
			<td><b>Member Home Address</b></td>
			<td><?php echo $owner_street . ' ' . $owner_suburb . ' ' . $owner_state . ' ' . $owner_postcode; ?></td>
			<td valign="top"><b>Pet Address</b></td>
			<td><?php echo $street . ' ' . $suburb . ' ' . $state . ' ' . $postcode; ?></td>
		</tr>
		<tr>
			<td colspan="4">________________________________________________________________________________________________________________________<br/></td>
		</tr>
		<tr>
			<td colspan="4"><p class="heading">Vet / Implanter Details</p></td>
		</tr>
		<tr>
			<td><b>Clinic</b></td>
			<td><?php echo $clinicname; ?></td>
			<td><b>Implanter Name</b></td>
			<td><?php echo $vetname;?></td>
		</tr>
		<tr>
			<td valign="top"><b>Address</b></td>
			<td valign="top"><?php echo trim($clinicname) != '' ? $clinicaddr : $vetaddr; ?></td>
			<td valign="top"><b>Date Registered</b></td>
			<td valign="top"><?php echo $registereddate; ?></td>
		</tr>
		<tr>
			<td colspan="4"><p>&nbsp;</p></td>
		</tr>
	</table>

	<table border="0" cellspacing="0" cellpadding="0" colswidth="50,200,90,200">
		<tr>
			<td colspan="2" valign="middle">
				<p><img src="/images/petsafe_com_au_sm.jpg" align="center" /></p>
			</td>
			<td colspan="2">

				<p class="smalltext"><b>Changing Member or Pet Details</b></p>

				<p class="smalltext">To make changes you will need both your Member ID and

				Password.<br/>

				Go to <b>www.petsafe.com.au</b> and select <b>&quot;Member Login&quot;</b><br/>

				<br/><br/>

				<b>Changing Ownership of a Pet</b><br/>

				Transfering ownership of a pet can only be completed by Petsafe staff and only after

				receiving <b>written advice</b> on a Petsafe Form from both the current and new owners.<br/>

				A form can be downloaded from www.petsafe.com.au </p>

			</td>

		</tr>

	</table>

	<pagefooter>
		<table border="0" cellpadding="0" cellspacing="0" colswidth="540">
			<tr>
				<td align="center"><p>&nbsp;</p></td>
			</tr>
		</table>
	</pagefooter>

</body>

</html>

<?php
	require_once '../phpobjects/common/pdf_print.php';

	if($email == true){
		email_pdf_from_buffer('PetsafeCertificate');
	}else{
		generate_pdf_from_buffer('PetsafeCertificate');	
	}

	// Cleanup

	fCleanup();

?>
