<?php
/**
 * Plugin Name: Kit (Formerly ConvertKit)
 * Description: Subscribe a contact to Kit (Formerly ConvertKit) when a form is submitted
 * Plugin URI: https://wedevs.com/docs/wp-user-frontend-pro/modules/convertkit/
 * Thumbnail Name: convertkit.png
 * Author: weDevs
 * Version: 1.0
 * Author URI: https://wedevs.com
 */

/**
 * ConvertKit CLass
 */
class WPUF_ConvertKit {

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

        add_action( 'init', [ $this, 'get_lists' ] );
        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_ck_lists');
        
        // If no lists but API key exists, try to fetch lists
        if ( ( ! $lists || ! is_array( $lists ) || empty( $lists ) ) && get_option( 'wpuf_convertkit_api_key' ) ) {
            $lists = $this->get_lists();
        }

        $fields['modules']['kit']['enable_convertkit'] = [
            'label' => __( 'Enable Kit', 'wpuf-pro' ),
            'type'  => 'toggle',
            'help_text' => __( 'Activate to connect your registration form with Kit, ensuring smooth integration with your email marketing lists', 'wpuf-pro' ),
        ];

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

            $fields['modules']['kit']['convertkit_list'] = [
                'label'   => __( 'Select Preferred List', 'wpuf-pro' ),
                'type'    => 'select',
                'options' => $options,
                'help_text'   => __( 'Select the target Kit list to automatically add new new sign-ups as subscribers', 'wpuf-pro' ),
            ];
        } else {
            $fields['modules']['kit']['convertkit_list'] = [
                'type'  => 'note',
                'note'  => __( 'You are not connected with Kit. 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['kit'] = [
            'label' => __( 'Kit (Formerly ConvertKit)', 'wpuf-pro' ),
            'icon'  => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.3232 10.3027C19.4454 11.2941 21.0352 16.0359 21.0772 20.8052C21.0781 20.9125 20.9915 21 20.8842 21H14.4363C14.3299 21 14.2433 20.9142 14.2427 20.8076C14.2233 17.1075 13.6238 13.8422 9.95756 13.7012C9.84819 13.6971 9.75705 13.7847 9.75705 13.8942V20.8071C9.75705 20.9136 9.6706 21 9.56404 21H3.11488C3.00832 21 2.92188 20.9138 2.92188 20.8071V3.193C2.92188 3.08645 3.00832 3 3.11488 3H9.56404C9.6706 3 9.75705 3.08645 9.75705 3.193V9.79123C9.75705 9.88911 9.83635 9.96842 9.93426 9.96842C10.0119 9.96842 10.0808 9.91785 10.1034 9.84347C11.7647 4.40233 14.8672 3.0342 19.9052 3.00056C20.0121 2.99981 20.0997 3.08664 20.0997 3.19357V9.77541C20.0997 9.88193 20.0133 9.96842 19.9067 9.96842H14.3555C14.2623 9.96842 14.1867 10.044 14.1867 10.1372C14.1867 10.218 14.244 10.2875 14.3232 10.3027Z" fill="#9CA3AF"/>
</svg>',
        ];

        return $settings;
    }

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

    /**
     * Add ConvertKit Submenu in WPUF
     */
    public function add_convertkit_menu() {
        add_submenu_page( 'wp-user-frontend', __( 'Kit (Formerly ConvertKit)', 'wpuf-pro' ), __( 'Kit (Formerly ConvertKit)', 'wpuf-pro' ), 'manage_options', 'wpuf_convertkit', array($this, 'convertkit_page') );
    }

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

    /**
     * Handle manual refresh of ConvertKit lists
     */
    public function handle_manual_refresh() {
        if ( isset( $_GET['wpuf_refresh_ck_lists'] ) && current_user_can( 'manage_options' ) ) {
            // Clear existing lists
            delete_option( 'wpuf_ck_lists' );
            
            // Fetch new lists
            $lists = $this->get_lists();
            
            if ( ! empty( $lists ) ) {
                wp_redirect( add_query_arg( 'ck_refresh', 'success', wp_get_referer() ) );
            } else {
                wp_redirect( add_query_arg( 'ck_refresh', 'failed', wp_get_referer() ) );
            }
            exit;
        }
    }

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

        $this->require_convertkit();

        $lists      = [];
        $ck_api_key = get_option( 'wpuf_convertkit_api_key' );

        if ( ! empty( $ck_api_key ) ) {
            $response = self::check_api_key( $ck_api_key );

            if ( ! is_array( $response ) ) {
                return [];
            }

            if ( array_key_exists( 'error', $response ) ) {
                return [];
            }

            if ( array_key_exists( 'forms', $response ) && is_array( $response['forms'] ) ) {
                foreach ( $response['forms'] as $list ) {
                    if ( isset( $list['id'] ) && isset( $list['name'] ) ) {
                        $lists[] = array(
                            'id'     => $list['id'],
                            'name'   => $list['name'],
                        );
                    }
                }

                update_option( 'wpuf_ck_lists', $lists );
            }
        }

        return $lists;
    }


    /**
     * 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_convertkit'] ) || $form_settings['enable_convertkit'] == 'no' ) {
            return;
        }

        if( empty( $form_settings['convertkit_list'] ) || $form_settings['convertkit_list'] == '' ) {
            return;
        }

        $user          = get_user_by( 'id', $user_id );
        $selected_form = get_option( 'wpuf_ck_lists' );
        // $selected_form = $selected_form[0]['id'];
        $selected_form = $form_settings['convertkit_list'];
        $this->require_convertkit();

        $ck_api_key      = get_option( 'wpuf_convertkit_api_key' );
        $ck_secret_key   = get_option( 'wpuf_convertkit_secret_key' );
        $ck_double_optin = get_option( 'wpuf_convertkit_double_opt' );
        $convertkit = new ConvertKit( $ck_api_key );

        $response = $convertkit->subscribeToAForm( $selected_form, $user->user_email, $user->display_name, $ck_double_optin );
    }

    /**
     * Check if key is valid and return forms | errors
     *
     * @param bool $ck_api_key
     *
     * @return array
     */
    public static function check_api_key( $ck_api_key ) {
        $convertkit = new ConvertKit( $ck_api_key );
        $response = $convertkit->getForms();
        
        if ( empty( $response ) ) {
            return array( 'error' => true, 'message' => __( 'No response from ConvertKit API. Please check your internet connection.', 'wpuf-pro' ) );
        }
        
        $decoded_response = json_decode( $response, true );
        
        if ( json_last_error() !== JSON_ERROR_NONE ) {
            return array( 'error' => true, 'message' => __( 'Invalid response from ConvertKit API. Please check your API key.', 'wpuf-pro' ) );
        }
        
        return $decoded_response;
    }
}

new WPUF_ConvertKit();
