<?php
	/***********************************************************************************
	*   Description : Update member details
	*
	*   Copyright Keysoft Pty Ltd 2009
	***********************************************************************************/

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

	/********************* Page Settings *********************/
	$gaPage['title'] = 'Petsafe.com.au';
	$gaPage['root_directory'] = '..';
	
	/************ Only allow admin users ************/
	if (!$_SESSION['IsAdminLogin'] == 1)
	{
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}


	/********************* Page Defaults *********************/
	fDefaultParameter('chip_id',           $_POST, '');
	fDefaultParameter('owner_type',        $_POST, '');
	fDefaultParameter('old_member_id',     $_POST, '');
	fDefaultParameter('member_id',         $_POST, '');
	// New Owner Details
	fDefaultParameter('owner_title',       $_POST, '');
	fDefaultParameter('owner_firstname',   $_POST, '');
	fDefaultParameter('owner_lastname',    $_POST, '');
	fDefaultParameter('owner_homephone',   $_POST, '');
	fDefaultParameter('owner_workphone',   $_POST, '');
	fDefaultParameter('owner_mobilephone', $_POST, '');
	fDefaultParameter('owner_fax',         $_POST, '');
	fDefaultParameter('owner_email',       $_POST, '');
	fDefaultParameter('mailing_list',      $_POST, '');
	fDefaultParameter('owner_altperson1',  $_POST, '');
	fDefaultParameter('owner_altphone1',   $_POST, '');
	fDefaultParameter('owner_altperson2',  $_POST, '');
	fDefaultParameter('owner_altphone2',   $_POST, '');
	fDefaultParameter('owner_password1',   $_POST, '');
	fDefaultParameter('owner_password2',   $_POST, '');
	fDefaultParameter('owner_address',     $_POST, '');
	fDefaultParameter('owner_suburb',      $_POST, '');
	fDefaultParameter('owner_state',       $_POST, '');
	fDefaultParameter('owner_postcode',    $_POST, '');
	fDefaultParameter('match_mailaddr',    $_POST, '');
	fDefaultParameter('mail_address',      $_POST, '');
	fDefaultParameter('mail_suburb',       $_POST, '');
	fDefaultParameter('mail_state',        $_POST, '');
	fDefaultParameter('mail_postcode',     $_POST, '');
	// Pet Details
	fDefaultParameter('pet_id',            $_POST, '');
	fDefaultParameter('match_petaddr',     $_POST, '');
	fDefaultParameter('pet_address',       $_POST, '');
	fDefaultParameter('pet_state',         $_POST, '');
    fDefaultParameter('pet_type',          $_POST, '');
	fDefaultParameter('pet_suburb',        $_POST, '');
	fDefaultParameter('pet_postcode',      $_POST, '');

	// get values
	$chip_id       = $_POST['chip_id'];
	$old_member_id = $_POST['old_member_id'];
	$member_id     = $_POST['member_id'];
	$pet_id        = $_POST['pet_id'];
	
	$aRequest = array();
	$aRequest['_pk_chip_id'] = '="' . $chip_id . '"';

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

	$chip_no       = "";
	/************ get chip no for audit ************/
	if ($fmrChip === FALSE || $fmrChip["response"]["dataInfo"]["foundCount"] != 1){
		// Not found
	}else{
		$fmcChip = $fmrChip["response"]["data"][0];
		
		$chip_no = $fmcChip['fieldData']['Chip No'];

	}
	

	// update the current member
	if ($_POST['owner_type'] == 'current')
	{
		// get the owner record
		$aRequest = array();
		$aRequest['_pk_member_id'] = '="' . $old_member_id . '"';

		$fmrOwner = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);
		// Check the owner was found
		if ($fmrOwner === FALSE || $fmrOwner["response"]["dataInfo"]["foundCount"] != 1)
		{
			fReturnError('The owner record was not found.');
		}

		$fmcOwner = $fmrOwner["response"]["data"][0];

		// Update the record
		$aUpdate = array();
		$aUpdate['Title']            = $_POST['owner_title'];
		$aUpdate['Given Name']       = $_POST['owner_firstname'];
		$aUpdate['Last Name']        = $_POST['owner_lastname'];
		$aUpdate['Home Phone']       = $_POST['owner_homephone'];
		$aUpdate['Work Phone']       = $_POST['owner_workphone'];
		$aUpdate['Mobile']           = $_POST['owner_mobilephone'];
		$aUpdate['Fax']              = $_POST['owner_fax'];
		$aUpdate['Email']            = $_POST['owner_email'];
		$aUpdate['Mail List']        = $_POST['mailing_list'];
		$aUpdate['Alt Person A']     = $_POST['owner_altperson1'];
		$aUpdate['Phone A']          = $_POST['owner_altphone1'];
		$aUpdate['Alt Person B']     = $_POST['owner_altperson2'];
		$aUpdate['Phone B']          = $_POST['owner_altphone2'];
		$aUpdate['Password']         = $_POST['owner_password1'];
		$aUpdate['Street']           = $_POST['owner_address'];
		$aUpdate['Suburb']           = $_POST['owner_suburb'];
		$aUpdate['State']            = $_POST['owner_state'];
		$aUpdate['Postcode']         = $_POST['owner_postcode'];
        
		if ($_POST['match_mailaddr'] == '1')
		{
			$aUpdate['Mailing Street']   = $_POST['owner_address'];
			$aUpdate['Mailing Suburb']   = $_POST['owner_suburb'];
			$aUpdate['Mailing State']    = $_POST['owner_state'];
			$aUpdate['Mailing Postcode'] = $_POST['owner_postcode'];
		}
		else
		{
			$aUpdate['Mailing Street']   = $_POST['mail_address'];
			$aUpdate['Mailing Suburb']   = $_POST['mail_suburb'];
			$aUpdate['Mailing State']    = $_POST['mail_state'];
			$aUpdate['Mailing Postcode'] = $_POST['mail_postcode'];
		}
        
        //GET FIELD NAMES SO WE CAN COMPARE LATER WITH UPDATED VALUES
        $fmcOwnerFields = array_flip($fmrOwner['fieldData']);
        
        //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, $fmcOwnerFields)){
                echo '1 - ';
                if(trim($value) != trim($fmcOwner['fieldData'][$key])){
                    $updated_values[] = strtoupper($key) . ': (' . trim($fmcOwner['fieldData'][$key]) . ' -> ' . trim($value) . ')'; 
                }
            }
        }

        $audit_extended_description = ' [' . implode(', ', $updated_values) . ']';
        $fmcOwnerID = $fmcOwner['recordId']; 

		// update owner details
		$fmrOwnerUpdate = fFMPerformUpdate('petsafe', 'Web - Owners',$fmcOwnerID, $aUpdate);

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

	}
	// change to a new existing member
	else if ($_POST['owner_type'] == 'existing')
	{
		$aRequest = array();
		$aRequest['_pk_member_id'] = '="' . $member_id . '"';

		$fmrMember = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);

		if ($fmrMember === FALSE || $fmrMember["response"]["dataInfo"]["foundCount"] != 1)
		{
			// invalid member id
			fRedirect('chip_owner_change.php?chip_id='.$chip_id.'&err_code=InvalidMemberID');
			fCleanup();
		}else{

		}
	}
	// create the new member
	else if ($_POST['owner_type'] == 'new')
	{
		$aInsert = array();
		$aInsert['Title']            = $_POST['owner_title'];
		$aInsert['Given Name']       = $_POST['owner_firstname'];
		$aInsert['Last Name']        = $_POST['owner_lastname'];
		$aInsert['Home Phone']       = $_POST['owner_homephone'];
		$aInsert['Work Phone']       = $_POST['owner_workphone'];
		$aInsert['Mobile']           = $_POST['owner_mobilephone'];
		$aInsert['Fax']              = $_POST['owner_fax'];
		$aInsert['Email']            = $_POST['owner_email'];
		$aInsert['Mail List']        = $_POST['mailing_list'];
		$aInsert['Alt Person A']     = $_POST['owner_altperson1'];
		$aInsert['Phone A']          = $_POST['owner_altphone1'];
		$aInsert['Alt Person B']     = $_POST['owner_altperson2'];
		$aInsert['Phone B']          = $_POST['owner_altphone2'];
		$aInsert['Password']         = $_POST['owner_password1'];
		$aInsert['Street']           = $_POST['owner_address'];
		$aInsert['Suburb']           = $_POST['owner_suburb'];
		$aInsert['State']            = $_POST['owner_state'];
		$aInsert['Postcode']         = $_POST['owner_postcode'];
		if ($_POST['match_mailaddr'] == '1')
		{
			$aInsert['Mailing Street']   = $_POST['owner_address'];
			$aInsert['Mailing Suburb']   = $_POST['owner_suburb'];
			$aInsert['Mailing State']    = $_POST['owner_state'];
			$aInsert['Mailing Postcode'] = $_POST['owner_postcode'];
		}
		else
		{
			$aInsert['Mailing Street']   = $_POST['mail_address'];
			$aInsert['Mailing Suburb']   = $_POST['mail_suburb'];
			$aInsert['Mailing State']    = $_POST['mail_state'];
			$aInsert['Mailing Postcode'] = $_POST['mail_postcode'];
		}
		$fmcMember = fFMPerformInsert('petsafe', 'Web - Owners', $aInsert);
      
        $newMemberID = fFMGetRecord('petsafe','Web - Owners',$fmcMember['response']['recordId']);

		// Set the new member id
		$member_id = $newMemberID['response']['data'][0]['fieldData']['_pk_member_id'];
	}



	// get the pet record
	$aRequest = array();
	$aRequest['_pk_pet_id'] = '="' . $pet_id . '"';

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

	// Check the pet was found
	if ($fmrPet === FALSE || $fmrPet["response"]["dataInfo"]["foundCount"] != 1)
	{
		fReturnError('The pet record was not found.');
	}
	
	$fmcPet = $fmrPet["response"]["data"][0];

	//create transaction unique id
	$transaction_id = strrev($fmcPet['fieldData']['Name']) . uniqid(rand(), true);
	
	//save data to web payments so it can be extracted later from there if payment is successful. 
	$aInsert = array();
	$aInsert['microchip_no'] = $pet_id;
	$aInsert['_sk_member_id'] = $member_id;
	$aInsert['_sk_pet_id'] = $pet_id;
	$aInsert['pets_address_same_as_owners'] = $_POST['match_petaddr'] == '1' ? 'Yes' : '';
	$aInsert['pet_street'] = $_POST['pet_address'];
	$aInsert['pet_suburb'] = $_POST['pet_suburb'];
	$aInsert['pet_state'] = $_POST['pet_state'];
    $aInsert['pet_type'] = $_POST['pet_type'];
	$aInsert['pet_postcode'] = $_POST['pet_postcode'];
	$aInsert['cookie_transaction_id'] = $transaction_id;
	
	$fmrRegister = fFMPerformInsert('petsafe', 'All Fields - Web_Payments', $aInsert);

	//echo '<pre>';
	//print_r($aInsert);
	//echo '</pre>';
	
	
	//die();
	
	// Update the pet record
	$aUpdate = array();
	$aUpdate['_sk_member_id']         = $member_id;
	$aUpdate['Address Same As Owner'] = $_POST['match_petaddr'] == '1' ? 'Yes' : '';
	$aUpdate['Street']                = $_POST['pet_address'];
	$aUpdate['Suburb']                = $_POST['pet_suburb'];
	$aUpdate['State']                 = $_POST['pet_state'];
	$aUpdate['Postcode']              = $_POST['pet_postcode'];
	$aUpdate['Name']                  = $_POST['pet_name'];
	$aUpdate['Type']                  = $_POST['pet_type'];
	$aUpdate['Colour']                = $_POST['pet_colour'];
	$aUpdate['Breed']                 = $_POST['pet_breed'];
	$aUpdate['DOB']                   = $_POST['pet_dob_mm'] . '/' . $_POST['pet_dob_dd'] . '/' . $_POST['pet_dob_yyyy'];
	$aUpdate['Sex']                   = $_POST['pet_sex'];
	$aUpdate['Desexed']               = $_POST['pet_desexed'];
	$aUpdate['Savage']                = $_POST['pet_savage'];

	// update pet details
	$fmrPetUpdate = fFMPerformUpdate('petsafe','Web - Pets', $fmcPet['recordId'], $aUpdate); 


	// Log if owner has changed
	if ($old_member_id != $member_id)
	{
		$aInsert = array();
		$aInsert['_sk_pet_id']    = $pet_id;
		$aInsert['_sk_member_id'] = $old_member_id;			
		$fmcPetHistory = fFMPerformInsert('petsafe', 'Web - Pet_History', $aInsert);
	}

	// ADD TO LOG: updated member details
	$aInsert = array();
	$aInsert['_sk_member_id'] = $member_id;
	$aInsert['description'] = 'Updated Pet Details for ' . $fmcPet['fieldData']['Name'];
	$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);

	// Redirect
	fRedirect('chip_owner_cart.php?chip_id='.$chip_id . '&t=' . $transaction_id);
	fCleanup();
?>
