<?php
/**
 * Class GSCFRMDFORM_Lib
 *
 * This class handles interactions with the Google Sheets API.
 *
 * @package GSheetConnector Formidable Forms
 * @since 1.0
 */

if (!defined('ABSPATH')) {
	exit;
}

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';

/**
 * GSCFRMDFORM_Lib Class
 *
 * @since 1.0
 */

class GSCFRMDFORM_Lib
{

	/**
	 * The authentication token for accessing the spreadsheet.
	 *
	 * @var string
	 */
	private $token;

	/**
	 * The spreadsheet object associated with this manager.
	 *
	 * @var Spreadsheet
	 */
	private $spreadsheet;

	/**
	 * The worksheet object associated with this manager.
	 *
	 * @var Worksheet
	 */
	private $worksheet;


	/**
	 * The single instance of the GIVEWPGSC_googlesheet class.
	 *
	 * @var GIVEWPGSC_googlesheet|null
	 * @since 1.0
	 */
	private static $instance;

	/**
	 * Constructor method for the GIVEWPGSC_googlesheet class.
	 *
	 * Initialize necessary properties and setup actions.
	 *
	 * @since 1.0
	 */
	public function __construct()
	{
	}

	/**
	 * Set the instance of the Google_Client for the GIVEWPGSC_googlesheet class.
	 *
	 * @param Google_Client|null $instance The Google_Client instance to set, or null to clear the instance.
	 *
	 * @since 1.0
	 */
	public static function setInstance(Google_Client $instance = null)
	{
		self::$instance = $instance;
	}

	/**
	 * Get the instance of the Google_Client for the GIVEWPGSC_googlesheet class.
	 *
	 * @return Google_Client The Google_Client instance.
	 *
	 * @throws LogicException If the instance is null.
	 *
	 * @since 1.0
	 */
	public static function getInstance()
	{
		if (is_null(self::$instance)) {
			throw new LogicException('Invalid Client');
		}

		return self::$instance;
	}

	/**
	 * Perform authentication for the Google Sheets API.
	 *
	 * @return string|false The authentication URL on success, or false on failure.
	 */
	public function auth()
	{

		$maunal_setting = get_option('gscfrmdform_manual_setting') != "" ? get_option('gscfrmdform_manual_setting') : '0';

		if ($maunal_setting == '1')
			$tokenData = json_decode(get_option('gscfrmdform_token_manual'), true);
		else
			$tokenData = json_decode(get_option('frmgsc_gs_token'), true);


		if (!isset($tokenData['refresh_token']) || empty($tokenData['refresh_token'])) {
			throw new LogicException("Auth, Invalid OAuth2 access token");
			exit();
		}

		try {
			$client = new Google_Client();

			if ($maunal_setting == '1') {
				$gscfrmdform_client_id = get_option('gscfrmdform_client_id');
				$gscfrmdform_secret_id = get_option('gscfrmdform_secret_id');
				$client->setClientId($gscfrmdform_client_id);
				$client->setClientSecret($gscfrmdform_secret_id);

			} else {
				// Fetch API creds
				if (is_multisite()) {
					// Fetch API creds
					$api_creds = get_site_option('formidablegsc_api_creds');
				} else {
					// Fetch API creds
					$api_creds = get_option('formidablegsc_api_creds');
				}
				$newClientSecret = get_option('is_new_client_secret_frmgsc');
				$clientId = ($newClientSecret == 1) ? $api_creds['client_id_web'] : $api_creds['client_id_desk'];
				$clientSecret = ($newClientSecret == 1) ? $api_creds['client_secret_web'] : $api_creds['client_secret_desk'];

				$client->setClientId($clientId);
				$client->setClientSecret($clientSecret);
			}

			$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
			$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
			$client->refreshToken($tokenData['refresh_token']);
			$client->setAccessType('offline');

			if ($maunal_setting == '1')
				GSCFRMDFORM_Lib::updateToken_manual($tokenData);
			else
				GSCFRMDFORM_Lib::updateToken($tokenData);

			self::setInstance($client);
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Auth, Error fetching OAuth2 access token, message: ' . $e->getMessage());
			exit();
		}
	}

