<?php
	/***********************************************************************************
	*   Filename : companyvets_delete.php
	*   Description : Removes vet from company
	* 
	* 	Date        Modification By      Description
	*   25/01/2009  Kenneth Ho           Initial Creation
	*   23/08/2022  John Muffett         Rework to support Data API
	*   30/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'] = '..';

    /************ Only allow logged in vets to this area ************/

	if ($_SESSION['LoggedIn'] == 0 or $_SESSION['VetID'] == ''){
		// Redirect
		fRedirect('logout.php');
		fCleanup();
	}
		/********************* Page Functions *********************/
	function isVetMainContact($vetId, $companyID){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $odataQuery = $fm->buildODataQuery([
          	'filter' => "_sk_vet_id eq ".$vetId." and _sk_company_id eq ".$companyID,
            'count' => true
        ]);
        $response = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true );
       
		return $response;
    }

	function deleteVetFromClinic($recid){
		$fm = \Keysoft\FileMaker\Client::getInstance();
        $response = $fm->delete('Company_Vet_Relation', $recid  );
        
		if (!$response['success'])
        {
            // Redirect
			var_dump($response);
			die;
        }

        return $response;
    }

	/********************* Page Defaults *********************/
	fDefaultParameter('companyid', $_GET, '');
	fDefaultParameter('vetid', $_GET, '');
	fDefaultParameter('recid', $_GET, '');

	// get values
	$companyid = $_GET['companyid'];
	$vetid = $_GET['vetid'];
	$recid = $_GET['recid'];

	// check if user is the main vet for this company
	$fmrVet = isVetMainContact( $_SESSION['VetID'] , $companyid);
	$fmcVet = $fmrVet['data']['value'][0];

	if ($fmcVet['vet_main_contact'] != 'Yes' or $companyid == '' or $recid == ''){
		// Redirect if NOT main vet
		fRedirect('companyvets.php?companyid=' . $companyid);
		fCleanup();
	}

	// Do the delete
	$deleteResult = deleteVetFromClinic( $recid );

	// ADD TO LOG: removed vet from company
	$entry = [];
	$entry = [
		"_sk_vet_id" => $_SESSION['VetID'],
		"description" => 'Removed Vet from company. Vet removed is: ' . $vetname,
		"is_web_admin_login" => isset($_SESSION['IsAdminLogin']) ? $_SESSION['IsAdminLogin'] : 0
	];
	makeLogEntry($entry);

	// Redirect
	fRedirect('companyvets.php?companyid=' . $companyid);
	fCleanup();

?>
