<?php
	/***********************************************************************************
	*   Filename    : vetlogin_submit.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
	*   22/08/2022  John Muffett         Reworked for Data API
	*   29/07/2025  John Muffett         Reworked for oData API
	*
	*   Copyright Keysoft Pty Ltd 2025
	***********************************************************************************/

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

    /********************* Page Defaults *********************/
	fDefaultParameter('vetid', $_POST, '');
	fDefaultParameter('state', $_POST, '');
	fDefaultParameter('password', $_POST, '');
	fDefaultParameter('query', $_POST, '');
	fDefaultParameter('searchtype', $_POST, '');

    $getVetID = $_POST['vetid'];
    $getState = $_POST['state'];
    $getPassword = $_POST['password'];
    $getQueryValue = $_POST['query'];
	$getSearchType = $_POST['searchtype'];

	/********************* Page Functions *********************/
	function makeLogEntry($data){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $response = $fm->create('Audit', $data);
        return;
    }
/*
	function getVetByLicenceNumber($licenceNumber){
        $fm = new FileMakerODataClient(
            'https://petsafe.keysoft.com.au/fmi/odata/v4/KeysoftPetsafe',
            'oData',
            "bWOsV97',?r]iQ9O{}4?"
        );
//-----> need new query builder here
        $odataQuery = $fm->buildODataQuery([
			'filter' => "vet_license_number eq ".$licenceNumber. " and record_type eq 'Vet' and vet_state eq '". $getState. '"',
            'count' => true
        ]);
        $response = $fm->get('Vet', $odataQuery ,$allPages = true , $debug = true);

        return $response;
    }
*/
	/*********************** Processing Start **********************/
	/************ Login Vet ************/

	// check if valid vet
	// if yes, create/refresh session vars
	// if not, reset session and throw user to login page

	if ($getVetID == '' or $getState == '' or $getPassword == ''){
		// Redirect
		fRedirect('vetlogin.php');
		fCleanup();
	} else {
      
		// check level 2: License #
	    $aRequest = array();
		$aRequest['vet_license_number'] = '="' . $getVetID . '"';
            
        // check password if NOT master password
        if ($getPassword != $gaFM['petsafe']['master_password']){
                $aRequest['vet_password'] = '="' . $getPassword . '"';
        }
            
		$aRequest['vet_state'] = '="' . $getState . '"';
		$aRequest['record_type'] = '="Vet"';
//----->
        $fmrLogin = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest);

        // check level 3: Implanter #
		if ($fmrLogin === FALSE || $fmrLogin["response"]["dataInfo"]["foundCount"] != 1){
			$aRequest = array();
			$aRequest['implanter_number'] = '="' . $getVetID . '"';
            
			// check password if NOT master password
			if ($getPassword != $gaFM['petsafe']['master_password']){
				$aRequest['vet_password'] = '="' . $getPassword . '"';
			}

			$aRequest['vet_state'] = '="' . $getState . '"';
			$aRequest['record_type'] = '="Vet"';
//----->			
			$fmrLogin = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest, null, null, FALSE);

			if ($fmrLogin === FALSE || $fmrLogin["response"]["dataInfo"]["foundCount"] != 1){
				// invalid id/pass
				// Redirect
				fRedirect('vetlogin.php?err_code=Incorrect');
				fCleanup();
			}
		}


		// valid user - log the user in
		$fmcLogin = $fmrLogin["response"]["data"][0]["fieldData"];

		// set session vars
		$_SESSION['LoggedIn'] = 1;
		$_SESSION['VetID'] = $fmcLogin['_pk_vet_id'];
		$_SESSION['VetAllowSearch'] = $fmcLogin['ability_to_search'];
        $_SESSION['cookieid'] = '';
        $_SESSION['vetState'] = $getState;
        
		if ($getPassword == $gaFM['petsafe']['master_password']){
			$_SESSION['IsAdminLogin'] = 1; // was an admin login
		}

		// ADD TO LOG: login action
		$entry = [];
		$entry = [
			"_sk_vet_id" => $_SESSION['VetID'],
			"description" => 'Logged in as Vet ',
			"is_web_admin_login" => isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0
		];
		makeLogEntry($entry);

		// redirect to vetarea
		if ($getQueryValue == ''){
			fRedirect('vetarea.php');
			fCleanup();
		}
		else {
			// redirect to search results
			fRedirect('indexsearchresults.php?getquery=' . $getQueryValue . '&searchtype=' . $getSearchType);
			fCleanup();
		}
	}



/************************ Processing End ***********************/

fCleanup();

?>