<?php
	/***********************************************************************************
	*   Filename    : pets_detail_update.php
	*   Description : Update pet details
	*
	*   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
	* 
	*   Copyright Keysoft Pty Ltd 2022
	***********************************************************************************/

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

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

	function updatePetDetails($id, $data){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $response = $fm->update('Pets', $id, $data);
		if (!$response['success'])
        {
            // Redirect
			var_dump($response);
			die;
        }

        return;
    }


	/************ Only allow logged in members to this area ************/

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['MemberID'] == ''){
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}
	
	/********************* Page Defaults *********************/
	fDefaultParameter('petid', $_POST, '');
	fDefaultParameter('pet_name', $_POST, '');
	fDefaultParameter('pet_desexed', $_POST, '');
	fDefaultParameter('match_petaddr',     $_POST, '');
	fDefaultParameter('pet_address', $_POST, '');
	fDefaultParameter('pet_state', $_POST, '');
	fDefaultParameter('pet_postcode', $_POST, '');
	fDefaultParameter('pet_suburb', $_POST, '');

	// get values
	$petid =  $_POST['petid'];
	$petname =  $_POST['pet_name'];
	$desexed =  $_POST['pet_desexed'];
	$street = $_POST['pet_address'];
	$suburb = $_POST['pet_suburb'];
	$state = $_POST['pet_state'];
	$postcode = $_POST['pet_postcode'];

	//  get pet record
	// $aRequest = array();
	// $aRequest['_sk_member_id'] = '="' . $_SESSION['MemberID'] . '"';
	// $aRequest['_pk_pet_id'] = '="' . $petid . '"';

	// $fmrPet = fFMPerformFind('petsafe', 'Web - Pets', $aRequest);

	$fm = \Keysoft\FileMaker\Client::getInstance();
	$odataQuery = $fm->buildODataQuery([
		'filter' => "_sk_member_id eq {$_SESSION['MemberID']}",
		'count' => true
	]);
	$fmrPet = $fm->get('Pets', $odataQuery ,$allPages = true );

	$fmcPet = $fmrPet["data"]["value"][0];
	$recordid = $fmcPet["recordId"];;
	// Get tag for audit
	$tag_no = $fmcPet["Tag"];
	
	$odataQuery = $fm->buildODataQuery([
		'filter' => "_sk_pet_id eq {$fmcPet['_pk_ped_id']}",
		'count' => true
	]);
	$chipData = $fm->get('Chips', $odataQuery ,$allPages = true );

	// Get chip no for audit
	$chip_no = $chipData['data']['value'][0]["Chip No"];
	
	//GET FIELD NAMES SO WE CAN COMPARE LATER WITH UPDATED VALUES
    $fmcPetFields = array_flip($fmcPet);

	$aUpdate = array();
	$aUpdate['Desexed'] = $desexed;
	$aUpdate['Name'] = $petname;
	$aUpdate['Address Same As Owner'] = $_POST['match_petaddr'] == '1' ? 'Yes' : '';
	$aUpdate['Street'] = $street;
	$aUpdate['Suburb'] = $suburb;
	$aUpdate['State'] = $state;
	$aUpdate['Postcode'] = $postcode;
	
	//CHECK WHAT VALUES WERE CHANGED SO WE CAN FORM A MORE DETAILED LOG ENTRY
	$updated_values = array();

	foreach($aUpdate as $key => $value){
		if(array_key_exists($key, $fmcPetFields)){
			if(trim($value) != trim($fmcPet[$key])){
				$updated_values[] = strtoupper($key) . ': (' . trim($fmcPet[$key]) . ' -> ' . trim($value) . ')'; 
			}
		}
	}
	
	$audit_extended_description = ' [' . implode(', ', $updated_values) . ']';

	// update pet details
	$fmrPetUpdate = updatePetDetails($recordid, $aUpdate);

	// ADD TO LOG: updated member details
	$aInsert = array();
	$aInsert['_sk_member_id'] = $_SESSION['MemberID'];
	$aInsert['_sk_chip_no'] = $chip_no;
	$aInsert['_sk_tag_no'] = $tag_no;
	$aInsert['description'] = 'Updated Pet Details for ' . $petname . $audit_extended_description;
	$aInsert['is_web_admin_login'] = isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0;
	//$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
	makeLogEntry($aInsert);

	// Redirect
	fRedirect('pets.php');
	fCleanup();
?>
