<?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 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 #
		$fm = \Keysoft\FileMaker\Client::getInstance();   // NEW SYSTEM
		$filters = [];
		$filters[] = "vet_license_number eq '{$getVetID}'";

		if ($getPassword != $gaFM['petsafe']['masterpassword']) {
			$filters[] = "vet_password eq '{$getPassword}'";
		}

		$filters[] = "vet_state eq '{$getState}'";
		$filters[] = "record_type eq 'Vet'";

		$filterString = implode(' and ', $filters);

        $odataQuery = $fm->buildODataQuery([
            'filter' => $filterString,
            'count' => true
        ]);
        $response = $fm->get('Vet', $odataQuery ,$allPages = true );
		
        // check level 3: Implanter #
		if (!$response['success'] || $response["data"]['count'] != 1) {
			// fallback to implanter check, same pattern
			$filters = [];
			$filters[] = "implanter_number eq '{$getVetID}'";
			if ($getPassword != $gaFM['petsafe']['master_password']) {
				$filters[] = "vet_password eq '{$getPassword}'";
			}
			$filters[] = "vet_state eq '{$getState}'";
			$filters[] = "record_type eq 'Vet'";

			$filterString = implode(' and ', $filters);

			$odataQuery = $fm->buildODataQuery([
				'filter' => $filterString,
				'count'  => true
			]);

			$response = $fm->get('Vet', $odataQuery, $allPages = true);

			if (!$response['success'] || $response["data"]['count'] != 1) {
				fRedirect('vetlogin.php?err_code=Incorrect');
				fCleanup();
			}
		}

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

		// 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();

?>