<?php
//throw new Exception('test error in paypal return page ...');
/*header('Status: 500 Internal Server Error');
header('HTTP/1.0 500 Internal Server Error');
exit;*/
?>

<?php
	/***********************************************************************************
   	*	This is the page returned from Paypal. It returns all the data that we sent to
	*	Paypal along with confirmation of payment. This page is received in background.
	*
	*	On confirmation, we must update the DB with complete date, amount, and ref. no.
	*	
	*   Copyright Keysoft Pty Ltd 2009
	***********************************************************************************/

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

$var_post = var_export($_POST, true);
file_put_contents('../tmp/post_output.txt', $var_post);

	$aCardTypes = array(
			  '0' => 'Visa'
			, '1' => 'MasterCard'
			, '2' => 'Discover'
			, '3' => 'American Express'
			, '4' => 'Diner\'s Club'
			, '5' => 'JCB'
		);

	/********************* 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
	fDefaultParameter('CARDTYPE', $_POST, ''); // cardtype
	
	// 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'];
	$payment_method = array_key_exists($_POST['CARDTYPE'], $aCardTypes) ?  $aCardTypes[$_POST['CARDTYPE']] : '';

	$aInsert = array();
	$aInsert['description'] = '(Processing payment)';
	$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);

	// check response from Paypal and update DB
	if ($result == 0) {
        $aInsert = array();
    	$aInsert['description'] = $var_post;
    	$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
    	
		if (trim($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){
				// stop - transaction not found
				$aInsert = array();
				$aInsert['description'] = '(No transaction found)';
				$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
				die;
			} 

			$emailsent = ',';
			$registeredPets = array(); 
			$fmcTransaction = $fmrTransaction["response"]["data"];

			foreach ($fmcTransaction as $trans_record){
				$newrecordid = $trans_record['fieldData']['_pk_record_id'];
				$email = $trans_record['fieldData']['owner_email'];
				$name = $trans_record['fieldData']['owner_title'] . ' ' . $trans_record['fieldData']['owner_first_name'] . ' ' . $trans_record['fieldData']['owner_last_name'];
				$password = $trans_record['fieldData']['owner_password'];
				$memberid = $trans_record['fieldData']['_sk_member_id'];
				$vetid = $trans_record['fieldData']['_sk_vet_id'];
				$petname = $trans_record['fieldData']['pet_name'];
				$paymentreference = $trans_record['fieldData']['payment_reference_no'];
                $rego_type = strtolower($trans_record['fieldData']['rego_type']);
				
				//Get chip no for audit
				$chip_no = $trans_record['fieldData']['microchip_no'];
				
				//Get tag no for audit
				$tag_no = $trans_record['fieldData']['petsafe_no'];
                
                $registeredPets[] = $petname;
                
				if ($paymentreference != ''){
					// stop - complete already
					$aInsert = array();
					$aInsert['description'] = '(Did not process - already complete)';
					$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
					die;
				}

				// update transaction with complete details
				$aUpdate = array();
				if ($trans_record['fieldData']['payment_required'] == 'Yes'){
					$aUpdate['payment_method']       = $payment_method;
					$aUpdate['payment_reference_no'] = $refno;
				}
                
				$aUpdate['transaction_finish'] = fGetFMTimeStamp();
				$fmrTransactionUpdate = fFMPerformUpdate('petsafe','All Fields - Web_Payments', $trans_record['recordId'], $aUpdate);

//$aInsert = array();
//$aInsert['description'] = '(Transaction update complete)';
//$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);



				// ADD TO LOG: paid for registration
				$aInsert = array();
				if ($vetid != '') {
					$aInsert['_sk_vet_id'] = $vetid;
					$aInsert['description'] = 'Registration payment approved for pet - ' . $petname . '.';
					$aInsert['_sk_chip_no'] = $chip_no;
					$aInsert['_sk_tag_no'] = $tag_no;
					$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
					
					$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
				} else if ($memberid != '') {
					$aInsert['_sk_member_id'] = $memberid;
					$aInsert['_sk_chip_no'] = $chip_no;
					$aInsert['_sk_tag_no'] = $tag_no;
					$aInsert['description'] = 'Registration payment approved for pet - ' . $petname . '.';
					$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
					
					$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
				} else {
					$aInsert['_sk_chip_no'] = $chip_no;
					$aInsert['_sk_tag_no'] = $tag_no;
					$aInsert['description'] = 'Registration payment approved for pet - ' . $petname . ' (New Owner: ' . $name . ').';
					$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
					
					$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
				}
$var_post = var_export($fmrLog, true);
file_put_contents('../tmp/audit_output.txt', $var_post);  
			//	$bRequest = array();
			//	$bRequest['_pk_record_id'] = '="' . $newrecordid . '"';
		// Run script to add registration - since it's PAID
                if($rego_type == 'breeder'){
                    $script = fFMExecuteScript('petsafe', '[OPS] process web transaction breeder', $newrecordid, 'All Fields - Web_Payments');
                }else{
                    $script = fFMExecuteScript('petsafe', '[OPS] process web transaction', $newrecordid, 'All Fields - Web_Payments' );
                }
                
$var_post = var_export($script, true);
file_put_contents('../tmp/script_output.txt', $var_post);  

                // Get generated member id that created in the fm script
                $new_member_id = $script['response']['scriptResult'];

 /*               // Get generated member id that created in the fm script
                $fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $bRequest);
                if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
                    // set member id
                    $new_member_id = 'There was an error retrieving your member id, please contact Petsafe.';
                }else{
                    $fmcTransaction = $fmrTransaction["response"]["data"][0];
                    $new_member_id = $fmcTransaction['fieldData']['generated_member_id'];
                }
*/
                $lb = "<br/><br/>";

				// send email confirmation - new rego details - only once
				if ($email != '' and $password != ''){
                    if (strpos(strtolower($emailsent),strtolower(',' . $email . ',')) === FALSE || strtoupper($_SESSION['rego_type']) == 'BREEDER'){
                        $headers = "From: " . $gaFM['petsafe']['email'] . "\r\n" . "X-Mailer: php";
						$to = $email;
						$subject = "Your PetSafe Registration was successful";
                        
		$body = <<<BODY
Hi $name,<br>
<br>
Your PetSafe Member ID and password details are as follows.<br>
<br>
Member ID:<b>$new_member_id</b><br>
Password:<b>$password</b><br>
<br>
If you did not receive your Petsafe certificate in the accompanying email you should check your spam/junk and trash folder<br>
<br>
If you cannot find it go to <a href="www.petsafe.com.au" target="_blank">www.petsafe.com.au</a> and login using the Member number and password above and print your certificate<br>
<br>
Keep a copy of your certificate in a safe place.<br>
In some States may need to show the certificate to your local council to prove registration on a lost and found database<br>
<br>
Please ensure that you keep your contact information up to date when you move or change phone numbers.<br>
You can make as many updates (ex ownership) as you like online for free.. i.e. when you go on holidays.<br>
<br>
<h4>Change of Petsafe Ownership Access</h4>
Change of Petsafe data Ownership cannot be completed online and must be notified in writing using our form<br>
The Form and should be signed by both the former owner and the new owner.<br>
If the former owner is not contactable for some reason complete the form with your details and send it to us.<br>
We will attempt to obtain consent from the owner as recorded on our records and will give them three working weeks to respond.<br>
If the original owner is uncontactable we will change ownership to your name after the three week period.<br>
In the event of a dispute we will freeze the Petsafe data pending a solution to the dispute.<br>
<br>
Download form <a href="/forms/Petsafe_Change_Owner.pdf" target="_blank">here</a>
<br>		
BODY;
                        
						send_mail($subject, $body, $to, array());
					}
				}

				$emailsent = $emailsent . $email . ',';
			}
		
		} else if (trim($invoiceid) != '') {
			// process direct payment of invoice
			$invoicelist = array();
			$invoicelist = explode(",",$invoiceid);
			foreach ($invoicelist as $id){
				$aRequest = array();
				$aRequest['_pk_invoice_id'] = '="' . $id . '"';
				$fmrInvoice = fFMPerformFind('petsafe', 'Web - Invoice', $aRequest);
				if ($fmrInvoice === FALSE || $fmrInvoice["response"]["dataInfo"]["foundCount"] != 1){
					// invoice not found
				}
				$fmcInvoice = $fmrInvoice["response"]["data"][0];
				$paymentreference = $fmcInvoice['fieldData']['payment_reference'];
				$vetid = $fmcInvoice['fieldData']['_sk_contact_id'];

				if ($paymentreference == ''){
					// update invoice
					$aUpdate = array();
					$aUpdate['payment_method']    = $payment_method;
					$aUpdate['payment_reference'] = $refno;
					$aUpdate['Invoice Status']    = 'Closed';
					$aUpdate['invoice_paid_date'] = date("m/d/Y");
					$aUpdate['approve']           = 'Yes';
					$fmrInvoiceUpdate = fFMPerformUpdate('petsafe', 'Web - Invoice', $fmcInvoice['recordId'], $aUpdate); 

					// ADD TO LOG: paid invoice
					$aInsert = array();
					$aInsert['_sk_vet_id'] = $vetid;
					$aInsert['description'] = 'Invoice# ' . $id . ' paid.';
					$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
					
					$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
				}
			}
		} else if (trim($chip_id) != '') {
			// Find the chip
			$aRequest = array();
			$aRequest['_pk_chip_id'] = '="' . $chip_id . '"';

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

			/************ Check for not found or duplicate ************/
			if ($fmrChip === FALSE || $fmrChip["response"]["dataInfo"]["foundCount"] != 1)
			{
				// Not found
				fCleanup();
			}
			$fmcChip = $fmrChip["response"]["data"][0];

			// Get the pet details
			$aRequest = array();
			$aRequest['_pk_pet_id'] = '="' . $fmcChip['fieldData']['_sk_pet_id'] . '"';

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

			/************ Check for not found or duplicate ************/
			if ($fmrPet === FALSE || $fmrPet["response"]["dataInfo"]["foundCount"] != 1)
			{
				// Not found
				fCleanup();
			}
			
			///////
			//AMOUNT HAS BEEN PAID!, GET DATA FROM WEB PAYMENTS AND UPDATE PET INFO
			$aRequest = array();
			$aRequest['cookie_transaction_id'] = '="' . $transaction_id . '"';
			
			$fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
			
			if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
				// invalid transaction
				fCleanup();
			}else{
				$fmrTransactionRecord = $fmrTransaction["response"]["data"][0];
				
				$new_owner_id = $fmrTransactionRecord['fieldData']['_sk_member_id'];
				$pet_street = $fmrTransactionRecord['fieldData']['pet_street'];
				$pet_suburb = $fmrTransactionRecord['fieldData']['pet_suburb'];
				$pet_state = $fmrTransactionRecord['fieldData']['pet_state'];
				$pet_postcode = $fmrTransactionRecord['fieldData']['pet_postcode'];
				$address_same_as_owner = $fmrTransactionRecord['fieldData']['pets_address_same_as_owners'];
			}
			////////////
			
			$fmcPet = $fmrPet["response"]["data"][0];
			
			$old_owner_id = $fmcPet['fieldData']['_sk_member_id'];
			
			// Get tag for audit
			$tag_no = $fmcPet['fieldData']["Tag"];
			
			// Get chip no for audit
			$chip_no = $fmcPet['fieldData']["pet_Chips::Chip No"];

			// Update the pet record with new owner
			$aUpdate = array();
			$aUpdate['_sk_member_id']         = $new_owner_id;
			$aUpdate['Address Same As Owner'] = $address_same_as_owner;
			$aUpdate['Street']                = $pet_street;
			$aUpdate['Suburb']                = $pet_suburb;
			$aUpdate['State']                 = $pet_state;
			$aUpdate['Postcode']              = $pet_postcode;
		
			// update pet details
			$fmrPetUpdate = fFMPerformUpdate('petsafe','All Fields - Pets', $fmcPet['recordId'], $aUpdate);
			// update transaction record with paypal ref no
			$tUpdate = array();
			$tUpdate['payment_reference_no']  = $refno;
			$tUpdate['payment_method']       = $payment_method;
			$tUpdate['transaction_finish'] = fGetFMTimeStamp();

			$fmrTransactionUpdate = fFMPerformUpdate('petsafe', 'All Fields - Web_Payments', $fmrTransactionRecord['recordId'], $tUpdate);

			//$fmcPet = $fmrPet->getFirstRecord();
			//$member_id = $fmcPet->getField('_sk_member_id');
			$member_id = $new_owner_id;
			$pet_id    = $fmcChip['fieldData']['_sk_pet_id'];

			// create the invoice
			$aInsert = array();
			$aInsert['client_type']       = 'Owner';
			$aInsert['_sk_client_id']     = $member_id;
			$aInsert['_sk_contact_id']    = $member_id;
			$aInsert['payment_method']    = $payment_method;
			$aInsert['payment_reference'] = $refno;
			$aInsert['approve']           = 'Yes';
			$aInsert['Invoice Status']    = 'Closed';
			$aInsert['invoice_paid_date'] = date("m/d/Y");
			$var_post = var_export($aInsert, true);


			// Set the new invoice id

			$fmcInvoice = fFMPerformInsert('petsafe', 'Web - Invoice', $aInsert);
	
            $fmcInvoice = fFMGetRecord('petsafe', 'Web - Invoice', $fmcInvoice['response']['recordId']);
            $invoice_id = $fmcInvoice['response']['data'][0]['fieldData']['_pk_invoice_id'];

