<?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
	*   14/11/2019	John Muffett	     Clean up of code to get working with PHP 7
	*   22/08/2022  John Muffett         Reworked for Data API
   	*
	*   Copyright Keysoft Pty Ltd 2022
	***********************************************************************************/

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

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

	$getMemberID = $_POST['memberid'];
	$getPassword = $_POST['password'];
	$getQueryValue = $_POST['query'];
	$getSearchType = $_POST['searchtype'];
	
	/*********************** Processing Start **********************/
	if ($getMemberID == '' or $getPassword == ''){ // Redirect
		fRedirect('memberlogin.php');
		fCleanup();
	}
	else {
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
            'filter' => "_pk_member_id eq ".str_ireplace('PS','',$getMemberID),
            'count' => true
        ]);
        $response = $fm->get('Owners', $odataQuery ,$allPages = true );

		if (!$response['success'] || $response["data"]['count'] != 1) {
			fRedirect('memberlogin.php?err_code=Incorrect');  // No results
			fCleanup();
		}
		else { // valid user - log the user in
			$memberObj = $response["data"]["value"][0];

			// set session vars
			$_SESSION['LoggedIn'] = 1;
			$_SESSION['MemberID'] = $memberObj['_pk_member_id'];
            $_SESSION['cookieid'] = '';
            
			if ($getPassword == $gaFM['petsafe']['master_password']){
				$_SESSION['IsAdminLogin'] = 1; // was an admin login
			}

			$entry = [
				"_sk_member_id" => $_SESSION['MemberID'],
				"description" => 'Logged in as Owner',
				"is_web_admin_login" => isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0
			];
			makeLogEntry($entry);

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



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

fCleanup();

?>