	/**
	 * Update the Google Sheets API token manually.
	 *
	 * @param array $tokenData The token data to be updated.
	 *  Example structure:
	 *  array(
	 *      'access_token'  => 'your_access_token',
	 *      'refresh_token' => 'your_refresh_token',
	 *      'expires_in'    => 'token_expiration_time',
	 *  )
	 *
	 * @return bool True on success, false on failure.
	 */
	public static function updateToken_manual($tokenData)
	{
		$expires_in = isset($tokenData['expires_in']) ? intval($tokenData['expires_in']) : 0;
		$tokenData['expire'] = time() + $expires_in;
		try {

			if (isset($tokenData['scope'])) {
				$permission = explode(' ', $tokenData['scope']);
				if ((in_array('https://www.googleapis.com/auth/drive.metadata.readonly', $permission)) && (in_array('https://www.googleapis.com/auth/spreadsheets', $permission))) {
					update_option('gscfrmdform_verify', 'valid');
				} else {
					update_option('gscfrmdform_verify', 'invalid-auth');
				}
			}
			$tokenJson = json_encode($tokenData);
			update_option('gscfrmdform_token_manual', $tokenJson);
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Auth, Error fetching OAuth2 access token, message:  ' . $e->getMessage());

			exit();
		}
	}

	/**
	 * Perform pre-authorization manually for the Google Sheets API.
	 *
	 * @param string $access_code The access code obtained during the authorization process.
	 * @param string $client_id   The Client ID associated with your Google API project.
	 * @param string $secret_id   The Client Secret associated with your Google API project.
	 * @param string $redirect_url The redirect URL used during the authorization process.
	 *
	 * @return array|false An array containing the token data (access_token, refresh_token, expires_in)
	 *                    on success, or false on failure.
	 */
	public static function preauth_manual($access_code, $client_id, $secret_id, $redirect_url)
	{
		$client = new Google_Client();
		$client->setClientId($client_id);
		$client->setClientSecret($secret_id);
		$client->setRedirectUri($redirect_url);
		$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
		$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
		$client->setAccessType('offline');
		$client->fetchAccessTokenWithAuthCode($access_code);
		$tokenData = $client->getAccessToken();
		self::updateToken_manual($tokenData);
	}

	/**
	 * Perform pre-authorization manually for the Google Sheets API.
	 *
	 * @param string $access_code The access code obtained during the authorization process.
	 * @param string $client_id   The Client ID associated with your Google API project.
	 * @param string $secret_id   The Client Secret associated with your Google API project.
	 * @param string $redirect_url The redirect URL used during the authorization process.
	 *
	 * @return array|false An array containing the token data (access_token, refresh_token, expires_in)
	 *                    on success, or false on failure.
	 */
	public static function preauth($access_code)
	{
		if (is_multisite()) {
			// Fetch API creds
			$api_creds = get_site_option('formidablegsc_api_creds');
		} else {
			// Fetch API creds
			$api_creds = get_option('formidablegsc_api_creds');
		}
		$newClientSecret = get_option('is_new_client_secret_frmgsc');
		$clientId = ($newClientSecret == 1) ? $api_creds['client_id_web'] : $api_creds['client_id_desk'];
		$clientSecret = ($newClientSecret == 1) ? $api_creds['client_secret_web'] : $api_creds['client_secret_desk'];
		$client = new Google_Client();

		$client->setClientId($clientId);
		$client->setClientSecret($clientSecret);

		// $client->setClientId(frmgsc_googlesheet::clientId);
		// $client->setClientSecret(frmgsc_googlesheet::clientSecret);
		// $client->setRedirectUri(frmgsc_googlesheet::redirect);
		$client->setRedirectUri('https://oauth.gsheetconnector.com');
		$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
		$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
		$client->setAccessType('offline');
		$client->fetchAccessTokenWithAuthCode($access_code);
		$tokenData = $client->getAccessToken();

		self::updateToken($tokenData);
	}

