<?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
	*   25/01/2016  Jaime Aramburo       Change pass recovery process from using email address to Chip Number/Member ID (password will be sent to the email address linked to the id provided)
	*   14/11/2019	John Muffett	     Clean up of code to get working with PHP 7
	*   24/07/2025  John Muffett         Reworked for oData API
	*
	*   Copyright Keysoft Pty Ltd 2025
	***********************************************************************************/

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

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

	/********************* Page Defaults *********************/
	fDefaultParameter('user_id', $_POST, '');
	fDefaultParameter('usertype', $_POST, 'owner');
	$getUserId = $_POST['user_id'];
	$userType = $_POST['usertype'];
	$recovery_method = '';
	
	/********************* Page Functions *********************/
    function getMemberByID($id){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
          	'filter' => "_pk_member_id eq ".$id,
			'select' => ['email'],
            'count' => true
        ]);
        $response = $fm->get('Owners', $odataQuery ,$allPages = true );
        
		return $response;
    }
	function getMemberByFullID($id){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
          	'filter' => "cMemberID eq '".$id."'",
			'select' => ['email'],
            'count' => true
        ]);
        $response = $fm->get('Owners', $odataQuery ,$allPages = true );
        
		return $response;
    }
	function getMemberByChip($id){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => "\"Chip No\" eq '".$id."'",
			//'select' => ['email'],
            'count' => true
        ]);
        $response = $fm->get('Chips', $odataQuery ,$allPages = true );
        
		return $response;
    }	
	function getVetByImplanterNumber($id){
        $fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => "\"implanter_number\" eq '".$id."' and vet_email eq '=*'",
			//'select' => ['email'],
            'count' => true
        ]);
        $response = $fm->get('Vets', $odataQuery ,$allPages = true );
        
		return $response;
    }
	function getVetByLicenceNumber($id){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
			'filter' => "\"vet_license_number\" eq '".$id."' and vet_email eq '=*'",
			//'select' => ['email'],
            'count' => true
        ]);
        $response = $fm->get('Vets', $odataQuery ,$allPages = true );
        
		return $response;
    }
	if ($userType == 'owner'){
		// password check for owner/members
        
        //CHECK LEVEL 1 - MEMBER ID (number part only)
		$fmrOwner = getMemberByID(filter_var($getUserId, FILTER_SANITIZE_NUMBER_INT));


		if ($fmrOwner["success"] === FALSE || $fmrOwner["data"]["count"] < 1){

			// Search level 2. (PS prefix + id)
			$fmrOwner = getMemberByFullID($getUserId);

			if ($fmrOwner["success"] === FALSE || $fmrOwner["data"]["count"] < 1){			
				//Level. 3 Member ID doesn't exist. CHECK LEVEL 3 - CHIP NUMBER

				$fmrOwner = getMemberByChip($getUserId);

				//no chip number - redirect
				if ($fmrOwner["success"] === FALSE || $fmrOwner["data"]["count"] < 1){
					fRedirect('memberlogin.php?err_code=InvalidID#forgotpass');
					fCleanup();
				}else{
					$recovery_method = 'chip_number';
				}	
			}else{
				$recovery_method = 'member_id';	
			}
		}else{
            $recovery_method = 'member_id';
        }

        $fmcOwner = $fmrOwner["data"]['value'][0];
   
        //if chip number is valid, get owner details.
        if($recovery_method == 'chip_number'){
            $fmrOwner = getMemberByID($fmcOwner['c_Pet_Owner']);
        }
 
        $fmcOwner = $fmrOwner["data"]['value'][0];
        $lb = "<br/><br/>";
		
		$email_address = trim($fmcOwner['Email']);

		//If no email address return error
		if($email_address == ''){
			fRedirect('memberlogin.php?err_code=InvalidEmail#forgotpass');
			fCleanup();
		}

        //send email containing user id and password to the email address found
        $headers = "From: " . $gaFM['petsafe']['email'] . "\r\n" . "X-Mailer: php";
        $to = $fmcOwner['Email'];
        $subject = "PetSafe password request";
        $body = "<b>PetSafe password request.</b>" . $lb . "Hi " . $fmcOwner['cFullName'] . "," . $lb . "PetSafe Member ID and password details are as follows." . $lb . " Member ID:<b>" . 
        'PS' . $fmcOwner['_pk_member_id'] . "</b><br/> Password:<b>" . $fmcOwner['Password'] . "</b>" . $lb .  "If you did not request your password ignore this message." .
        $lb . "PetSafe.com.au";

		$emailResult = send_mail($subject, $body, $to, array());

        if ($emailResult) {
            // ADD TO LOG: password sent
			$entry = [];
			$entry = [
				"_sk_member_id" => $_SESSION['MemberID'],
				"description" => 'Owner Password sent by email to: ' . $fmcOwner['Email'],
				"is_web_admin_login" => isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0
			];
			makeLogEntry($entry);

            // redirect user to confirmation
            fRedirect('memberlogin.php?err_code=EmailSent#forgotpass');
            fCleanup();
        } else {
            // redirect user to confirmation
            fRedirect('memberlogin.php?err_code=SendError#forgotpass');
            fCleanup();
        }
	} elseif ($userType == 'vet'){
		// password check for vets

        $lb = "<br/><br/>";
        
		$fmrVet = getVetByImplanterNumber($getUserId);

		if ($fmrVet["success"] === FALSE || $fmrVet["data"]["count"] != 1){

			//Implanter ID not valid. CHECK LEVEL 2 - License ID
			$fmrVet = getVetByLicenceNumber($getUserId);
  
			//no license number - redirect
			if ($fmrVet["success"]  === FALSE || $fmrVet["data"]["count"] != 1){
				fRedirect('vetlogin.php?err_code=InvalidID#forgotpass');
				fCleanup();
			}else{
				$recovery_method = 'license_number';
			}
		} else {
			$recovery_method = 'implanter_number';
		}
		
		$fmcVet = $fmrVet["data"]['value'][0];

		// send email
		$headers = "From: " . $gaFM['petsafe']['email'] . "\r\n" . "X-Mailer: php";
		$to = $fmcVet['vet_email'];
		$subject = "PetSafe password request.";
		$body = "Hi " . $fmcVet['title_full_name_c'] . "," . $lb . "Your PetSafe implanter no. and password details are as follows." . $lb 
			. "Implanter No.:<b>" . $fmcVet['implanter_number'] . "</b><br>"
			. "License No.:<b>" . $fmcVet['vet_license_number'] . "</b><br>"
			. "Password:<b>" . $fmcVet['vet_password'] . "</b>" . $lb 
			. "You may also use your Vet License Number as your login ID (if it is registered with PetSafe)."  . $lb 
			.  "If you did not request your password ignore this message." . $lb 
			. "PetSafe.com.au";
			
		if (send_mail($subject, $body, $to, array())) {
			// ADD TO LOG: password sent

			$entry = [];
			$entry = [
				"_sk_member_id" => $_SESSION['MemberID'],
				"description" => 'Vet Password sent by email to: ' . $fmcVet['vet_email'],
				"is_web_admin_login" => isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0
			];
			makeLogEntry($entry);

			// redirect user to confirmation
			fRedirect('vetlogin.php?err_code=EmailSent#forgotpass');
			fCleanup();
		} else {
			// redirect user to confirmation
			fRedirect('vetlogin.php?err_code=SendError#forgotpass');
			fCleanup();
		}

	}

	fCleanup();
?>