<?php

	/***********************************************************************************
	*   Copyright Keysoft Pty Ltd 2009
	***********************************************************************************/

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

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

	/********************* Page Defaults *********************/
	fDefaultParameter('err_code', $_GET, '');
	$cookieid = $_SESSION['cookieid'];

	if ($cookieid == ''){
		// no cookie id - throw to rego page
		fRedirect('register.php?problem=NoCookie');
		fCleanup();
	}

    $fmrTransaction = getTransactionFromCookie($cookieid);

	//invalid cookie id check
	// $aRequest = array();
	// $aRequest['cookie_transaction_id'] = '="' . $cookieid . '"';
	// $fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
	if (!$fmrTransaction['success'] || $fmrTransaction["data"]['count'] < 1){
		// invalid cookie id
		fRedirect('register.php?problem=InvalidCookie');
		fCleanup();

	} else {
		// cookie exists - retrieve info
		$fmcTransaction = $fmrTransaction["data"]["value"];

		// the transaction is already complete!
		$fmcQuickCheck = $fmrTransaction["data"]["value"][0];
		if ($fmcQuickCheck['transaction_finish'] != ''){
			//init cookie in session - no 2nd chance
			$_SESSION['cookieid'] = '';

			// invalid cookie id
			fRedirect('register.php?problem=UsedCookie');
			fCleanup();
		}
	}

?>
<!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>
.vet-clinic-box{
	display:inline-block;
	margin-top:2px;
	font-size:11px;
	font-weight:bold;	
}
</style>
</head>

<?php

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

<td valign="top">

<br/><h2 class="greenheading">New Registration: Payment</h2><br/>

<table class="tbl" width="100%" border="0" cellspacing="0" cellpadding="5">
<tr>
	<td class="tableheader">
        <b>Owner</b>
        <?php
        if ($_SESSION['VetID'] != '' && strtoupper($_SESSION['rego_type']) == 'BREEDER'){?>
            <b> (BREEDER)</b>
        <?php } ?>
    </td>
	<td class="tableheader"><b>Pet Name</b></td>
	<td class="tableheader"><b>Chip No.</b></td>
	<td class="tableheader" align="right"><b>Amount inc GST</b></td>
	<td class="tableheader"><b>Status</b></td>
	<td class="tableheader">&nbsp;</td>
</tr>
<?php

//total amount
$totalAmount = 0;

$rowstyle = '';
$v = '';