	/**
	 *  Updates the token data used for authentication.
	 *  @param array $tokenData The token data to be updated.
	 *  @return void
	 */
	public static function updateToken($tokenData)
	{
		$expires_in = isset($tokenData['expires_in']) ? intval($tokenData['expires_in']) : 0;
		$tokenData['expire'] = time() + $expires_in;
		try {

			if (isset($tokenData['scope'])) {
				$permission = explode(" ", $tokenData['scope']);
				if ((in_array("https://www.googleapis.com/auth/drive.metadata.readonly", $permission)) && (in_array("https://www.googleapis.com/auth/spreadsheets", $permission))) {
					update_option('gscfrmdform_verify', 'valid');
				} else {

					update_option('gscfrmdform_verify', 'invalid-auth');
				}
			}

			$tokenJson = json_encode($tokenData);
			update_option('frmgsc_gs_token', $tokenJson);

			// ==============permission checking ==========
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Auth, Error fetching OAuth2 access token, message: ' . $e->getMessage());

			exit();
		}
	}

	/**
	 * Generate token for the user and refresh the token if it's expired.
	 *
	 * @param int $flag Optional flag for return behavior on error.
	 * @param string $gscff_clientId Google Client ID.
	 * @param string $gscff_clientSecert Google Client Secret.
	 *
	 * @return Google_Client|string|false Google Client object or error message or false.
	 */
	public static function getClient_auth($flag = 0, $gscff_clientId = '', $gscff_clientSecert = '')
	{
		$gscff_client = new Google_Client();
		$gscff_client->setApplicationName('Manage Formidable Forms with Google Spreadsheet');

		// Set required scopes.
		$gscff_client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
		$gscff_client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
		$gscff_client->addScope(Google_Service_Drive::DRIVE_FILE); // For file uploads
		$gscff_client->addScope(Google_Service_Sheets::SPREADSHEETS);
		$gscff_client->addScope('https://www.googleapis.com/auth/userinfo.email');

		// Set client credentials.
		$gscff_client->setClientId($gscff_clientId);
		$gscff_client->setClientSecret($gscff_clientSecert);
		$gscff_client->setRedirectUri(esc_html(admin_url('admin.php?page=formidable-form-google-sheet-config')));
		$gscff_client->setAccessType('offline');
		$gscff_client->setApprovalPrompt('force');

		try {
			// Check for existing auth token or access token
			if (empty($gscff_auth_token)) {
				return $gscff_client->createAuthUrl();
			}

			if (!empty($gscff_gscff_accessToken)) {
				$gscff_accessToken = json_decode($gscff_gscff_accessToken, true);
			} elseif (empty($gscff_auth_token)) {
				return $gscff_client->createAuthUrl();
			}

			$gscff_client->setAccessToken($gscff_accessToken);

			// Refresh the token if expired
			if ($gscff_client->isAccessTokenExpired()) {
				$gscff_refreshTokenSaved = $gscff_client->getRefreshToken();

				// Fetch new token
				$gscff_client->fetchAccessTokenWithRefreshToken($gscff_refreshTokenSaved);
				$gscff_accessTokenUpdated = $gscff_client->getAccessToken();

				// Re-attach refresh token
				$gscff_accessTokenUpdated['refresh_token'] = $gscff_refreshTokenSaved;

				// Save and set the updated access token
				gscff::gscff_update_option('ffsheets_google_accessToken', json_encode($gscff_accessTokenUpdated));
				$gscff_accessToken = json_decode(json_encode($gscff_accessTokenUpdated), true);
				$gscff_client->setAccessToken($gscff_accessToken);
			}
		} catch (Exception $e) {
			// Log the error message to file
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Auth, Error fetching OAuth2 access token, message: ' . $e->getMessage());

			if ($flag) {
				return $e->getMessage(); // return error message if flag set
			} else {
				return false; // else return false
			}
		}

		return $gscff_client;
	}


	/**
	 * Set the ID of the Google Sheet for the instance.
	 *
	 * @since 1.0
	 *
	 * @param string $id The ID of the Google Sheet.
	 */
	public function setSpreadsheetId($id)
	{
		$this->spreadsheet = $id;
	}

	/**
	 * Get the ID of the Google Sheet associated with the instance.
	 *
	 * @since 1.0
	 *
	 * @return string The ID of the Google Sheet.
	 */
	public function getSpreadsheetId()
	{

		return $this->spreadsheet;
	}

