<?php
/*
Plugin Name: BuddyPress Profile
Plugin URI: https://wedevs.com/docs/wp-user-frontend-pro/modules/buddypress-profile-integration/
Thumbnail Name: wpuf-buddypress.png
Description: Register and upgrade user profiles and sync data with BuddyPress
Version: 0.3
Author: Tareq Hasan
Author URI: http://tareq.wedevs.com/
License: GPL2
*/

/**
 * Copyright (c) 2013 Tareq Hasan (email: tareq@wedevs.com). All rights reserved.
 *
 * Released under the GPL license
 * http://www.opensource.org/licenses/gpl-license.php
 *
 * This is an add-on for WordPress
 * http://wordpress.org/
 *
 * **********************************************************************
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * **********************************************************************
 */

// don't call the file directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * WPUF_BP_Profile class
 *
 * @class WPUF_BP_Profile The class that holds the entire WPUF_BP_Profile plugin
 */
class WPUF_BP_Profile {
    /**
     * @var array|object|stdClass[]|null
     */
    protected $bp_fields;
    /**
     * @var mixed|string
     */
    private $bp_settings;

    /**
     * Constructor for the WPUF_BP_Profile class
     *
     * Sets up all the appropriate hooks and actions
     * within our plugin.
     *
     * @uses is_admin()
     * @uses add_action()
     */
    public function __construct() {
        add_action( 'save_post', array( $this, 'save_form_settings' ), 1, 2 );

        add_action( 'wpuf_update_profile', array( $this, 'on_profile_update' ), 10, 2 );
        add_action( 'wpuf_after_register', array( $this, 'on_user_registration' ), 10, 2 );

        // 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 ) {
        global $post, $wpdb;

        $this->bp_fields = $wpdb->get_results( "SELECT id, name FROM {$wpdb->prefix}bp_xprofile_fields WHERE parent_id = 0" );

        $form_settings = wpuf_get_form_settings( $post->ID );
        $this->bp_settings = isset( $form_settings['_wpuf_bp_mapping'] ) ? $form_settings['_wpuf_bp_mapping'] : '';
        $wpuf_fields       = wpuf_get_form_fields( $post->ID );

        $excluded          = apply_filters( 'wpuf_bp_settings_content_excluded', array( 'user_login' ) );
        $allowed_type      = apply_filters( 'wpuf_bp_settings_content_allowed_types', array( 'text', 'numeric_text', 'email', 'textarea', 'date', 'radio', 'select', 'multiselect', 'checkbox', 'country_list', 'url', 'column_field' ) );

        $user_profile = is_multisite() ? admin_url( 'network/users.php?page=bp-profile-setup' ) : admin_url( 'users.php?page=bp-profile-setup' );
        $options[-1] = __( '-- Select --', 'wpuf-pro' );

        foreach ( $this->bp_fields as $bp_field ) {
            $options[ $bp_field->id ] = $bp_field->name;
        }

        foreach ( $wpuf_fields as $index => $field ) {
            if ( $field['input_type'] === 'password' ) {
                continue;
            }
            if ( isset( $field['name'] ) && in_array( $field['name'], $excluded, true ) ) {
                continue;
            }
            if ( ! in_array( $field['input_type'], $allowed_type, true ) ) {
                continue;
            }

            if ( empty( $field['label'] )) {
                continue;
            }

            // lowercase the label and replace space with `_`
            // $key = strtolower( str_replace( ' ', '_', $field['label'] ) );
            $key = ! empty( $field['name'] ) ? sanitize_text_field( $field['name'] ) : '';

            $fields['modules']['buddypress'][ $key ] = [
                'label'   => $field['label'],
                'type'    => 'select',
                'name'    => 'wpuf_settings[_wpuf_bp_mapping][' . $key . ']',
                'options' => $options,
            ];
        }

        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['buddypress'] = [
            'label' => __( 'BuddyPress', 'wpuf-pro' ),
            'icon'  => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.1605 2.01277C8.54364 2.28266 6.25522 3.41325 4.59821 5.25501C3.19303 6.81231 2.38278 8.55925 2.06525 10.6891C1.97765 11.2946 1.97765 12.6987 2.0689 13.315C2.38643 15.5106 3.30618 17.3961 4.80625 18.9424C7.4268 21.6413 11.2116 22.6406 14.8322 21.5902C16.4674 21.1161 17.9638 20.208 19.1938 18.9424C20.7011 17.3888 21.6282 15.4814 21.9348 13.2968C22.0223 12.6658 22.0223 11.2982 21.9311 10.6891C21.599 8.40972 20.65 6.49502 19.0806 4.92678C17.5294 3.37678 15.6388 2.42854 13.4052 2.08207C13.0365 2.02372 11.5073 1.9763 11.1605 2.01277ZM13.3906 2.5343C17.1572 3.0996 20.2266 5.82031 21.234 9.48561C22.0588 12.4908 21.3325 15.7549 19.3069 18.1656C17.7448 20.0183 15.46 21.2328 13.0329 21.499C12.5767 21.5501 11.4233 21.5501 10.9671 21.499C10.4561 21.4443 9.73347 21.2984 9.259 21.1526C4.61646 19.7484 1.76961 15.1604 2.56892 10.3864C2.71856 9.47831 2.98865 8.65772 3.42297 7.77149C4.55441 5.47019 6.5618 3.72325 8.99986 2.92089C9.77727 2.6656 10.3649 2.54889 11.343 2.45042C11.6934 2.41395 12.9343 2.46501 13.3906 2.5343Z" fill="#9CA3AF"/>
<path d="M11.3814 3.4484C7.9287 3.7037 4.95047 6.01593 3.86648 9.2837C3.3847 10.7462 3.30441 12.3801 3.64749 13.9082C4.33 16.9571 6.75347 19.4736 9.77185 20.265C10.6223 20.4875 11.0018 20.5312 12.0019 20.5312C13.0019 20.5312 13.3815 20.4875 14.2319 20.265C16.232 19.7398 18.0204 18.4415 19.1847 16.669C19.8891 15.5968 20.3344 14.375 20.5096 13.0402C20.5826 12.4712 20.5643 11.1692 20.4731 10.6331C20.3198 9.75418 20.0789 8.99923 19.6884 8.20782C18.1518 5.08229 14.8524 3.19311 11.3814 3.4484ZM14.3742 5.23911C15.3597 5.41417 16.2429 6.19099 16.5933 7.19758C16.6882 7.47476 16.7065 7.57688 16.7211 8.00723C16.7357 8.42664 16.7247 8.55064 16.659 8.80959C16.4327 9.72135 15.794 10.4763 14.9546 10.8264C14.7246 10.9249 14.4655 11.0015 14.4655 10.9759C14.4655 10.9686 14.5202 10.8483 14.5896 10.7134C15.0933 9.71406 15.0933 8.48864 14.5896 7.493C14.1881 6.69064 13.3706 5.99041 12.5311 5.73146C12.4216 5.69499 12.3048 5.65852 12.2756 5.64758C12.199 5.62205 12.5566 5.44335 12.9143 5.32664C13.3742 5.17711 13.845 5.14793 14.3742 5.23911ZM12.1479 6.27852C13.2793 6.58488 14.1224 7.493 14.3195 8.61629C14.3852 8.98464 14.3487 9.63018 14.2465 9.95841C13.9728 10.8191 13.4435 11.4209 12.6296 11.8002C12.2318 11.9862 11.8924 12.0555 11.407 12.0555C10.1113 12.0555 9.03459 11.2641 8.61487 10.0022C8.51267 9.69582 8.50172 9.62288 8.50172 9.15606C8.49807 8.7257 8.51267 8.6017 8.58202 8.3537C8.90685 7.2377 9.8047 6.42805 10.9544 6.22017C11.1989 6.17276 11.8924 6.20923 12.1479 6.27852ZM16.7101 11.2896C17.8087 11.6361 18.4766 12.4749 18.7723 13.879C18.8489 14.2547 18.9438 15.2941 18.9073 15.3889C18.8854 15.4399 18.7978 15.4472 18.243 15.4472C17.8927 15.4472 17.6043 15.4363 17.6043 15.4254C17.6043 15.2722 17.4693 14.5647 17.3853 14.2838C17.024 13.0657 16.2356 12.1466 15.3159 11.8731C15.2283 11.8476 15.159 11.8111 15.159 11.7965C15.159 11.7783 15.2757 11.6324 15.4217 11.4683L15.6845 11.1692L16.0714 11.1911C16.3159 11.2021 16.5459 11.2385 16.7101 11.2896ZM10.4945 13.1496L11.4362 14.0796L11.7719 13.7514C11.9581 13.5727 12.4399 13.1022 12.8413 12.7083L13.5713 11.9898L13.845 12.0226C14.6005 12.1175 15.3195 12.4457 15.8415 12.9417C16.4619 13.5289 16.816 14.2583 16.9656 15.2467C17.0204 15.6114 17.0423 16.6836 16.9985 16.9024L16.9766 17.0155H11.4325C7.51263 17.0155 5.88482 17.0045 5.87022 16.9754C5.81912 16.8988 5.80452 15.8922 5.84832 15.491C6.06366 13.445 7.17685 12.2232 9.00904 12.0263C9.36307 11.9898 9.20978 11.8768 10.4945 13.1496Z" fill="#9CA3AF"/>
</svg>',
        ];

        return $settings;
    }

