<?php
defined('ABSPATH') or die('No script kiddies please!!');
if (!empty($form_details['general']['constant_contact_v3_id']) || !empty($std_settings['constant_contact_v3']['lists'])) {

    /**
     * std_cc_post_parameters filters parameters being sent to Constant Contact
     *
     * @param array $post_parameters
     * @param array $form_data
     * @param array $form_details
     */
    $post_parameters = apply_filters('std_cc_post_parameters', $post_parameters, $form_data, $form_details);
    $settings_constant_contact_lists_obj = $std_settings['constant_contact_v3']['lists'];
    $settings_constant_contact_lists = [];
    if (!empty($std_settings['constant_contact_v3']['enable'])) {
        if (!empty($settings_constant_contact_lists_obj)) {
            foreach ($settings_constant_contact_lists_obj as $constant_contact_list) {
                $settings_constant_contact_lists[] = $constant_contact_list['list_id'];
            }
        }
    }
    $constant_contact_lists = (!empty($form_details['general']['constant_contact_v3_id'])) ? $form_details['general']['constant_contact_v3_id'] : $settings_constant_contact_lists;
    $access_token = $std_settings['constant_contact_v3']['access_token'];
    if (empty($access_token)) {
        $this->record_cc_v3_response('Error: No access token found. Please authenticate first.');
        return;
    }
    // Check if the token has expired (you can compare the stored expiration time)
    if (time() >= $std_settings['constant_contact_v3']['expires_in']) {
        // If expired, refresh the token
        $access_token = $this->refresh_access_token();


        if (strpos($access_token, 'Error') !== false) {
            return;
        }
    }
    if (!empty($constant_contact_lists)) {
        foreach ($constant_contact_lists as $list_id) {
            $api_url = "https://api.cc.email/v3/contacts";

            // Prepare the request body
            $request_body = array(
                "contact_id" => $list_id,
                'email_address' => array(
                    "address" => $form_data['std_email'],
                    "permission_to_send" => "implicit"
                ),
                "first_name" => $fname,
                "last_name" => $lname,
                'create_source' => 'Account'
            );
            $post_parameters = array(
                'body'    => json_encode($request_body),
                'headers' => array(
                    'Authorization' => "Bearer $access_token",
                    'Content-Type'  => 'application/json',
                )
            );

            // Make the API request to subscribe
            $response = wp_remote_post($api_url, $post_parameters);
            if (is_wp_error($response)) {
                $this->record_cc_v3_response("Error: " . $response->get_error_message());
                return;
            }
        }
        $this->record_cc_v3_response(wp_remote_retrieve_body($response));
    }
}