	/**
	 * Set the ID of the worksheet (tab) for the instance.
	 *
	 * @since 1.0
	 *
	 * @param string $id The ID of the worksheet.
	 */
	public function setWorkTabId($id)
	{
		$this->worksheet = $id;
	}

	/**
	 * Get the ID of the worksheet (tab) associated with the instance.
	 *
	 * @since 1.0
	 *
	 * @return string The ID of the worksheet.
	 */
	public function getWorkTabId()
	{
		return $this->worksheet;
	}

	/**
	 * Add a row of data to the Google Sheet.
	 *
	 * @since 1.0
	 *
	 * @param array $data The data to be added as a row.
	 */
	public function add_row($data)
	{
		try {
			$client = self::getInstance();
			$service = new Google_Service_Sheets($client);
			$spreadsheetId = $this->getSpreadsheetId();
			$work_sheets = $service->spreadsheets->get($spreadsheetId);

			if (!empty($work_sheets) && !empty($data)) {
				foreach ($work_sheets as $sheet) {
					$properties = $sheet->getProperties();

					$sheet_id = $properties->getSheetId();
					$worksheet_id = $this->getWorkTabId();

					if ($sheet_id == $worksheet_id) {
						$worksheet_id = $properties->getTitle();
						$worksheetCell = $service->spreadsheets_values->get($spreadsheetId, $worksheet_id . '!1:1');
						$insert_data = array();
						if (isset($worksheetCell->values[0])) {
							$insert_data_index = 0;
							foreach ($worksheetCell->values[0] as $k => $name) {
								if ($insert_data_index == 0) {
									if (isset($data[$name]) && $data[$name] != '') {
										$insert_data[] = $data[$name];
									} else {
										$insert_data[] = '';
									}
								} elseif (isset($data[$name]) && $data[$name] != '') {
									$insert_data[] = $data[$name];
								} else {
									$insert_data[] = '';
								}
								++$insert_data_index;
							}
						}
						$range_new = $worksheet_id;

						// Create the value range Object
						$valueRange = new Google_Service_Sheets_ValueRange();

						// set values of inserted data
						$valueRange->setValues(array('values' => $insert_data));

						// Add two values
						// Then you need to add configuration
						$conf = array('valueInputOption' => 'USER_ENTERED');

						// append the spreadsheet(add new row in the sheet)
						$result = $service->spreadsheets_values->append($spreadsheetId, $range_new, $valueRange, $conf);
					}
				}
			}
		} catch (Exception $e) {
			// Log the error message to file
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file($e->getMessage());
			return null;
			exit();
		}
	}

