<?php

defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('STD_Library')) {

    class STD_Library {

        /**
         * Exit for unauthorized access
         *
         * @since 1.0.0
         */
        function permission_denied() {
            die('No script kiddies please!!');
        }

        /**
         * Prints array in the pre format
         *
         * @param array $array
         * @since 1.0.0
         */
        function print_array($array) {
            echo "<pre>";
            print_r($array);
            echo "</pre>";
        }

        /**
         * Sanitizes Multi Dimensional Array
         * @param array $array
         * @param array $sanitize_rule
         * @return array
         *
         * @since 1.0.0
         */
        function sanitize_array($array = array(), $sanitize_rule = array()) {
            if (!is_array($array) || count($array) == 0) {
                return array();
            }

            foreach ($array as $k => $v) {
                if (!is_array($v)) {

                    $default_sanitize_rule = (is_numeric($k)) ? 'html' : 'text';
                    $sanitize_type = isset($sanitize_rule[$k]) ? $sanitize_rule[$k] : $default_sanitize_rule;
                    $array[$k] = $this->sanitize_value($v, $sanitize_type);
                }
                if (is_array($v)) {
                    $array[$k] = $this->sanitize_array($v, $sanitize_rule);
                }
            }

            return $array;
        }

        /**
         * Sanitizes Value
         *
         * @param type $value
         * @param type $sanitize_type
         * @return string
         *
         * @since 1.0.0
         */
        function sanitize_value($value = '', $sanitize_type = 'text') {
            switch ($sanitize_type) {
                case 'html':
                    $allowed_html = wp_kses_allowed_html('post');
                    return $this->sanitize_html($value);
                    break;
                case 'to_br':
                    return $this->sanitize_escaping_linebreaks($value);
                    break;
                case 'none':
                    return $value;
                    break;
                default:
                    return sanitize_text_field($value);
                    break;
            }
        }

        /**
         * Check if alias has already been used or not
         *
         * @param string $form_alias
         * @param int $form_id
         *
         * @since 1.0.0
         */
        function is_alias_available($form_alias, $form_id = 0) {
            $form_table = STD_FORM_TABLE;
            global $wpdb;
            if (empty($form_id)) {
                $alias_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $form_table WHERE form_alias like %s", $form_alias));
            } else {
                $alias_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $form_table WHERE form_alias like %s  AND form_id !=%d", $form_alias, $form_id));
            }
            if ($alias_count == 0) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * Ajax nonce verification for ajax in admin
         *
         * @return bolean
         * @since 1.0.0
         */
        function admin_ajax_nonce_verify() {
            if (!empty($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'std_ajax_nonce')) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * Ajax nonce verification for ajax in frontend
         *
         * @return bolean
         * @since 1.0.0
         */
        function ajax_nonce_verify() {
            if (!empty($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'std_frontend_ajax_nonce')) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * Fetches the form row from form table
         *
         * @global object $wpdb
         * @param int $form_id
         * @return object
         */
        public static function get_form_row_by_id($form_id) {
            global $wpdb;
            $table = STD_FORM_TABLE;
            $form_row = $wpdb->get_row($wpdb->prepare("select * from $table where form_id = %d", $form_id));
            return $form_row;
        }

        /**
         * Returns the shortcode from alias
         *
         * @param string $alias
         * @return string
         *
         * @since 1.0.0
         */
        function generate_shortcode($alias) {
            $shortcode = "[std alias='$alias' ]";
            return $shortcode;
        }

        /**
         * Returns the default email message
         *
         * @return string
         *
         * @since 1.0.0
         */
        function get_default_email_message() {
            $default_email_message = esc_html__(sprintf('Hello There,

Thank you for subscribing in our %s website. Please download the file from below link:

#download_link

Thank you', esc_attr(get_bloginfo('name'))), 'subscribe-to-download');
            return $default_email_message;
        }

        /**
         * Returns the default download notification email message
         *
         * @return string
         *
         * @since 1.0.7
         */
        function get_default_download_notification_message() {
            $default_email_message = esc_html__(sprintf('Hello There,

Your file has been downloaded. Details below:

Download File Name: #download_file
Email: #email

Thank you', esc_attr(get_bloginfo('name'))), 'subscribe-to-download');
            return $default_email_message;
        }
        /**
         * Returns the default admin notification email message
         *
         * @return string
         *
         * @since 1.0.7
         */
        function get_default_admin_notification_message() {
            $default_email_message = esc_html__(sprintf('Hello There,

You have a new subscriber in you %s website. Details below:

Name: #name
Email: #email

Thank you', esc_attr(get_bloginfo('name'))), 'subscribe-to-download');
            return $default_email_message;
        }

        /**
         * Returns the default confirmation email message
         *
         * @return string
         *
         * @since 1.0.0
         */
        function get_default_confirmation_email_message() {
            $default_email_message = esc_html__(sprintf('Hello There,

Thank you for subscribing in our %s website. Please confirm your subscription from below below link:

#confirmation_link

You will receive the download link as soon as you will confirm the subscription.

Thank you', esc_attr(get_bloginfo('name'))), 'subscribe-to-download');
            return $default_email_message;
        }

        /**
         * Sanitizes the content by bypassing allowed html
         *
         * @param string $text
         * @return string
         *
         * @since 1.0.0
         */
        function sanitize_html($text, $br_omit = false) {
            $allowed_html = wp_kses_allowed_html('post');
            if ($br_omit) {
                unset($allowed_html['br']);
            }
            return wp_kses($text, $allowed_html);
        }

        /**
         * Sanitizes field by converting line breaks to <br /> tags
         *
         * @since 1.0.0
         *
         * @return string $text
         */
        function sanitize_escaping_linebreaks($text) {
            $text = $this->sanitize_html($text, true);
            $text = implode("<br \>", explode("\n", $text));
            return $text;
        }

        /**
         * Outputs by converting <Br/> tags into line breaks
         *
         * @since 1.0.0
         *
         * @return string $text
         */
        function output_converting_br($text) {

            $text = implode("\n", explode("<br \>", $text));
            $text = $this->sanitize_html($text, true);
            return $text;
        }

        /**
         * Gets the form row as per the alias
         *
         * @param string $alias
         *
         * @return object
         *
         * @since 1.0.0
         */
        function get_form_row_by_alias($alias) {
            global $wpdb;
            $form_table = STD_FORM_TABLE;
            $form_row = $wpdb->get_row("select * from $form_table where form_alias = '$alias'");
            return $form_row;
        }

        /**
         * Gets the subscriber row from email
         *
         * @param string $email
         *
         * @return object/boolean
         *
         * @since 1.0.0
         */
        function get_subscriber_row_by_email($email, $form_alias) {
            global $wpdb;
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            $subscriber_row = $wpdb->get_row($wpdb->prepare("select * from $subscriber_table where subscriber_email = %s and subscriber_form_alias = %s", $email, $form_alias));
            return $subscriber_row;
        }

        /**
         * Returns the default From Email
         *
         * @return string
         *
         * @since 1.0.0
         */
        function get_default_from_email() {
            $site_url = home_url();
            $find_h = '#^http(s)?://#';
            $find_w = '/^www\./';
            $replace = '';
            $output = preg_replace($find_h, $replace, $site_url);
            $output = preg_replace($find_w, $replace, $output);
            return 'noreply@' . $output;
        }

        /**
         * Generates a unique encryption key
         *
         * @return string
         *
         * @since 1.0.0
         */
        function generate_encryption_key() {
            $current_date_time = date('Y-m-d H:i:s');
            $encryption_key = md5($current_date_time);
            return $encryption_key;
        }

        /**
         * Returns download Path
         *
         * @global object $wpdb
         * @param string $encryption_key
         * @return string/boolean
         *
         * @since 1.0.0
         */
        function get_download_path($encryption_key, $form_alias = '') {
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            global $wpdb;
            if (empty($form_alias)) {
                $subscriber_row = $wpdb->get_row($wpdb->prepare("select * from $subscriber_table where subscriber_encryption_key = %s", $encryption_key));
                if (empty($subscriber_row)) {
                    // if encryption key is invalid
                    return false;
                }
                $form_alias = $subscriber_row->subscriber_form_alias;
            }
            $form_row = $this->get_form_row_by_alias($form_alias);
            if (empty($form_row)) {
                //if form has been deleted or not available in db
                return false;
            }
            $form_details = maybe_unserialize($form_row->form_details);
            if (empty($form_details['general']['download_file_id'])) {
                // If download file is not available in the settings
                return false;
            }
            $attachment_path = get_attached_file(intval($form_details['general']['download_file_id']));
            return $attachment_path;
        }

        /**
         * Returns subscriber email by encryption key
         *
         * @global object $wpdb
         * @param string $encryption_key
         * @return string/boolean
         *
         * @since 1.0.0
         */
        function get_email_by_encryption_key($encryption_key) {
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            global $wpdb;
            $subscriber_row = $wpdb->get_row("select * from $subscriber_table where subscriber_encryption_key = '$encryption_key'");
            if (empty($subscriber_row)) {
                // if encryption key is inavalid
                return false;
            }
            return $subscriber_row->subscriber_email;
        }

        /**
         * Returns the file name from download URL
         *
         * @param string $url
         * @return string
         *
         * @since 1.0.0
         */
        function get_file_name_from_url($url) {
            $url = untrailingslashit($url);
            $url_array = explode('/', $url);
            $file_name = end($url_array);
            return $file_name;
        }

        /**
         * Copy form
         *
         * @param int $form_id
         * @return boolean
         *
         * @since 1.0.0
         */
        function copy_form($form_id) {
            global $wpdb;
            $form_row = $this->get_form_row_by_id($form_id);
            $form_alias = $form_row->form_alias . '_' . rand(1111, 9999);
            $copy_check = $wpdb->insert(
                STD_FORM_TABLE,
                array(
                    'form_title' => $form_row->form_title . ' - Copy',
                    'form_alias' => $form_alias,
                    'form_details' => $form_row->form_details,
                    'form_status' => $form_row->form_status
                ),
                array('%s', '%s', '%s', '%d')
            );
            return $copy_check;
        }

        function check_if_already_subscribed($encryption_key) {
            $encryption_key = sanitize_text_field($encryption_key);
            global $wpdb;
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            $subscriber_count = $wpdb->get_var("SELECT COUNT(*) FROM $subscriber_table WHERE subscriber_encryption_key like '$encryption_key'");
            if ($subscriber_count == 0) {
                return false;
            } else {
                return true;
            }
        }

        /**
         * Prints Display None
         *
         * @param string $parameter1
         * @param string $parameter2
         *
         * @since 1.0.0
         */
        function display_none($parameter1, $parameter2) {
            if ($parameter1 != $parameter2) {
                echo 'style="display:none"';
            }
        }

        function get_mc_headers($api_key) {
            global $wp_version;

            $headers = array();
            $headers['Authorization'] = 'Basic ' . base64_encode('std:' . $api_key);
            $headers['Accept'] = 'application/json';
            $headers['Content-Type'] = 'application/json';
            $headers['User-Agent'] = 'std/' . STD_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url');



            return $headers;
        }
        function get_ml_headers($api_key) {
            global $wp_version;

            $headers = array();
            $headers['X-MailerLite-ApiKey'] =  $api_key;
            $headers['Accept'] = 'application/json';
            $headers['Content-Type'] = 'application/json';
            $headers['User-Agent'] = 'std/' . STD_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url');



            return $headers;
        }
        function get_sib_headers($api_key) {
            global $wp_version;

            $headers = array();
            $headers['api-key'] =  $api_key;
            $headers['Accept'] = 'application/json';
            $headers['Content-Type'] = 'application/json';
            $headers['User-Agent'] = 'std/' . STD_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url');



            return $headers;
        }
        function get_ck_headers() {
            global $wp_version;

            $headers = array();
            $headers['Accept'] = 'application/json';
            $headers['Content-Type'] = 'application/json';
            $headers['User-Agent'] = 'std/' . STD_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url');



            return $headers;
        }

        function get_cc_headers($access_token) {
            global $wp_version;

            $headers = array();
            $headers['Authorization'] = 'Bearer ' . $access_token;
            $headers['Accept'] = 'application/json';
            $headers['Content-Type'] = 'application/json';
            $headers['User-Agent'] = 'std/' . STD_VERSION . '; WordPress/' . $wp_version . '; ' . get_bloginfo('url');
            return $headers;
        }



        /**
         * Subscribe the user to mailchimp list
         *
         * @param string $list_id
         * @param array $post_parameters
         * @return null
         */
        function subscribe_to_mailchimp($list_id, $post_parameters) {
            $api_key = $this->get_mailchimp_api_key();
            if (empty($api_key)) {
                return;
            }
            $api_url = STD_MC_API_URL;
            $dash_position = strpos($api_key, '-');
            if ($dash_position !== false) {
                $api_url = str_replace('//api.', '//' . substr($api_key, $dash_position + 1) . ".api.", $api_url);
                $api_url = $api_url . 'lists/' . $list_id;
                $method = 'POST';
                $args = array(
                    'url' => $api_url,
                    'headers' => $this->get_mc_headers($api_key),
                    'timeout' => 10,
                    'sslverify' => true,
                    'body' => json_encode($post_parameters)
                );
                $mailchimp_connection = wp_remote_post($api_url, $args);


                $this->record_mc_response(wp_remote_retrieve_body($mailchimp_connection));
            }
        }
        /**
         * Subscribe the user to mailerlite list
         *
         * @param string $list_id
         * @param array $post_parameters
         * @return null
         */
        function subscribe_to_mailerlite($list_id, $post_parameters) {
            $std_settings = get_option('std_settings');
            $api_key = (!empty($std_settings['mailerlite']['api_key'])) ? $std_settings['mailerlite']['api_key'] : '';
            if (empty($api_key)) {
                return;
            }
            $api_url = STD_ML_API_URL;

            $api_url = $api_url . 'groups/' . $list_id . '/subscribers';
            $method = 'POST';
            $args = array(
                'url' => $api_url,
                'headers' => $this->get_ml_headers($api_key),
                'timeout' => 10,
                'sslverify' => true,
                'body' => json_encode($post_parameters)
            );
            $mailerlite_connection = wp_remote_post($api_url, $args);


            $this->record_ml_response(wp_remote_retrieve_body($mailerlite_connection));
        }
        /**
         * Subscribe the user to sendinblue list
         *
         * @param string $list_id
         * @param array $post_parameters
         * @return null
         */
        function subscribe_to_sendinblue($post_parameters) {
            $std_settings = get_option('std_settings');
            $api_key = (!empty($std_settings['sendinblue']['api_key'])) ? $std_settings['sendinblue']['api_key'] : '';
            if (empty($api_key)) {
                return;
            }
            $api_url = STD_SIB_API_URL;

            $api_url = $api_url . 'contacts';
            $method = 'POST';
            $args = array(
                'url' => $api_url,
                'headers' => $this->get_sib_headers($api_key),
                'timeout' => 10,
                'sslverify' => true,
                'body' => json_encode($post_parameters)
            );
            $sendinblue_connection = wp_remote_post($api_url, $args);


            $this->record_sib_response(wp_remote_retrieve_body($sendinblue_connection));
        }
        /**
         * Subscribe the user to convertkit list
         *
         * @param string $list_id
         * @param array $post_parameters
         * @return null
         */
        function subscribe_to_convertkit($form_id, $post_parameters) {


            $api_url = STD_CK_API_URL;

            $api_url = $api_url . 'forms/' . $form_id . '/subscribe';
            $method = 'POST';
            $args = array(
                'url' => $api_url,
                'headers' => $this->get_ck_headers(),
                'timeout' => 10,
                'sslverify' => true,
                'body' => json_encode($post_parameters)
            );
            $convertkit_connection = wp_remote_post($api_url, $args);


            $this->record_ck_response(wp_remote_retrieve_body($convertkit_connection));
        }

        function get_mailchimp_api_key() {
            $std_settings = get_option('std_settings');
            return (!empty($std_settings['mailchimp']['api_key'])) ? $std_settings['mailchimp']['api_key'] : '';
        }

        function record_mc_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['mailchimp']['mc_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }
        function record_ml_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['mailerlite']['ml_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }
        function record_sib_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['sendinblue']['sib_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }
        function record_ck_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['convertkit']['ck_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }

        /**
         * Subscribe the user to constant contact list
         *
         * @param string $list_id
         * @param array $post_parameters
         * @return null
         */
        function subscribe_to_cc($list_id, $post_parameters) {
            $std_settings = get_option('std_settings');
            if (empty($std_settings['constant_contact']['api_key']) || empty($std_settings['constant_contact']['access_token'])) {
                return;
            }
            $api_url = STD_CC_API_URL;
            $api_key = $std_settings['constant_contact']['api_key'];
            $access_token = $std_settings['constant_contact']['access_token'];
            $api_url = $api_url . 'contacts?action_by=ACTION_BY_OWNER&api_key=' . $api_key;
            $method = 'POST';
            $args = array(
                'url' => $api_url,
                'headers' => $this->get_cc_headers($access_token),
                'timeout' => 10,
                'sslverify' => true,
                'body' => json_encode($post_parameters)
            );
            $contant_contact_connection = wp_remote_post($api_url, $args);
            $this->record_cc_response(wp_remote_retrieve_body($contant_contact_connection));
            return $contant_contact_connection;
        }

        function record_cc_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['constant_contact']['cc_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }
        function record_cc_v3_response($raw_response) {
            $std_settings = get_option('std_settings');
            $std_settings['constant_contact_v3']['cc_log'] = $this->sanitize_html($raw_response);
            update_option('std_settings', $std_settings);
        }

        /**
         * Returns the default opt-in confirmation message
         *
         * @return string
         *
         * @since 1.0.5
         */
        function get_default_optin_confirmation_message() {
            $default_optin_confirmation_message = esc_html__('Congratulations!!

Your email has been verified and we have sent the download link in your email.

Please check your inbox for the download link.

Thank you', 'subscribe-to-download');
            return $default_optin_confirmation_message;
        }

        /**
         * Returns default message when unsubscribed
         *
         * @return string
         *
         * @since 1.0.8
         */
        function default_unsubscribe_message() {
            return esc_html__('You have unsubscribed successfully.', 'subscribe-to-unlock');
        }

        /**
         * Check if encryption key is valid or not
         *
         * @param string $subscriber_encryption_key
         * @return boolean
         *
         * @since 1.0.8
         */
        function is_valid_encryption_key($subscriber_encryption_key) {

            global $wpdb;
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            $subscribe_row_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $subscriber_table WHERE subscriber_encryption_key like '%s'", $subscriber_encryption_key));
            if ($subscribe_row_count >= 1) {
                return true;
            } else {
                return false;
            }
        }

        function is_already_subscribed() {
            if (isset($_COOKIE['std_encryption_key'], $_COOKIE['std_download_verified_key']) && $this->check_if_already_subscribed($_COOKIE['std_encryption_key']) && $_COOKIE['std_encryption_key'] == $_COOKIE['std_download_verified_key']) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * Returns visitors IP address
         *
         * @return string $ip
         *
         * @since 1.1.7
         */
        function get_user_IP() {
            $client = @$_SERVER['HTTP_CLIENT_IP'];
            $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
            $remote = $_SERVER['REMOTE_ADDR'];

            if (filter_var($client, FILTER_VALIDATE_IP)) {
                $ip = $client;
            } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
                $ip = $forward;
            } else {
                $ip = $remote;
            }

            return $ip;
        }

        /**
         * Filter the mail content type.
         */
        function wpdocs_set_html_mail_content_type() {
            return 'text/html';
        }

        /**
         * Generates current page URL
         *
         * @return string $pageURL
         *
         * @since 1.0.0
         */
        function get_current_page_url() {
            $pageURL = 'http';
            if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
                $pageURL .= "s";
            }
            $pageURL .= "://";
            if ($_SERVER["SERVER_PORT"] != "80") {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
            } else {
                $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            }
            $pageURL = explode('?', $pageURL);
            $pageURL = $pageURL[0];
            return $pageURL;
        }

        /**
         * Validates google reCaptcha V3
         * 
         * @since 2.0.7
         * 
         * @param string $secret_key
         */
        function validate_recaptcha_v3($recaptcha_response, $secret_key) {
            $response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', array(
                'body' => array(
                    'secret' => $secret_key,
                    'response' => $recaptcha_response,
                )
            ));

            $response_body = wp_remote_retrieve_body($response);
            $result = json_decode($response_body);


            /**
             * std_reCaptcha_score
             * 
             * Filters reCaptcha score
             */
            $uper_end_score = apply_filters('std_reCaptcha_score', 0.5);
            // Check if reCAPTCHA was successful
            if ($result && $result->success && $result->score >= $uper_end_score) {
                return true; // Success
            } else {
                return false; // Failure
            }
        }

        function refresh_access_token() {
            // Get the stored refresh token
            $std_settings = get_option('std_settings');
            $refresh_token = $std_settings['constant_contact_v3']['refresh_token'];


            if (!$refresh_token) {
                $this->record_cc_v3_response("Error: No refresh token found. Please authenticate first.");
                return "Error: No refresh token found. Please authenticate first.";
            }

            // Your Constant Contact API credentials

            $client_id = $std_settings['constant_contact_v3']['client_id'];
            $client_secret = $std_settings['constant_contact_v3']['client_secret'];
            $redirect_uri = site_url() . '?std_constant_contact_authorize';

            // API URL to refresh the access token
            $token_url = 'https://authz.constantcontact.com/oauth2/default/v1/token';
            $state = bin2hex(random_bytes(16));
            // Prepare the request body
            $request_body = array(
                'grant_type'    => 'refresh_token',
                'refresh_token' => $refresh_token,
                'client_id'     => $client_id,
                'client_secret' => $client_secret,
                'redirect_uri'  => $redirect_uri,
                'state' => $state
            );

            // Make the API request
            $response = wp_remote_post($token_url, array(
                'body'    => $request_body,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
            ));

            if (is_wp_error($response)) {
                return "Error: " . $response->get_error_message();
            }

            // Decode the response
            $body = json_decode(wp_remote_retrieve_body($response), true);
            

            if (isset($body['access_token'])) {
                // Store the new access token and refresh token
                $std_settings['constant_contact_v3']['access_token'] = $body['access_token'];
                $std_settings['constant_contact_v3']['refresh_token'] = $body['refresh_token'];
                $std_settings['constant_contact_v3']['expires_in'] = time() + $body['expires_in'];
                update_option('std_settings', $std_settings);
                $std_settings = get_option('std_settings');
                

                return $body['access_token']; // Return new access token
            } else {
                return "Error: Failed to refresh access token.";
            }
        }

        function fetch_constant_contact_lists() {
            // Get the stored access token
            $std_settings = get_option('std_settings');
            $access_token = $std_settings['constant_contact_v3']['access_token'];
            if (!$access_token) {
                return "Error: No access token found. Please authenticate first.";
            }

            // Check if the token has expired (you can compare the stored expiration time)
            if (time() >= get_option('constant_contact_token_expires')) {
                // If expired, refresh the token
                $access_token = refresh_access_token();
                if (strpos($access_token, 'Error') !== false) {
                    return $access_token; // Return error if token refresh fails
                }
            }

            // API URL to fetch contact lists
            $api_url = "https://api.cc.email/v3/contact_lists";

            // Make the API request
            $response = wp_remote_get($api_url, array(
                'headers' => array(
                    'Authorization' => "Bearer $access_token",
                    'Content-Type'  => 'application/json',
                ),
            ));

            if (is_wp_error($response)) {
                return "Error: " . $response->get_error_message();
            }

            // Decode API response
            $body = json_decode(wp_remote_retrieve_body($response), true);

            if (isset($body['error_key'])) {
                return "API Error: " . $body['error_message'];
            }

            return $body; // Returns the list array
        }
    }

    $GLOBALS['std_library'] = new STD_Library();
}
