<?php
	/***********************************************************************************
    *	Filename    : register_return.php
	*   Description :	This is the page returned from Paypal. It returns all the data that we sent to
	*	Paypal along with confirmation of payment.
	*
	*	On confirmation, we must update the DB with complete date, amount, and ref. no.
	*   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'] = '..';

	/********************* Page Defaults *********************/
	fDefaultParameter('USER1', $_POST, ''); // cookie/transaction id for REGO PAYMENT
	fDefaultParameter('USER2', $_POST, ''); // invoice id for INVOICE PAYMENT
	fDefaultParameter('USER3', $_POST, ''); // chip id for Change of Ownership or change of details
	fDefaultParameter('USER4', $_POST, ''); // item_code for Change of Ownership or change of details
	fDefaultParameter('USER5', $_POST, ''); // transaction id for change of ownership
	fDefaultParameter('RESULT', $_POST, ''); // should be 0 - means approved
	fDefaultParameter('RESPMSG', $_POST, ''); // response desc - use to show user if not approved
	fDefaultParameter('PNREF', $_POST, ''); // payment reference number
	fDefaultParameter('AMT', $_POST, ''); // amount

	// get values into variables
	$cookieid = $_POST['USER1'];
	$invoiceid = $_POST['USER2'];
	$chip_id = $_POST['USER3'];
	$item_code= $_POST['USER4'];
	$transaction_id= $_POST['USER5'];
	$result = $_POST['RESULT'];
	$response = $_POST['RESPMSG'];
	$refno = $_POST['PNREF'];
	$amount = $_POST['AMT'];



	// check response from Paypal - success or fail
	if ($result == 0) {
		if (trim($cookieid) != ''){
			//init cookie if in session - no 2nd chance
			$_SESSION['cookieid'] = '';

			// select transaction
			$aRequest = array();
			$aRequest['cookie_transaction_id'] = '="' . $cookieid . '"';
			$fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
			if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
				// redirect to error when transaction not found
				fRedirect('register_error.php');
				fCleanup();
			} 
			$fmcTransaction = $fmrTransaction["response"]["data"];

			// loop transactions/rego's
			$no_vets = 0;
			$no_members = 0;
			foreach ($fmcTransaction as $trans_record){
				// need to detect if it is a single owner doing the transaction
				if ($trans_record['fieldData']['_sk_vet_id'] != ''){
					$no_vets = $no_vets + 1;
				}
				if ($trans_record['fieldData']['_sk_member_id'] != ''){
					$no_members = $no_members + 1;
				}
			}

			//if new user, then log the user in and show login details on the next page
			if ($no_vets == 0 and $no_members == 0 and $_SESSION['LoggedIn'] == 0){
				$fmcSingleTransaction = $fmrTransaction["response"]["data"][0];

				// get pet id and then from there, member id
				$petid = $trans_record['fieldData']['_sk_pet_id'];
				$aRequest = array();
				$aRequest['_pk_pet_id'] = '="' . $petid . '"';
				$fmrPet = fFMPerformFind('petsafe', 'Web - Pets', $aRequest, null, null, FALSE);
				$fmcPet = $fmrPet["response"]["data"][0];
				//get owner id from pet record
				$ownerid = $fmcPet['fieldData']['_sk_member_id'];

				// log the user in
				// set session vars
				$_SESSION['LoggedIn'] = 1;
				$_SESSION['MemberID'] = $ownerid;

				// ADD TO LOG: login action
				$aInsert['_sk_member_id'] = $ownerid;
				$aInsert['description'] = 'Logged in as Owner';
				$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
				
				$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);

				// redirect to thanks, plus show user login details
				fRedirect('register_thanks.php?newuser=true&id=' . $cookieid);
				fCleanup();
			}

			// redirect to thanks
			fRedirect('register_thanks.php?id=' . $cookieid);
			fCleanup();

		} else if (trim($invoiceid) != ''){
			// select invoice
			$invoicelist = array();
			$invoicelist = explode(",",$invoiceid);
			$aRequest = array();
			$aRequest['_pk_invoice_id'] = '="' . $invoicelist[0] . '"';
			$fmrInvoice = fFMPerformFind('petsafe', 'Web - Invoice', $aRequest);
			if ($fmrInvoice === FALSE || $fmrInvoice["response"]["dataInfo"]["foundCount"] != 1){
				// redirect to error when transaction not found
				fRedirect('/invoice/invoice_paymenterror.php');
				fCleanup();
			} 

			// redirect to thanks
			fRedirect('/invoice/invoice_paymentthanks.php?id=' . $refno);
			fCleanup();
		} else if (trim($chip_id) != '') {
			// redirect to thanks
			fRedirect('chip_owner_paymentthanks.php?chip_id=' . $chip_id . '&id=' . $transaction_id);
			fCleanup();
		}

	} else {
		// redirect to error
		fRedirect('register_error.php?err_code=' . $response);
		fCleanup();
	}
?>