	public function add_row_feed($spreadsheet_id, $sheet_title, $data, $append = true)
{
    try {
        $client = self::getInstance();
        $service = new Google_Service_Sheets($client);
        $work_sheets = $service->spreadsheets->get($spreadsheet_id)->getSheets();

        if (!empty($work_sheets) && !empty($data)) {
            foreach ($work_sheets as $sheet) {
                $properties = $sheet->getProperties();
                $sheet_id = $properties->getSheetId();
                $worksheet_id = $this->getWorkTabId();

                if ($sheet_id == $worksheet_id) {

                    // Fetch all data from sheet
                    $allData = $service->spreadsheets_values->get($spreadsheet_id, $sheet_title)->getValues();
                    if (empty($allData) || !isset($allData[0])) {
                        Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('No headers found in the sheet.');
                        return;
                    }

                    $headers = $allData[0];
                    $insert_data = [];

                    // Map the $data to the headers
                    foreach ($headers as $header) {
                        $insert_data[] = isset($data[$header]) ? $data[$header] : '';
                    }

                    // Find Entry ID column
                    $entryIdColumnIndex = array_search('Entry ID', $headers);
                    if ($entryIdColumnIndex === false) {
                        Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Entry ID column not found.');
                        return;
                    }

                    // Check for existing Entry ID
                    $foundRow = null;
                    foreach ($allData as $rowIndex => $row) {
                        if ($rowIndex === 0) continue; // skip header
                        if (isset($row[$entryIdColumnIndex]) && $row[$entryIdColumnIndex] == $data['Entry ID']) {
                            $foundRow = $rowIndex + 1; // Google Sheets rows are 1-indexed
                            break;
                        }
                    }

                    // Prepare value range
                    $valueRange = new Google_Service_Sheets_ValueRange();
                    $valueRange->setValues([$insert_data]);
                    $conf = ['valueInputOption' => 'USER_ENTERED'];

                    if ($foundRow) {
                        // Update existing row
                        $range = $sheet_title . '!' . $foundRow . ':' . $foundRow;
                        $response = $service->spreadsheets_values->update($spreadsheet_id, $range, $valueRange, $conf);
                        // Debug log
                        // error_log('Updated row: ' . $foundRow);
                    } else {
                        // Append as new row
                        $range = $sheet_title . '!A1';
                        $response = $service->spreadsheets_values->append($spreadsheet_id, $range, $valueRange, $conf);
                        // Debug log
                        // error_log('Appended new row.');
                    }
                }
            }
        }
    } catch (Exception $e) {
        Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Error appending/updating data in Google Sheets: "' . $e->getMessage() . '"');
        return null;
    }
}
public function update_row_by_entry_id($spreadsheet_id, $tab_name, $row_data) {
     $client = self::getInstance();
    $service = new Google_Service_Sheets($client);

    // Fetch all existing rows
    $range = $tab_name . '!A:Z'; // Adjust columns as needed
    $response = $service->spreadsheets_values->get($spreadsheet_id, $range);
    $values = $response->getValues() ?? [];

    // Entry ID is assumed to be the first column
    $entry_id = $row_data[0];
    $row_index = null;

    foreach ($values as $index => $row) {
        if (isset($row[0]) && $row[0] == $entry_id) {
            $row_index = $index + 1; // Google Sheets rows start at 1
            break;
        }
    }

    // if ($row_index === null) {
    //     // Entry ID not found → optionally throw exception or log
    //     throw new Exception("Entry ID {$entry_id} not found in the sheet.");
    // }

    // Update (replace) the row
    $update_range = $tab_name . '!A' . $row_index;
    $body = new Google_Service_Sheets_ValueRange([
        'values' => [$row_data]
    ]);
    $params = ['valueInputOption' => 'RAW'];

    $service->spreadsheets_values->update($spreadsheet_id, $update_range, $body, $params);

    // Optional: log success
    Gscfrmdform_Connector_Utility::frmgsc_debug_log_file("Entry ID {$entry_id} updated in Google Sheet {$tab_name}.");
}

	/**
	 * Get a list of available Google Sheets.
	 *
	 * @since 1.0
	 *
	 * @return array An array of available Google Sheets.
	 */
	public function get_spreadsheets()
	{
		$all_sheets = array();
		try {
			$client = self::getInstance();

			$service = new Google_Service_Drive($client);

			$optParams = array(
				'q' => "mimeType='application/vnd.google-apps.spreadsheet'",
			);
			$results = $service->files->listFiles($optParams);
			foreach ($results->files as $spreadsheet) {
				if (isset($spreadsheet['kind']) && $spreadsheet['kind'] == 'drive#file') {
					$all_sheets[] = array(
						'id' => $spreadsheet['id'],
						'title' => $spreadsheet['name'],
					);
				}
			}
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file($e->getMessage());
			return null;
			exit();
		}
		return $all_sheets;
	}

	/**
	 * Get a list of available tabs in a Google Sheet.
	 *
	 * @since 1.0
	 *
	 * @param string $spreadsheet_id The ID of the Google Sheet.
	 * @return array An array of available tabs in the specified Google Sheet.
	 */
	public function get_worktabs($spreadsheet_id)
	{

		$work_tabs_list = array();
		try {
			$client = self::getInstance();
			$service = new Google_Service_Sheets($client);
			$work_sheets = $service->spreadsheets->get($spreadsheet_id);

			foreach ($work_sheets as $sheet) {
				$properties = $sheet->getProperties();
				$work_tabs_list[] = array(
					'id' => $properties->getSheetId(),
					'title' => $properties->getTitle(),
				);
			}
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file($e->getMessage());
			return null;
			exit();
		}

		return $work_tabs_list;
	}

