<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('IAFWZDESK_Util')) {

    /**
     * Utility class for handling such as access token management.
     */
    class IAFWZDESK_Util
    {
        private static $option_name = 'iafwzdesk_access_tokens';

        /**
         * Retrieves the access token for a given account ID.
         *
         * @param int $account_id The account ID to retrieve the access token for.
         * @return string|null The decrypted access token, or null if not found.
         */
        public static function getAccessToken($account_id)
        {
            // Retrieve all access tokens stored in the WordPress option.
            $stored_tokens = get_option(self::$option_name);

            // Check if tokens exist and if the requested ID is present.
            if ($stored_tokens && isset($stored_tokens[$account_id])) {
                // Decrypt and return the access token for the specific account ID.
                $iafwzdesk_decoded = base64_decode($stored_tokens[$account_id], true);
                if ($iafwzdesk_decoded === false) {
                    return null;
                }
                return $iafwzdesk_decoded;
            }

            // Return null if the access token is not found.
            return null;
        }

        /**
         * Updates the access token for a given account ID.
         *
         * @param int $account_id The account ID to associate with the access token.
         * @param string $access_token The access token to encrypt and store.
         * @return bool True if the token was successfully updated, false otherwise.
         */
        public static function updateAccessToken($account_id, $access_token)
        {
            // Retrieve existing tokens or initialize an empty array.
            $stored_tokens = get_option(self::$option_name, []);

            // Encrypt the access token and store it with the account ID as the key.
            $stored_tokens[$account_id] = base64_encode($access_token);

            // Update the option with the new or modified access token array.
            return update_option(self::$option_name, $stored_tokens, false);
        }
    }
}
