<?php
	/***********************************************************************************
	*   Filename    : index.php
	*   Description : Petsafe Index/Home page
	*
	*   Date        Modification By      Description
	*   20/10/2008  Shane Schokman       Initial Creation
	*   23/01/2009  Kenneth Ho           Adaptation to Digivet-Petsafe
    *
	*   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('microchip_no', $_POST, '');
	fDefaultParameter('petsafe_no', $_POST, '');
	fDefaultParameter('clinic_no', $_POST, '');
	fDefaultParameter('implanting_vet', $_POST, '');
	fDefaultParameter('owner_title', $_POST, '');
	fDefaultParameter('owner_firstname', $_POST, '');
	fDefaultParameter('owner_lastname', $_POST, '');
	fDefaultParameter('owner_address', $_POST, '');
	fDefaultParameter('owner_state', $_POST, '');
	fDefaultParameter('owner_suburb', $_POST, '');
	fDefaultParameter('owner_postcode', $_POST, '');
	fDefaultParameter('match_mailaddr', $_POST, '');
	fDefaultParameter('mail_address', $_POST, '');
	fDefaultParameter('mail_state', $_POST, '');
	fDefaultParameter('mail_suburb', $_POST, '');
	fDefaultParameter('mail_postcode', $_POST, '');
	fDefaultParameter('owner_homephone', $_POST, '');
	fDefaultParameter('owner_workphone', $_POST, '');
	fDefaultParameter('owner_mobilephone', $_POST, '');
	fDefaultParameter('owner_fax', $_POST, '');
	fDefaultParameter('owner_email', $_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('mailing_list', $_POST, '');
	fDefaultParameter('pet_name', $_POST, '');
	fDefaultParameter('pet_type', $_POST, '');
	fDefaultParameter('pet_colour', $_POST, '');
	fDefaultParameter('pet_breed', $_POST, '');
	fDefaultParameter('pet_dob_dd', $_POST, '');
	fDefaultParameter('pet_dob_mm', $_POST, '');
	fDefaultParameter('pet_dob_yyyy', $_POST, '');

	fDefaultParameter('pet_breeder_id', $_POST, '');
	fDefaultParameter('pet_implant_dd', $_POST, '');
	fDefaultParameter('pet_implant_mm', $_POST, '');
	fDefaultParameter('pet_implant_yyyy', $_POST, '');
	fDefaultParameter('pet_distinguishing_marks', $_POST, '');

	fDefaultParameter('pet_sex', $_POST, '');
	fDefaultParameter('pet_desexed', $_POST, '');
	fDefaultParameter('pet_savage', $_POST, '');
	fDefaultParameter('match_petaddr', $_POST, '');
	fDefaultParameter('pet_address', $_POST, '');
	fDefaultParameter('pet_state', $_POST, '');
	fDefaultParameter('pet_suburb', $_POST, '');
	fDefaultParameter('pet_postcode', $_POST, '');
	fDefaultParameter('entered_by', $_POST, '');

	// get values into variables
	$chipno = $_POST['microchip_no'];
	$petsafeno = $_POST['petsafe_no'];
	$companyid = trim($_POST['clinic_no']);
	
	//////////////////////////////////////////
	$implanting_vet = trim($_POST['implanting_vet']);
	//////////////////////////////////////////
	
	$title = $_POST['owner_title'];
	$firstname = $_POST['owner_firstname'];
	$lastname = $_POST['owner_lastname'];
	$street = $_POST['owner_address'];
	$suburb = $_POST['owner_suburb'];
	$state = $_POST['owner_state'];
	$postcode = $_POST['owner_postcode'];
	if ($_POST['match_mailaddr'] == '1'){
		// mail address same as owner
		$mailstreet = $street;
		$mailsuburb = $suburb;
		$mailstate = $state;
		$mailpostcode = $postcode;
	} else {
		// mail address entered
		$mailstreet = $_POST['mail_address'];
		$mailsuburb = $_POST['mail_suburb'];
		$mailstate = $_POST['mail_state'];
		$mailpostcode = $_POST['mail_postcode'];
	}
	$homephone = $_POST['owner_homephone'];
	$workphone = $_POST['owner_workphone'];
	$mobile = $_POST['owner_mobilephone'];
	$fax = $_POST['owner_fax'];
	$email = $_POST['owner_email'];
	$altpersonA = $_POST['owner_altperson1'];
	$altphoneA = $_POST['owner_altphone1'];
	$altpersonB = $_POST['owner_altperson2'];
	$altphoneB = $_POST['owner_altphone2'];
	$password = $_POST['owner_password1'];
    
	$mailinglist = $_POST['mailing_list'];
	$petname = $_POST['pet_name'];
	$pettype = $_POST['pet_type'];
	$petcolour = $_POST['pet_colour'];
	$petbreed = $_POST['pet_breed'];
	$petdob = $_POST['pet_dob_mm'] . '/' . $_POST['pet_dob_dd'] . '/' . $_POST['pet_dob_yyyy'];
	
	$pet_dist_marks = $_POST['pet_distinguishing_marks'];
	$entered_by = $_POST['entered_by'];
	$pet_breeder_id = $_POST['pet_breeder_id'];
	
	$pet_implant_date = '';
	
	if($_POST['pet_implant_mm'] != '' and $_POST['pet_implant_dd'] != '' and $_POST['pet_implant_yyyy'] != ''){
		$pet_implant_date = $_POST['pet_implant_mm'] . '/' . $_POST['pet_implant_dd'] . '/' . $_POST['pet_implant_yyyy'];
	}
	
	$petsex = $_POST['pet_sex'];
	$petdesexed = $_POST['pet_desexed'];
	$petsavage = $_POST['pet_savage'];
	
	if ($_SESSION['MemberID'] != '' and $_POST['match_petaddr'] == '1'){
		// retrieve member address details
		$aRequest = array();
		$aRequest['_pk_member_id'] = '="' . $_SESSION['MemberID'] . '"';
		$fmrOwner = fFMPerformFind('petsafe', 'Web - Owners', $aRequest);
		$fmcOwner = $fmrOwner["response"]["data"][0];
		// fill pet fields with member's address
		$petstreet = $fmcOwner['fieldData']['Street'];
		$petsuburb = $fmcOwner['fieldData']['Suburb'];
		$petstate = $fmcOwner['fieldData']['State'];
		$petpostcode = $fmcOwner['fieldData']['Postcode'];
		$petsAddressSameAsOwners = 'Yes';

	} else if ($_POST['match_petaddr'] == '1'){
		// pet address same as owner
		$petstreet = $street;
		$petsuburb = $suburb;
		$petstate = $state;
		$petpostcode = $postcode;
		$petsAddressSameAsOwners = 'Yes';
	} else {
		// pet address entered
		$petstreet = $_POST['pet_address'];
		$petsuburb = $_POST['pet_suburb'];
		$petstate = $_POST['pet_state'];
		$petpostcode = $_POST['pet_postcode'];
		$petsAddressSameAsOwners = '';
	}
	
	$vetid = $_SESSION['VetID'];
	$memberid = $_SESSION['MemberID'];
	$transactionamount = '';
	$transactionstart = fGetFMTimeStamp();
	$transactioncomplete = ''; // reset later if required
	$paymentref = ''; // reset later if required
	$paymentrequired = 'No'; // reset later if required

	if (trim($chipno) == '' and trim($petsafeno) == ''){
		// cannot register without mandatory details
		fRedirect('register.php?err_code=Incomplete'); // display error too
		fCleanup();
	}

	///////////////////////////////////////////////////////////////////////////
	// need to check if chip or tag is registered or linked to a pet already //
	///////////////////////////////////////////////////////////////////////////
	if (trim($petsafeno) != ''){
		$aRequest = array();
		$aRequest['Tag'] = '="' . $petsafeno . '"';
		$fmrTag = fFMPerformFind('petsafe', 'Web - Pets', $aRequest);
		if ($fmrTag === FALSE || $fmrTag["response"]["dataInfo"]["foundCount"] < 1){
			// no error
		} else {
			// tag in use - cannot register this!
			fRedirect('register.php?err_code=TagInUse'); // display error too
			fCleanup();
		}
	}

	if (trim($chipno) != ''){
		$aRequest = array();
		$aRequest['Chip No'] = '="' . $chipno . '"';
		$fmrChip = fFMPerformFind('petsafe', 'Web - Chips', $aRequest);
		if ($fmrChip === FALSE || $fmrChip["response"]["dataInfo"]["foundCount"] < 1){
			// no duplicates
		} else {
			// POSSIBLE duplicate found
			$fmcChip = $fmrChip["response"]["data"];
			$duplicate = 0;
			foreach ($fmcChip as $chip){
				$petid = $chip['fieldData']['_sk_pet_id'];
				if (trim($petid) != ''){
					$duplicate = 1;
					break;
				}
			}
			if ($duplicate == 1){
				// chip in use - cannot register this!
				fRedirect('register.php?err_code=ChipInUse'); // display error too
				fCleanup();
			}
		}
		
		//also check chip no is not being used in the current transaction.
		if ($_SESSION['cookieid'] != ''){
			$aRequest = array();
			$aRequest['microchip_no'] = '="' . $chipno . '"';
			$aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
			
			$fmrChip = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
			
			if ($fmrChip === FALSE || $fmrChip["response"]["dataInfo"]["foundCount"] < 1){
				//not found in current transaction
			} else {
				fRedirect('register.php?err_code=ChipInUseCurrTran'); // display error too
				fCleanup();
			}
		}
		
	}
    
	// check if payment needed
	//		- if no chip in system, payment needed
	//		- if chip not entered, payment needed
	//		- if chip in system check if payment needed:
	//			- lookup invoice number for that chip in the chip table
	//			- does invoice number exist?
	//				- if yes, NO payment needed
	//				- else, payment needed
	if (trim($chipno) == ''){
		// no chip entered - payment required
		$paymentrequired = 'Yes';
	} else {

		// get chip record, if any
		$cRequest = array();
		$cRequest['Chip No'] = '="' . $chipno . '"';
		$fmrChips = fFMPerformFind('petsafe', 'Web - Chips', $cRequest);

		if ($fmrChips === FALSE || $fmrChips["response"]["dataInfo"]["foundCount"] != 1){
			// new chip not in system - payment required
			$paymentrequired = 'Yes';

		} else {
			// chip exists - check if rego has been paid
			$fmcChip = $fmrChips["response"]["data"][0];
			$chipInvoice = $fmcChip['fieldData']['_sk_invoice_id'];
			if (trim($chipInvoice) != ''){
				// chip has been paid for
				$paymentrequired = 'No';
			} else {
				// chip has NOT been paid for - payment required
				$paymentrequired = 'Yes';
			}
		}
	}
	
	// check if user is NEW and adding 2nd pet
	if ($_SESSION['LoggedIn'] == 0 and $_SESSION['cookieid'] != ''){
		// retrieve info from cookie id
		$aRequest = array();
		$aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
		$fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
		if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
			// invalid cookie id
			$SESSION['cookieid'] = '';

		} else {
			// cookie exists - retrieve user info

			$fmcTransaction = $fmrTransaction["response"]["data"][0];
			
			$title = $fmcTransaction['fieldData']['owner_title'];
			$firstname = $fmcTransaction['fieldData']['owner_first_name'];
			$lastname = $fmcTransaction['fieldData']['owner_last_name'];
			$street = $fmcTransaction['fieldData']['owner_street'];
			$suburb = $fmcTransaction['fieldData']['owner_suburb'];
			$state = $fmcTransaction['fieldData']['owner_state'];
			$postcode = $fmcTransaction['fieldData']['owner_postcode'];
			$mailstreet = $fmcTransaction['fieldData']['mailing_street'];
			$mailsuburb = $fmcTransaction['fieldData']['mailing_suburb'];
			$mailstate = $fmcTransaction['fieldData']['mailing_state'];
			$mailpostcode = $fmcTransaction['fieldData']['mailing_postcode'];
			$homephone = $fmcTransaction['fieldData']['owner_home_phone'];
			$workphone = $fmcTransaction['fieldData']['owner_work_phone'];
			$mobile = $fmcTransaction['fieldData']['owner_mobile'];
			$fax = $fmcTransaction['fieldData']['owner_fax'];
			$email = $fmcTransaction['fieldData']['owner_email'];
			$altpersonA = $fmcTransaction['fieldData']['alternate_person_a'];
			$altphoneA = $fmcTransaction['fieldData']['alternate_phone_a'];
			$altpersonB = $fmcTransaction['fieldData']['alternate_person_b'];
			$altphoneB = $fmcTransaction['fieldData']['alternate_phone_b'];
			$password = $fmcTransaction['fieldData']['owner_password'];
			$mailinglist = $fmcTransaction['fieldData']['mail_list'];

			if ($_POST['match_petaddr'] == '1'){
				$petstreet = $street;
				$petsuburb = $suburb;
				$petstate = $state;
				$petpostcode = $postcode;
				$petsAddressSameAsOwners = 'Yes';
			}

		}
	}
	
	// check if transaction pending and get clinic id since clinic is locked to the first registration.
	if ($_SESSION['cookieid'] != ''){
		//if cookieid found, get owner details from web payment table. (used for multiple regos performed by vets)
		if($_SESSION['VetID'] != ''){
			$aRequest = array();
			$aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
			
			$fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
			if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
				// do nothing
			}else{
				$fmcTransaction = $fmrTransaction["response"]["data"][0];

				// get clinic 
				$companyid = $fmcTransaction['fieldData']['_sk_company_id'];
			}
		}
		
	}

	// check if user is adding 2nd pet
	if ($_SESSION['cookieid'] != ''){
		$cookieid = $_SESSION['cookieid'];
		
		//if cookieid found, get owner details from web payment table. (used for multiple regos performed by vets)
		if($_SESSION['VetID'] != ''){
			$aRequest = array();
			$aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
			$aRequest['_sk_vet_id'] = $implanting_vet;
			
			$fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
			if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
				//cookie not found	
			}else{
				$fmcTransaction = $fmrTransaction["response"]["data"][0];

				// get clinic and breeder id selected on first registration, this is used for subsequent registrations to avoid payment issues when completing the transaction.				
				$companyid = $fmcTransaction['fieldData']['_sk_company_id'];
				$pet_breeder_id = $fmcTransaction['fieldData']['pet_breeder_id'];
				
				//get only owner details.
				$title = $fmcTransaction['fieldData']['owner_title'];
				$firstname = $fmcTransaction['fieldData']['owner_first_name'];
				$lastname = $fmcTransaction['fieldData']['owner_last_name'];
				$street = $fmcTransaction['fieldData']['owner_street'];
				$suburb = $fmcTransaction['fieldData']['owner_suburb'];
				$state = $fmcTransaction['fieldData']['owner_state'];
				$postcode = $fmcTransaction['fieldData']['owner_postcode'];
				$mailstreet = $fmcTransaction['fieldData']['mailing_street'];
				$mailsuburb = $fmcTransaction['fieldData']['mailing_suburb'];
				$mailstate = $fmcTransaction['fieldData']['mailing_state'];
				$mailpostcode = $fmcTransaction['fieldData']['mailing_postcode'];
				$homephone = $fmcTransaction['fieldData']['owner_home_phone'];
				$workphone = $fmcTransaction['fieldData']['owner_work_phone'];
				$mobile = $fmcTransaction['fieldData']['owner_mobile'];
				$fax = $fmcTransaction['fieldData']['owner_fax'];
				$email = $fmcTransaction['fieldData']['owner_email'];
				$altpersonA = $fmcTransaction['fieldData']['alternate_person_a'];
				$altpersonB = $fmcTransaction['fieldData']['alternate_person_b'];
				$altphoneA = $fmcTransaction['fieldData']['alternate_phone_a'];
				$altphoneB = $fmcTransaction['fieldData']['alternate_phone_b'];
				$password = $fmcTransaction['fieldData']['owner_password'];
				$mailinglist = $fmcTransaction['fieldData']['mail_list'];
				
				if ($_POST['match_petaddr'] == '1'){
					$petstreet = $street;
					$petsuburb = $suburb;
					$petstate = $state;
					$petpostcode = $postcode;
					$petsAddressSameAsOwners = 'Yes';
				}
			}
		}
		
	} else {
		// generate cookie id - can be common for all pets OR different and store array in session
		$cookieid = strrev($petname) . uniqid(rand(), true);
	}
	
	
	// Check provided implanting vet is valid.
	if($implanting_vet != '' and $_SESSION['VetID'] != '' and $companyid != ''){
		// Check vet is the head vet of the clinic.
		$aRequest = array();
		$aRequest['_sk_vet_id'] = $_SESSION['VetID'];
		$aRequest['_sk_company_id'] = $companyid;
		$aRequest['vet_main_contact'] = "Yes";

		$fmrVetMain = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);

		if ($fmrVetMain === FALSE || $fmrVetMain["response"]["dataInfo"]["foundCount"] == 0){
			// not found
			$implanting_vet	= '';
		} else {
			// Vet is the head vet. Now check that the provided implanting vet belongs to the clinic.
			$aRequest = array();
			$aRequest['_sk_vet_id'] = $implanting_vet;
			$aRequest['_sk_company_id'] = $companyid;
	
			$fmrVet = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);
	
			if ($fmrVet === FALSE || $fmrVet["response"]["dataInfo"]["foundCount"] == 0){
				// not found
				$implanting_vet	= '';
			} else {
				// Vet does belong to the clinic.
			}
		}
		
	}else{
		$implanting_vet	= '';
	}
	

	// insert into web payment processing table
	$aInsert = array();
	$aInsert['payment_reference_no'] = $paymentref;
	$aInsert['transaction_amount'] = $transactionamount;
	$aInsert['payment_required'] = $paymentrequired;
	$aInsert['transaction_finish'] = $transactioncomplete;
	$aInsert['transaction_start'] = $transactionstart;
	$aInsert['microchip_no'] = $chipno;
	$aInsert['petsafe_no'] = $petsafeno;
	$aInsert['_sk_company_id'] = $companyid;
	$aInsert['owner_title'] = $title;
	$aInsert['owner_first_name'] = $firstname;
	$aInsert['owner_last_name'] = $lastname;
	$aInsert['owner_street'] = $street;
	$aInsert['owner_suburb'] = $suburb;
	$aInsert['owner_state'] = $state;
	$aInsert['owner_postcode'] = $postcode;
	$aInsert['mailing_street'] = $mailstreet;
	$aInsert['mailing_suburb'] = $mailsuburb;
	$aInsert['mailing_state'] = $mailstate;
	$aInsert['mailing_postcode'] = $mailpostcode;
	$aInsert['owner_home_phone'] = fReformatPhones($homephone);
	$aInsert['owner_work_phone'] = fReformatPhones($workphone);
	$aInsert['owner_mobile'] = fReformatPhones($mobile);
	$aInsert['owner_fax'] = fReformatPhones($fax);
	$aInsert['owner_email'] = $email;
	$aInsert['alternate_person_a'] = $altpersonA;
	$aInsert['alternate_person_b'] = $altpersonB;
	$aInsert['alternate_phone_a'] = fReformatPhones($altphoneA);
	$aInsert['alternate_phone_b'] = fReformatPhones($altphoneB);
    
    //auto generate password when it's a breeder's registration
    if(strtoupper($_SESSION['rego_type']) == 'BREEDER'){
        $password = generate_basic_password();
    }
    
	$aInsert['owner_password'] = $password;
	$aInsert['mail_list'] = $mailinglist;
	$aInsert['pet_name'] = $petname;
	$aInsert['pet_type'] = $pettype;
	$aInsert['pet_colour'] = $petcolour;
	$aInsert['pet_breed'] = $petbreed;
	$aInsert['pet_dob'] = $petdob;
	
	$aInsert['pet_implant_date'] = $pet_implant_date;
	$aInsert['pet_distinguishing_marks'] = $pet_dist_marks;
	$aInsert['pet_breeder_id'] = $pet_breeder_id;
	
	$aInsert['pet_sex'] = $petsex;
	$aInsert['pet_desexed'] = $petdesexed;
	$aInsert['pet_savage'] = $petsavage;
	$aInsert['pet_street'] = $petstreet;
	$aInsert['pet_suburb'] = $petsuburb;
	$aInsert['pet_state'] = $petstate;
	$aInsert['pet_postcode'] = $petpostcode;
	$aInsert['pets_address_same_as_owners'] = $petsAddressSameAsOwners;
	
	// May 2017 changed so that main vet can select a different vet to be the implanting vet from a dropdown list, this due to nurses doing most of the registrations in the hospital on behalf of the vets...
	// with this change the nurse can log in using the main vet account and do multiple registrations on behalf of vets without having to log in and log out every time using the individual accounts.
	
	// If no implanting vet was selected, then it defaults to the logged in vet.
	$aInsert['_sk_vet_id'] = $implanting_vet == '' ? $vetid : $implanting_vet;
	//
	
	$aInsert['_sk_member_id'] = $memberid;
	$aInsert['cookie_transaction_id'] = $cookieid;
    $aInsert['rego_type'] = $_SESSION['rego_type'];
	
	if ($_SESSION['cookieid'] != '' and $_SESSION['VetID'] != ''){

	}
        
    /*
    echo '<pre>';
    print_r($aInsert);
    echo '</pre>';
    exit;
    */

	
	$fmrRegister = fFMPerformInsert('petsafe', 'All Fields - Web_Payments', $aInsert);

	// store cookie id in session for multiple rego/pets
	$_SESSION['cookieid'] = $cookieid;

	// ADD TO LOG: submitted new registration
	// add during payment
	if ($_SESSION['VetID'] != '') {
		$aInsert = array();
		$aInsert['_sk_vet_id'] = $_SESSION['VetID'];
		$aInsert['description'] = 'Submitted new registration. Entered by: '.$entered_by;
		$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);

	} else if ($_SESSION['MemberID'] != '') {
		$aInsert = array();
		$aInsert['_sk_member_id'] = $_SESSION['MemberID'];
		$aInsert['description'] = 'Submitted new registration.';
		$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
	} else {
		$aInsert = array();
		$aInsert['description'] = 'Submitted new registration. Chip:'.$chipno;
		$fmrLog = fFMPerformInsert('petsafe', 'Web - Audit', $aInsert);
	}
	

	//override - redirect to interim page - multiple pets/regos
	fRedirect('register_cart.php');
	fCleanup();

	if ($paymentrequired == 'Yes'){
		// if YES (payment needed), redirect to paypal
		fRedirect('register_paypal.php?id=' . $cookieid);
		fCleanup();

	} else {
		// if NO (payment NOT needed)

		// redirect to confirmation
		fRedirect('register_free.php?id=' . $cookieid);
		fCleanup();
	}

?>