//loop records
foreach ($fmcTransaction as $trans_record)
{
	if ($rowstyle == 'tr1_green'){
		$rowstyle = '';
	} else {
		$rowstyle = 'tr1_green';
	}
	$recordid = $trans_record['_pk_record_id'];
	if ($_SESSION['LoggedIn'] != 1){
	//if new user
		$name = $trans_record['owner_first_name'] . ' ' . $trans_record['owner_last_name'];
		$ownername = $trans_record['owner_title'] . ' ' . $trans_record['owner_first_name'] . ' ' . $trans_record['owner_last_name'];
		$address = $trans_record['owner_street'];
		$city = $trans_record['owner_suburb'];
		$state = $trans_record['owner_state'];
		$postcode = $trans_record['owner_postcode'];
		$country = 'AU';
		$phone = $trans_record['owner_home_phone'];
		$email = $trans_record['owner_email'];

		//show in table
		$petname = $trans_record['pet_name'];
		$chipno = $trans_record['microchip_no'];

		// get payment details
		if ($trans_record['payment_required'] == 'Yes'){
			$fm = \Keysoft\FileMaker\Client::getInstance();
			$odataQuery = $fm->buildODataQuery([
				'filter' => "item_code eq 'PSRP'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrPrice = $fm->get('Item_Type', $odataQuery ,$allPages = true );

			// $aRequest = array();
			//$aRequest['pbq_Price_Bracket::item_type'] = '="Registration"';
			//$aRequest['pbq_Price_Bracket::price_bracket'] = '="Premium Customer"';
			//$aSort = array();
			//$aSort[0] = 'qty';
			//$fmrPrice = fFMPerformFind('petsafe', 'WEB - Price_Bracket_Qty', $aRequest, $aSort, null, FALSE);
			// $aRequest['item_code'] = '=="PSRP"';
			// $fmrPrice = fFMPerformFind('petsafe', 'All Fields - Item_Type', $aRequest);
			$fmcPrice = $fmrPrice["data"]["value"][0];
			$price = $fmcPrice['price'];
			
		} else {
			$price = 0;
		}

		$aUpdate = array();
		$aUpdate['transaction_amount'] = $price;
		// $fmrTransactionUpdate = fFMPerformUpdate('petsafe', 'All Fields - Web_Payments', $trans_record['recordId'], $aUpdate);

		$fm = \Keysoft\FileMaker\Client::getInstance();
		$response = $fm->update('Web_Payments', $trans_record['_pk_record_id'], $aUpdate);
		if (!$response['success'])
		{
			// Redirect
			var_dump($response);
			die;
		}

		$price = round($price * 1.1,2);

		$totalAmount = $totalAmount + $price;

		//output to table
		echo '<tr class="' . $rowstyle . '">';
		echo '<td>' . $ownername . '</td>';
		echo '<td>' . $petname . '</td>';
		echo '<td>' . $chipno;
		if ($price == 0) {echo ' (Prepaid)';}
		echo '</td>';
		echo '<td align="right">' . $price . '</td>';
		echo '<td>Waiting</td>';
		echo '<td align="right"><a href="javascript:if(confirm(\'Do you really wish to remove the selected registration? (' . $petname . ')\')){ window.location.href = \'register_remove.php?id=' . $trans_record['_pk_record_id'] . '\';}" class="foot-links">X</a></td>';
		echo '</tr>';

	} else if ($_SESSION['VetID'] != '') {
	//if vet logged in
		// flag to show the 'Pay Later' option, must have a valid company on all records
		$bShowPayLaterOption = true;
		// get vet details
		// $fm = \Keysoft\FileMaker\Client::getInstance();
		// $odataQuery = $fm->buildODataQuery([
		// 	'filter' => "_pk_vet_id eq '".$_SESSION['VetID']."'",
		// 	'select' => ['content'],
		// 	'count' => true
		// ]);
		$fmcVet = getVetByVetID($_SESSION['VetID']);
		// $aRequest = array();
		// $aRequest['_pk_vet_id'] = '="' . $_SESSION['VetID'] . '"';
		// $fmrVet = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest);
		$name = $fmcVet['vet_first_name'] . ' ' . $fmcVet['vet_last_name'];
		$country = 'AU';
		$phone = $fmcVet['vet_phone'];
		$email = $fmcVet['vet_email'];
		$address = $fmcVet['vet_street'];
		$city = $fmcVet['vet_suburb'];
		$state = $fmcVet['vet_state'];
		$postcode =  $fmcVet['vet_postcode'];
		$companyid = $fmcVet['vet_Company_Vet_Relation::_sk_company_id'];

		//show in table
		$ownername = $trans_record['owner_title'] . ' ' . $trans_record['owner_first_name'] . ' ' . $trans_record['owner_last_name'];
		
		$implanting_vet_name = $trans_record['web_payments_Vet::title_full_name_c'];
		$clinic_name = $trans_record['web_payment_Company::company_name_with_myob_no_c'];
		
		$v = trim($trans_record['_sk_vet_id']);
		
		$petname = $trans_record['pet_name'];
		$chipno = $trans_record['microchip_no'];

		$aRequest = array();
		$aRequest['_pk_company_id'] = '="' . $companyid . '"';
		$fmrCompany = fFMPerformFind('petsafe', 'All Fields - Companies', $aRequest);
		$pricebracket = '';

		if ($fmrCompany !== FALSE && $fmrCompany["response"]["dataInfo"]["foundCount"] > 0){
			$fmcCompany = $fmrCompany["response"]["data"][0];
			$pricebracket = $fmcCompany['fieldData']['price_bracket'];
		}
		else
		{
			$bShowPayLaterOption = false;
		}


		// get payment details
		if ($trans_record['payment_required'] != 'Yes'){
			$price = 0;

		} else if ($pricebracket != ''){
			$aRequest = array();
			$aRequest['pbq_Price_Bracket::price_bracket'] = '=="' . $pricebracket . '"';
			$aRequest['pbq_Price_Bracket::item_code'] = '=="PSRV"';
            $aSort[]=["fieldName" => "qty", "sortOrder" => "ascend"];
			$fmrPrice = fFMPerformFind('petsafe', 'WEB - Price_Bracket_Qty', $aRequest, $aSort);
			if ($fmrPrice === FALSE || $fmrPrice["response"]["dataInfo"]["foundCount"] < 1){
				// get default pricing because price bracket not found
				$aRequest = array();
				$aRequest['item_code'] = '=="PSRV"';
				$fmrPrice = fFMPerformFind('petsafe', 'All Fields - Item_Type', $aRequest);
				$fmcPrice = $fmrPrice["response"]["data"][0];
				$price = $fmcPrice['fieldData']['price'];
			} else {
				$fmcPrice = $fmrPrice["response"]["data"][0];
				$price = $fmcPrice['fieldData']['price'];
			}

		} else {
			// get default pricing because price bracket not found
			$aRequest = array();
			$aRequest['item_code'] = '=="PSRV"';
			$fmrPrice = fFMPerformFind('petsafe', 'All Fields - Item_Type', $aRequest);
			$fmcPrice = $fmrPrice["response"]["data"][0];
			$price = $fmcPrice['fieldData']['price'];
		}

		$aUpdate = array();
		$aUpdate['transaction_amount'] = $price;
		$fmrTransactionUpdate = fFMPerformUpdate('petsafe', 'All Fields - Web_Payments', $trans_record['_pk_record_id'], $aUpdate);

		$price = round($price * 1.1,2);

		$totalAmount = $totalAmount + $price;

		//output to table
		echo '<tr class="' . $rowstyle . '">';
		echo '<td>' . $ownername . '<br><span class="vet-clinic-box">' . $implanting_vet_name . ' | ' . $clinic_name . '</span></td>';
		echo '<td>' . $petname . '</td>';
		echo '<td>' . $chipno;
		if ($price == 0) {echo ' (Prepaid)';}
		echo '</td>';
		echo '<td align="right">' . $price . '</td>';
		echo '<td>Waiting</td>';
		echo '<td align="right"><a href="javascript:if(confirm(\'Do you really wish to remove the selected registration? (' . $petname . ')\')){ window.location.href = \'register_remove.php?id=' . $trans_record['_pk_record_id'] . '\';}" class="foot-links">X</a></td>';
		echo '</tr>';

	} else if ($_SESSION['MemberID'] != '') {
	//if member logged in
		$aRequest = array();
		$aRequest['_pk_member_id'] = '="' . $_SESSION['MemberID'] . '"';
		$fmrOwner = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);
		$fmcOwner = $fmrOwner["response"]["data"][0];
		// get member details
		$ownername = $fmcOwner['fieldData']['Title'] . ' ' . $fmcOwner['fieldData']['Given Name'] . ' ' . $fmcOwner['fieldData']['Last Name'];
		$name = $fmcOwner['fieldData']['Given Name'] . ' ' . $fmcOwner['fieldData']['Last Name'];
		$address = $fmcOwner['fieldData']['Street'];
		$city = $fmcOwner['fieldData']['Suburb'];
		$state = $fmcOwner['fieldData']['State'];
		$postcode = $fmcOwner['fieldData']['Postcode'];
		$country = 'AU';
		$phone = $fmcOwner['fieldData']['Home Phone'];
		$email = $fmcOwner['fieldData']['Email'];

		//show in table
		$petname = $trans_record['pet_name'];
		$chipno = $trans_record['microchip_no'];

		// get payment details
		if ($trans_record['payment_required'] == 'Yes'){
			$aRequest = array();
			$aRequest['item_code'] = '=="PSRP"';
			$fmrPrice = fFMPerformFind('petsafe', 'All Fields - Item_Type', $aRequest);
			$fmcPrice = $fmrPrice["response"]["data"][0];
			$price = $fmcPrice['fieldData']['price'];
		} else {
			$price = 0.00;
		}

		$aUpdate = array();
		$aUpdate['transaction_amount'] = $price;
		$fmrTransactionUpdate = fFMPerformUpdate('petsafe', 'All Fields - Web_Payments', $trans_record['_pk_record_id'], $aUpdate);

		$price = round($price * 1.1,2);

		$totalAmount = $totalAmount + $price;

		//output to table
		echo '<tr class="' . $rowstyle . '">';
		echo '<td>' . $ownername . '</td>';
		echo '<td>' . $petname . '</td>';
		echo '<td>' . $chipno;
		if ($price == 0) {echo ' (Prepaid)';}
		echo '</td>';
		echo '<td align="right">' . $price . '</td>';
		echo '<td>Waiting</td>';
		echo '<td align="right"><a href="javascript:if(confirm(\'Do you really wish to remove the selected registration? (' . $petname . ')\')){ window.location.href = \'register_remove.php?id=' . $trans_record['_pk_record_id'] . '\';}" class="foot-links">X</a></td>';
		echo '</tr>';
	}
} // end loop

?>

<tr>
	<td class="tablesummary" colspan="3" align="right"><b>Total</b></td>
	<td class="tablesummary" align="right"><b>$<?php echo formatDecimal($totalAmount); ?></b></td>
	<td class="tablesummary" colspan="2">(GST inc: $<?php echo formatDecimal($totalAmount - $totalAmount/1.1); ?>)</td>
</tr>
</table>

<br/>
<hr/>
<br/>

<table width="100%" border="0">
<tr>
<td valign="top"><form method="post" action="register.php?type=<?php echo $_SESSION['rego_type']; echo ($v != '') ? ('&v=' . $v) : ''; ?>" name="frmAdd"><input type="submit" value="Add Another Pet" /></form></td>

<?php
if ($_SESSION['VetID'] != '' and $totalAmount > 0 and $bShowPayLaterOption == true) {
?>
<td valign="top" align="right">
<form method="GET" name="frmAccount" action="register_later.php">
<input type="hidden" name="id" value="<?php echo $cookieid; ?>"/>
<input type="submit" value="Add to Account / Pay Later"/>
</form>
</td>
<?php
}
?>

<td align="right">
<?php
if ($totalAmount > 0) {
?>
<form method="post" name="frmPayment" action="https://pilot-payflowlink.paypal.com">

<input type="hidden" name="LOGIN" value="PetsafeF"/>
<input type="hidden" name="PARTNER" value="VSA"/>
<input type="hidden" name="DESCRIPTION" value="PetSafe Registration"/>
<input type="hidden" name="AMOUNT" value="<?php echo $totalAmount; ?>"/>
<input type="hidden" name="TYPE" value="S"/>
<input type="hidden" name="NAME" value="<?php echo $name; ?>"/>
<input type="hidden" name="PHONE" value="<?php echo $phone; ?>"/>
<input type="hidden" name="EMAIL" value="<?php echo $email; ?>"/>
<input type="hidden" name="ADDRESS" value="<?php echo $address; ?>"/>
<input type="hidden" name="CITY" value="<?php echo $city; ?>"/>
<input type="hidden" name="ZIP" value="<?php echo $postcode; ?>"/>
<!-- to ship info -->
<!--
<input type="hidden" name="NAMETOSHIP" value="<?php echo $name; ?>"/>
<input type="hidden" name="ADDRESSTOSHIP" value="<?php echo $address; ?>"/>
<input type="hidden" name="CITYTOSHIP" value="<?php echo $city; ?>"/>
<input type="hidden" name="STATETOSHIP" value="<?php echo $state; ?>"/>
<input type="hidden" name="ZIPTOSHIP" value="<?php echo $postcode; ?>">
<input type="hidden" name="COUNTRYTOSHIP" value="<?php echo $country; ?>"/>
-->
<input type="hidden" name="USER1" value="<?php echo $cookieid; ?>"/>
<input type="hidden" name="USER2" value=""/>
<input type="hidden" name="USER3" value=""/>
<input type="hidden" name="METHOD" value="CC"/>
<input type="hidden" name="ECHODATA" value="True"/>
<input type="hidden" name="VERBOSITY" value="HIGH"/>

<input type="submit" value="Click Here to Purchase"/>
<div class="smalltext"><b>Credit Card payment is processed securely by Verisign.</b></div>
</form>

<?php
} else {
?>
<form method="GET" name="frmConfirm" action="register_free.php">
<input type="hidden" name="id" value="<?php echo $cookieid; ?>"/>
<input type="submit" value="Click Here to Confirm"/>
</form>
<?php
}
?>
</td>
</tr>
</table>
<br><br>

</td>

<td valign="top">
<div><img align="right" src="<?php echo $gaPage['root_directory']; ?>/images/cockatoo_help.jpg" />&nbsp;</div>
</td>

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

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

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