//$aInsert = array();
//$aInsert['description'] = "Created invoice:".$invoice_id;
//$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);		           
			
			// create the invoice item **** FIX FROM HERE
			$aInsert = array();
			$aInsert['_sk_client_id'] = $member_id;
			$aInsert['_sk_member_id'] = $member_id;
			$aInsert['_sk_chip_id'] = $chip_id;
			$aInsert['_sk_pet_id'] = $pet_id;
			$aInsert['item_code'] = $item_code;
			$aInsert['_sk_invoice_id'] = $invoice_id;
			$aInsert['Qty'] = 1;
			$aInsert['Amount'] = $amount;
			$fmcInvoiceItem = fFMPerformInsert('petsafe', 'Web - Invoice Items', $aInsert);
	
//$logInsert = array();
//$logInsert['description'] = "Invoice Line:<br/>".var_export($aInsert,true)."\n".var_export($fmcInvoiceItem,true);
//$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $logInsert);		

			//log in pet history
			$aRequest = array();
			$aRequest['_sk_pet_id'] = '="' . $pet_id . '"';
			$aSort[]=["fieldName" => "creation_timestamp", "sortOrder" => "descend"];
			$fmrHistory = fFMPerformFind('petsafe', 'All Fields - Pet_History', $aRequest, $aSort);
			
			if($old_owner_id != $new_owner_id){
				//if there is already history, check if the last added record is different from the new owner, if so, log the change
				if ($fmrHistory === FALSE){
					$aInsert = array();
					$aInsert['_sk_member_id'] = $old_owner_id;
					$aInsert['_sk_pet_id'] = $pet_id;
			
					$fmcHistory = fFMPerformInsert('petsafe', 'All Fields - Pet_History', $aInsert);
				}elseif($fmrHistory["response"]["dataInfo"]["foundCount"] > 0){
					$fmrHistoryRecord = $fmrHistory["response"]["data"][0];
					
					if($old_owner_id != $fmrHistoryRecord['fieldData']['_sk_member_id']){
						$aInsert = array();
						$aInsert['_sk_member_id'] = $old_owner_id;
						$aInsert['_sk_pet_id'] = $pet_id;
						
						$fmcHistory = fFMPerformInsert('petsafe', 'All Fields - Pet_History', $aInsert);
					}
				}
			}
			
			
			// ADD TO LOG: updated member details
			if ($old_owner_id != $new_owner_id)
			{
			$aInsert = array();
			$aInsert['_sk_member_id'] = $member_id;
			$log_description = 'Updated Pet Details for ' . $fmcPet['fieldData']['Name'] . '. [Old Owner ID:' . $old_owner_id . ' -> New Owner ID:' . $new_owner_id . ']';
			$aInsert['description'] = $log_description;
			$aInsert['_sk_chip_no'] = $chip_no;
			$aInsert['_sk_tag_no'] = $tag_no;
			$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
			
			$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
			}

		}

	}
?>