    /**
     * Initializes the WPUF_BP_Profile() class
     *
     * Checks for an existing WPUF_BP_Profile() instance
     * and if it doesn't find one, creates it.
     */
    public static function init() {
        static $instance = false;

        if ( ! $instance ) {
            $instance = new WPUF_BP_Profile();
        }

        return $instance;
    }

    public function bp_settings_tab_head() {
        ?>
        <a href="#wpuf-metabox-buddypress" class="nav-tab" id="wpuf_buddypress-tab"><?php esc_attr_e( 'BuddyPress', 'wpuf-pro' ); ?></a>
        <?php
    }

    public function bp_settings_content() {
        global $post, $wpdb;

        $this->bp_fields = $wpdb->get_results( "SELECT id, name FROM {$wpdb->prefix}bp_xprofile_fields WHERE parent_id = 0" );

        $form_settings = wpuf_get_form_settings( $post->ID );
        $this->bp_settings = isset( $form_settings['_wpuf_bp_mapping'] ) ? $form_settings['_wpuf_bp_mapping'] : '';
        $wpuf_fields       = wpuf_get_form_fields( $post->ID );

        $excluded          = apply_filters( 'wpuf_bp_settings_content_excluded', array( 'user_login' ) );
        $allowed_type      = apply_filters( 'wpuf_bp_settings_content_allowed_types', array( 'text', 'numeric_text', 'email', 'textarea', 'date', 'radio', 'select', 'multiselect', 'checkbox', 'country_list', 'url', 'column_field' ) );

        $user_profile = is_multisite() ? admin_url( 'network/users.php?page=bp-profile-setup' ) : admin_url( 'users.php?page=bp-profile-setup' );
        ?>
        <div id="wpuf-metabox-buddypress" class="group">

            <?php if ( $wpuf_fields ) { ?>
                <table class="form-table">
                    <tbody>
                    <?php
                    foreach ( $wpuf_fields as $index => $field ) {
                        if ( $field['input_type'] === 'password' ) {
                            continue;
                        }

                        if ( isset( $field['name'] ) && in_array( $field['name'], $excluded, true ) ) {
                            continue;
                        }

                        if ( ! in_array( $field['input_type'], $allowed_type, true ) ) {
                            continue;
                        }

                        ?>
                        <?php
                        if ( $field['input_type'] === 'column_field' ) {
                            $i         = 1;
                            $max_count = count( $field['inner_fields'] );

                            for ( $i; $i <= $max_count; $i ++ ) {
                                if ( empty( $field['inner_fields'][ 'column-' . $i ][0]['label'] ) ) {
                                    continue;
                                }
                                ?>
                                <tr>
                                    <th><?php echo $field['inner_fields'][ 'column-' . $i ][0]['label']; ?></th>
                                    <td>
                                        <?php echo $this->bp_get_dropdown( $field['inner_fields'][ 'column-' . $i ][0]['name'] ); ?>
                                    </td>
                                </tr>
                                <?php
                            }
                        } else {
                            ?>
                            <tr>
                                <th><?php echo $field['label']; ?></th>
                                <td>
                                    <?php echo $this->bp_get_dropdown( $field['name'] ); ?>
                                </td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                    </tbody>
                </table>
                <p><a class="button" href="<?php echo $user_profile; ?>" target="_blank"><?php esc_attr_e( 'BuddyPress profile fields &rarr;', 'wpuf-pro' ); ?></a></p>
            <?php } else { ?>

                <?php esc_attr_e( 'No fields found in the form. Add fields first and update the form.', 'wpuf-pro' ); ?>

            <?php } ?>
        </div>
        <?php
    }

    public function bp_get_dropdown( $index, $field_id = false ) {
        $dropdown = '<select name="wpuf_settings[_wpuf_bp_mapping][' . $index . ']">';
        $dropdown .= '<option value="-1">' . __( '-- Select --', 'wpuf-pro' ) . '</option>';

        if ( $this->bp_fields ) {
            foreach ( $this->bp_fields as $field ) {
                $selected = '';

                if ( isset( $this->bp_settings[ $index ] ) && $this->bp_settings[ $index ] === $field->id ) {
                    $selected = ' selected="selected"';
                }

                $dropdown .= '<option value="' . $field->id . '"' . $selected . '>' . $field->name . '</option>';
            }
        }

        $dropdown .= '</select>';

        return $dropdown;
    }

    public function save_form_settings( $post_id, $post ) {
        if ( ! isset( $_REQUEST['form_data'] ) ) {
            return;
        }

        $form_data = array();
        //phpcs:ignore
        parse_str( wp_unslash( $_REQUEST['form_data'] ), $form_data );

        if ( ! isset( $form_data['wpuf_settings']['_wpuf_bp_mapping'] ) ) {
            return;
        }

        // Is the user allowed to edit the post or page?
        if ( ! current_user_can( 'edit_post', $post->ID ) ) {
            return $post->ID;
        }

        update_post_meta( $post->ID, 'wpuf_bp_form', $form_data['wpuf_settings']['_wpuf_bp_mapping'] );
    }

    public function update_user_data( $user_id, $form_id ) {
        $fields = get_post_meta( $form_id, 'wpuf_bp_form', true );

        if ( $fields && is_array( $fields ) ) {
            foreach ( $fields as $input_name => $xprofile_field_id ) {

                if ( $xprofile_field_id !== '-1' && isset( $_REQUEST[ $input_name ] ) ) {
                    $field_type = BP_XProfile_Field::get_type( $xprofile_field_id );

                    //phpcs:ignore
                    $value  = isset( $_REQUEST[ $input_name ] ) ?  $_REQUEST[ $input_name ] : '';
                    if ( is_array( $value ) ) {
                        $value = array_map( 'sanitize_text_field', $value );
                    } else {
                        $value = sanitize_text_field( $value );
                    }

                    if ( 'datebox' === $field_type ) {
                        $date  = isset( $_REQUEST[ $input_name ] ) ? sanitize_text_field( wp_unslash( $_REQUEST[ $input_name ] ) ) : gmdate( 'Y-m-d' );
                        $date  = str_replace( '/', '-', $date );
                        $value = gmdate( 'Y-m-d H:i:s', strtotime( $date ) );
                    }
                    xprofile_set_field_data( $xprofile_field_id, $user_id, $value );
                }
            }
        }
    }

    public function on_profile_update( $user_id, $form_id ) {
        $this->update_user_data( $user_id, $form_id );
    }

    public function on_user_registration( $user_id, $form_id ) {
        $this->update_user_data( $user_id, $form_id );

        if ( function_exists( 'bp_activity_add' ) ) {
            bp_activity_add(
                array(
                    'user_id'   => $user_id,
                    'component' => 'members',
                    'type'      => 'new_member',
                )
            );
        }
    }

}

function wpuf_bp_init() {

    //check dependency for wp_user_frontend
    if ( ! class_exists( 'WP_User_Frontend' ) ) {
        return;
    }

    //check dependency for buddypress
    if ( ! class_exists( 'BuddyPress' ) ) {
        return;
    }

    $wpuf_bp = WPUF_BP_Profile::init();
}

// WPUF_BP_Profile
wpuf_bp_init();
