<?php
/**
 * Plugin Name: GetResponse
 * Description: Subscribe a contact to GetResponse when a form is submited
 * Plugin URI: https://wedevs.com/docs/wp-user-frontend-pro/modules/get-response/
 * Thumbnail Name: getresponse.png
 * Author: weDevs
 * Version: 1.0
 * Author URI: https://wedevs.com
 */

/**
 * GetResponse CLass
 */
class WPUF_GetResponse {

    function __construct() {
        add_action( 'wpuf_admin_menu', [ $this, 'add_getresponse_menu' ] );

        // Only call get_lists when needed, not on every init
        add_action( 'init', [ $this, 'handle_manual_refresh' ] );
        add_action( 'wpuf_after_register', [ $this, 'subscribe_user' ], 10, 3 );

        // registration form setting items
        add_filter( 'wpuf_registration_form_module_settings_menu_sub_items', [ $this, 'add_settings_sub_menu' ] );
        add_filter( 'wpuf_registration_form_builder_setting_menu_contents', [ $this, 'add_settings_fields' ] );
    }

    /**
     * Add fields on registration form settings
     *
     * @since 4.1.0
     *
     * @param $fields
     *
     * @return array
     */
    public function add_settings_fields( $fields ) {
        $lists = get_option( 'wpuf_gr_lists');
        
        // Only try to fetch lists if we haven't recently failed
        if ( ( ! $lists || ! is_array( $lists ) || empty( $lists ) ) && get_option( 'wpuf_getresponse_api_key' ) ) {
            // Check if we recently failed API call to prevent spam
            $last_api_failure = get_transient( 'wpuf_gr_api_failure' );
            if ( ! $last_api_failure ) {
                $lists = $this->get_lists();
            }
        }

        $fields['modules']['get_response']['enable_getresponse'] = [
            'label'     => __( 'Enable GetResponse', 'wpuf-pro' ),
            'type'      => 'toggle',
            'help_text' => __( 'Activate to connect registration form with GetResponse, facilitating smooth inclusion in your marketing strategies', 'wpuf-pro' ),
        ];

        if ( $lists && is_array( $lists ) && ! empty( $lists ) ) {
            $options = [];
            foreach ( $lists as $list ) {
                $options[$list['id']] = $list['name'];
            }

            $fields['modules']['get_response']['getresponse_list'] = [
                'label'       => __( 'Select Preferred List', 'wpuf-pro' ),
                'type'        => 'select',
                'options'     => $options,
                'help_text'   => __( 'Select the GetResponse list where new sign-ups will be added as subscribers ', 'wpuf-pro' ),
            ];
        } else {
            // Check if we have an API key but still no lists
            $api_key = get_option( 'wpuf_getresponse_api_key' );
            if ( $api_key ) {
                $fields['modules']['get_response']['getresponse_list'] = [
                    'type'  => 'note',
                    'note'  => __( 'GetResponse API connected but no campaigns found. You may need a paid plan to access campaigns/lists. Please check your GetResponse account.', 'wpuf-pro' ),
                ];
            } else {
                $fields['modules']['get_response']['getresponse_list'] = [
                    'type'  => 'note',
                    'note'  => __( 'You are not connected with GetResponse. Insert your API key first', 'wpuf-pro' ),
                ];
            }
        }

        return $fields;
    }

    /**
     * Add sub-menu settings heading on registration form
     *
     * @since 4.1.0
     *
     * @param $settings
     *
     * @return mixed
     */
    public function add_settings_sub_menu( $settings ) {
        $settings['get_response'] = [
            'label' => __( 'GetResponse', 'wpuf-pro' ),
            'icon'  => '<svg width="20" height="13" viewBox="0 0 20 13" xmlns="http://www.w3.org/2000/svg">
<path d="M9.99643 9.98324C8.14875 9.98324 6.44997 9.31997 5.08282 8.31153C3.32312 7.01883 2.26053 5.00871 1.96951 3.22871C1.9492 3.09335 1.9289 2.96476 1.90859 2.8497C1.83415 2.34886 2.19962 1.80742 2.81552 1.80742H3.23514C3.62091 3.62803 4.62259 4.91396 5.63103 5.73967C6.98464 6.83609 8.56837 7.24218 9.96259 7.27602C13.7459 7.35723 17.4345 3.9935 19.7898 0.318445C19.6342 0.122171 19.3973 0.000345704 19.1266 0.000345704H0.852776C0.379012 -0.0131904 0 0.372589 0 0.839586V11.8512C0 12.325 0.379012 12.704 0.852776 12.704H19.1333C19.6071 12.704 19.9861 12.3182 19.9861 11.8512V2.41655C16.8863 7.87161 13.3196 9.97647 9.98966 9.98324H9.99643Z" fill="#9CA3AF"/>
</svg>',
        ];

        return $settings;
    }

    /**
     * Require the GetResponse class if not exists
     *
     * @return void
     */
    public function require_getresponse() {
        if ( ! class_exists( 'GetResponse' ) ) {
            require_once dirname( __FILE__ ) . '/class-getresponse.php';
        }
    }

