<?php
/**
 * Plugin Name: Campaign Monitor
 * Description: Subscribe a contact to Campaign Monitor when a form is submited
 * Plugin URI: https://wedevs.com/docs/wp-user-frontend-pro/modules/campaign-monitor/
 * Thumbnail Name: campaign_monitor.png
 * Author: weDevs
 * Version: 1.0
 * Author URI: https://wedevs.com
 */

/**
 * Campaign Monitor Integration class
 */
class WPUF_Campaign_Monitor {

    function __construct() {
        add_action( 'wpuf_admin_menu', array( $this, 'add_campaign_monitor_menu' ) );
        // add_action( 'wpuf_profile_form_tab', array( $this, 'add_tab_campaign_monitor_form' ) );
        add_action( 'wpuf_profile_form_tab_content', array( $this, 'add_tab_content_profile_form' ) );

        add_action( 'init', array( $this, 'get_lists' ) );
        add_action( 'wpuf_after_register', array( $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 post form settings
     *
     * @since 4.1.0
     *
     * @param $fields
     *
     * @return array
     */
    public function add_settings_fields( $fields ) {
        $lists = get_option( 'wpuf_camp_monitor_lists');

        $fields['modules']['campaign_monitor']['enable_campaign_monitor'] = [
            'label' => __( 'Enable Campaign Monitor', 'wpuf-pro' ),
            'type'  => 'toggle',
            'help_text' => __( 'Activate to connect your registration form with Campaign Monitor for automatic list management', 'wpuf-pro' ),
        ];

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

            $fields['modules']['campaign_monitor']['campaign_monitor_list'] = [
                'label'   => __( 'Select Preferred List', 'wpuf-pro' ),
                'type'    => 'select',
                'options' => $options,
                'help_text'   => __( 'Select the desired Campaign Monitor list to automatically add new sign-ups as subscribers', 'wpuf-pro' ),
            ];
        } else {
            $fields['modules']['campaign_monitor']['campaign_monitor_list'] = [
                'type'  => 'note',
                'note'  => __( 'You are not connected with campaign_monitor. 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['campaign_monitor'] = [
            'label' => __( 'Campaign Monitor', 'wpuf-pro' ),
            'icon'  => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.81396 5.00192C2.95202 5.01177 3.08478 5.05913 3.1979 5.1389L10.8873 10.5155L2 17.7947V5.75018C2.00178 5.61178 2.04132 5.47649 2.11436 5.35892C2.18741 5.24135 2.29117 5.14596 2.41446 5.08304C2.53776 5.02013 2.67589 4.99208 2.81396 5.00192ZM21.6484 5.12127C21.7326 5.175 21.8055 5.24483 21.8627 5.32676H21.8623C21.9496 5.45118 21.9975 5.59892 22 5.7509V17.7736C22 17.9751 21.9199 18.1684 21.7774 18.3109C21.6349 18.4534 21.4416 18.5335 21.24 18.5335H2.75858C2.63643 18.5337 2.51604 18.5044 2.40769 18.4479C2.29934 18.3915 2.20625 18.3098 2.13636 18.2096L20.8031 5.1401C20.8848 5.08267 20.9772 5.04193 21.0747 5.02023C21.1723 4.99852 21.2732 4.99627 21.3716 5.01361C21.47 5.03095 21.5641 5.06754 21.6484 5.12127Z" fill="#9CA3AF"/>
</svg>',
        ];

        return $settings;
    }

    /**
     * Get the API key
     *
     * @return string
     */
    private function get_api_key() {
        $api_key = get_option( 'wpuf_campaign_monitor_api_key' );

        return $api_key;
    }

    /**
     * Add Campaign Monitor Submenu in WPUF
     */
    public function add_campaign_monitor_menu() {
        add_submenu_page( 'wp-user-frontend', __( 'Campaign Monitor', 'wpuf-pro' ), __( 'Campaign Monitor', 'wpuf-pro' ), 'manage_options', 'wpuf_campaign_monitor', array( $this, 'campaign_monitor_page' ) );
    }

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

    /**
     * Add Campaign Monitor tab in Each form
     */
    public function add_tab_campaign_monitor_form() {
        ?>
        <a href="#wpuf-metabox-campaign_monitor" class="nav-tab" id="wpuf_campaign_monitor-tab"><?php _e( 'Campaign Monitor', 'wpuf-pro' ); ?></a>
        <?php
    }

    /**
     * Display settings option in tab content
     */
    public function add_tab_content_profile_form() {
        ?>
        <div id="wpuf-metabox-campaign_monitor" class="group">
            <?php require_once dirname( __FILE__ ) . '/templates/campaign-monitor-settings-tab.php'; ?>
        </div>
        <?php
    }

    /**
     * Require the campaign monitor class if not exists
     *
     * @return void
     */
    public function require_campaign_monitor() {
        if ( ! class_exists( 'CS_REST_General' ) ) {
            require_once dirname( __FILE__ ) . '/cm-php-sdk/csrest_general.php';
        }
    }

    /**
     * Fetch the udpated list from campaign-monitor and save it
     *
     * @return void
     */
    public function get_lists() {
        $api_key = $this->get_api_key();

        $this->require_campaign_monitor();
        $auth = array( 'api_key' => $api_key );
        $client_lists = $list_object = $lists = array();

        $cm_general = new CS_REST_General( $auth );

        try {
            $result = $cm_general->get_clients();
        } catch ( Exception $e ) {
            return new WP_Error( __( 'campaign-monitor client error.', 'wpuf-pro' ), $e->getMessage() );
        }

        if ( $result->http_status_code === 200 ) {
            foreach ( $result->response as $client ) {
                if ( ! class_exists( 'CS_REST_Clients' ) ) {
                    require_once dirname( __FILE__ ) . '/cm-php-sdk/csrest_clients.php';
                }
                $client_class = new CS_REST_Clients( $client->ClientID, $auth );
                $client_lists[] = $client_class->get_lists();
            }
        }

        foreach ( $client_lists as $list ) {
            foreach ( $list->response as $list_obj ) {
                $list_object[] = $list_obj;
            }
        }

        foreach ( $list_object as $list ) {
            $lists[] = array(
                'id'     => $list->ListID,
                'name'   => $list->Name,
            );
        }

        update_option( 'wpuf_camp_monitor_lists', $lists );
    }

    /**
     * Subscribe a user when a form is submitted
     *
     * @param  int $form_id
     * @param  int $page_id
     * @param  array $form_settings
     *
     * @return void
     */
    public function subscribe_user( $user_id, $form_id, $form_settings ) {
        if ( ! isset( $form_settings['enable_campaign_monitor'] ) || $form_settings['enable_campaign_monitor'] == 'no' ) {
            return;
        }

        $user          = get_user_by( 'id', $user_id );
        $list_selected = isset( $form_settings['campaign_monitor_list'] ) ? $form_settings['campaign_monitor_list'] : '';

        $this->require_campaign_monitor();
        $auth = array( 'api_key' => $this->get_api_key() );

        if ( ! class_exists( 'CS_REST_Subscribers' ) ) {
            require_once dirname( __FILE__ ) . '/cm-php-sdk/csrest_subscribers.php';
        }

        $wrap = new CS_REST_Subscribers( $list_selected, $auth );

        $result = $wrap->add(
            array(
                'EmailAddress' => $user->user_email,
                'Name' => $user->display_name,
                'CustomFields' => array(),
                'Resubscribe' => true,
                'ConsentToTrack' => 'yes',
            )
        );
    }
}

new WPUF_Campaign_Monitor();