	/**
	 * GFGSC_googlesheet::gsheet_get_google_account
	 * Get Google Account
	 *
	 * @since 3.1
	 * @retun $user
	 **/
	public function gsheet_get_google_account()
	{

		try {
			$client = $this->getInstance();

			if (!$client) {
				return false;
			}

			$service = new Google_Service_Oauth2($client);
			$user = $service->userinfo->get();
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Something Wrong : - ' . $e->getMessage());
			exit();
		}

		return $user;
	}

	/**
	 * GFGSC_googlesheet::gsheet_print_google_account_email
	 * Get Google Account Email (automatic method)
	 *
	 * @since 3.1
	 * @return string|false Google account email or false on failure.
	 */
	public function gsheet_print_google_account_email()
	{
		try {
			// Authenticate and fetch Google account email
			$google_sheet = new GSCFRMDFORM_Lib();
			$google_sheet->auth();

			$email = $google_sheet->gsheet_get_google_account_email();

			// Save to WordPress options for reuse
			update_option('gscfrmd_email_account', $email);

			return $email;
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Something Wrong : - ' . $e->getMessage());
			return false;
		}
	}

	/**
	 * GFGSC_googlesheet::gsheet_print_google_account_email_manual
	 * Get Google Account Email (manual method)
	 *
	 * @since 3.1
	 * @return string|false Google account email or false on failure.
	 */
	public function gsheet_print_google_account_email_manual()
	{
		try {
			// Authenticate and fetch Google account email
			$google_sheet = new GSCFRMDFORM_Lib();
			$google_sheet->auth();

			$email = $google_sheet->gsheet_get_google_account_email();

			// Save manually authenticated email to options
			update_option('frmgsc_email_account_manual', $email);

			return $email;
		} catch (Exception $e) {
			Gscfrmdform_Connector_Free_Utility::frmgsc_debug_log_file('Something Wrong : - ' . $e->getMessage());
			return false;
		}
	}

	/**
	 * GSCFRMDFORM_Lib::gsheet_get_google_account_email
	 * Get only the email address from authenticated Google account
	 *
	 * @return string Google account email, or empty string on failure.
	 */
	public function gsheet_get_google_account_email()
	{
		$google_account = $this->gsheet_get_google_account();

		if ($google_account) {
			return $google_account->email;
		} else {
			return "";
		}
	}

	/**
	 * Revoke the Google Sheets API token for auto/manual integration.
	 *
	 * @param string $access_code JSON-encoded token string.
	 */
	public static function revokeToken_auto_manual($access_code)
	{
		$clientId = get_option('gscfrmdform_client_id');
		$clientSecret = get_option('gscfrmdform_secret_id');

		if (!empty($clientId) && !empty($clientSecret)) {
			$client = new Google_Client();
			$client->setClientId($clientId);
			$client->setClientSecret($clientSecret);

			$tokendecode = json_decode($access_code);
			if (!empty($tokendecode)) {
				$token = isset($tokendecode->access_token) ? $tokendecode->access_token : '';
				if (!empty($token)) {
					$client->revokeToken($token);
				}
			}
		}
	}

	/**
	 * Revoke token for auto integration with multisite/client-type detection.
	 *
	 * @param string $access_code JSON-encoded token string.
	 */
	public static function revokeToken_auto($access_code)
	{
		// Fetch API credentials based on site type
		if (is_multisite()) {
			$api_creds = get_site_option('formidablegsc_api_creds');
		} else {
			$api_creds = get_option('formidablegsc_api_creds');
		}

		$newClientSecret = get_option('is_new_client_secret_frmgsc');

		// Determine client ID/Secret based on selected app type
		$clientId = ($newClientSecret == 1) ? $api_creds['client_id_web'] : $api_creds['client_id_desk'];
		$clientSecret = ($newClientSecret == 1) ? $api_creds['client_secret_web'] : $api_creds['client_secret_desk'];

		$client = new Google_Client();
		$client->setClientId($clientId);
		$client->setClientSecret($clientSecret);

		$tokendecode = json_decode($access_code);
		if (!empty($tokendecode)) {
			$token = isset($tokendecode->access_token) ? $tokendecode->access_token : '';
			if (!empty($token)) {
				$client->revokeToken($token);
			}
		}
	}


}