    /**
     * Add GetResponse Submenu in WPUF
     */
    public function add_getresponse_menu() {
        add_submenu_page( 'wp-user-frontend', __( 'GetResponse', 'wpuf-pro' ), __( 'GetResponse', 'wpuf-pro' ), 'manage_options', 'wpuf_getresponse', array($this, 'getresponse_page') );
    }

    /**
     * Submenu Call Back Page
     */
    public function getresponse_page() {
        require_once dirname( __FILE__ ) . '/templates/getresponse-template.php';
    }

    /**
     * Handle manual refresh of GetResponse lists
     */
    public function handle_manual_refresh() {
        if ( isset( $_GET['wpuf_refresh_gr_lists'] ) && current_user_can( 'manage_options' ) ) {
            // Clear existing lists and failure cache
            delete_option( 'wpuf_gr_lists' );
            delete_transient( 'wpuf_gr_api_failure' );
            delete_transient( 'wpuf_gr_last_log' );
            
            // Fetch new lists
            $lists = $this->get_lists();
            
            if ( ! empty( $lists ) ) {
                wp_redirect( add_query_arg( 'gr_refresh', 'success', wp_get_referer() ) );
            } else {
                wp_redirect( add_query_arg( 'gr_refresh', 'failed', wp_get_referer() ) );
            }
            exit;
        }
    }

    /**
     * Fetch the udpated list from getresponse and save it
     *
     * @return array
     */
    public function get_lists() {

        $this->require_getresponse();

        $lists       = array();
        $gr_key      = $this->get_api_key();

        if ( ! empty( $gr_key ) ) {

            $getresponse = new GetResponse( $gr_key );
            $response    = $getresponse->getCampaigns();

            if ( ! isset( $response->httpStatus ) && is_array( $response ) ) {

                foreach ( $response as $list ) {
                    if ( isset( $list->campaignId ) && isset( $list->name ) ) {
                        $lists[] = [
                            'id'     => $list->campaignId,
                            'name'   => $list->name
                        ];
                    }
                }
                update_option( 'wpuf_gr_lists', $lists );
            } else {
                if ( isset( $response->httpStatus ) ) {
                   
                    $last_log = get_transient( 'wpuf_gr_last_log' );
                    if ( ! $last_log ) {
                        set_transient( 'wpuf_gr_last_log', time(), HOUR_IN_SECONDS );
                    }
                    // response code 1023 indicates access forbidden (HTTP 403) - permission/account issue requiring manual intervention
                    if ( '1023' === $response->code ) {
                        set_transient( 'wpuf_gr_api_failure', $response->code, DAY_IN_SECONDS );
                    } else {
                        // Other error codes (network issues, rate limits, server errors) - shorter cache for potentially temporary problems
                        set_transient( 'wpuf_gr_api_failure', $response->code, HOUR_IN_SECONDS );
                    }
                }
            
                delete_option( 'wpuf_gr_lists' );
            }
        } else {
            delete_option( 'wpuf_gr_lists' );
        }

        return $lists;
    }

    /**
     * Get GetResponse API key
     */
    public function get_api_key() {

        $gr_api_key = get_option( 'wpuf_getresponse_api_key' );

        return $gr_api_key;
    }

    /**
     * Test API connection and return debug info
     */
    public function test_api_connection() {
        $this->require_getresponse();
        
        $gr_key = $this->get_api_key();
        
        if ( empty( $gr_key ) ) {
            return [
                'status'  => 'error',
                'message' => 'No API key found'
            ];
        }
        
        $getresponse = new GetResponse( $gr_key );
        $response = $getresponse->accounts();
        
        if ( isset( $response->httpStatus ) ) {
            return [
                'status'   => 'error',
                'message'  => 'API call failed',
                'response' => $response
            ];
        } else {
            return [
                'status'       => 'success',
                'message'      => 'API connection successful',
                'account_info' => $response
            ];
        }
    }

    /**
     * Subscribe a user when a form is submitted
     *
     * @param  int $user_id
     * @param  int $form_id
     * @param  array $form_settings
     *
     * @return void
     */
    public function subscribe_user( $user_id, $form_id, $form_settings ) {

        if ( ! isset( $form_settings['enable_getresponse'] ) || $form_settings['enable_getresponse'] == 'no' ) {
            return;
        }

        $user          = get_user_by( 'id', $user_id );
        $list_selected = isset( $form_settings['getresponse_list'] ) ? $form_settings['getresponse_list'] : '';
        $gr_key        = $this->get_api_key();

        // Validate required data
        if ( empty( $gr_key ) || empty( $list_selected ) || !$user ) {
            return;
        }

        $this->require_getresponse();

        $param = (object) [
            'name'     => $user->user_nicename,
            'email'    => $user->user_email,
            'campaign' => [
                'campaignId' => $list_selected
            ],
        ];

        $getresponse = new GetResponse( $gr_key );
        $getresponse->addContact( $param );
    }
}

new WPUF_GetResponse();
