<?php
/**
 * Buddypress plugin functions
 *
 * @package BoomBox_Theme
 * @since   1.0.0
 * @version 2.0.0
 */

// Prevent direct script access.
if ( !defined( 'ABSPATH' ) ) {
	die( 'No direct script access allowed' );
}

if ( !class_exists( 'Boombox_Essb' ) ) {

	final class Boombox_Essb {

		/**
		 * Holds class single instance
		 * @var null
		 */
		private static $_instance = NULL;

		/**
		 * Get instance
		 * @return Boombox_Essb|null
		 */
		public static function get_instance () {

			if ( NULL == static::$_instance ) {
				static::$_instance = new self();
			}

			return static::$_instance;

		}

		/**
		 * Holds displaying position name
		 * @var string
		 */
		private $display_position_name = 'display-41';

		/**
		 * Holds position name
		 * @var string
		 */
		private $position_name = 'boombox';

		/**
		 * Holds rendering state
		 * @var bool
		 */
		private $rendering = false;

		/**
		 * Holds options
		 * @var array
		 */
		private $options;

		/**
		 * Boombox_Essb constructor.
		 */
		private function __construct () {
			if ( ( defined( 'WP_INSTALLING' ) && WP_INSTALLING ) ) {
				return;
			}

			if ( !boombox_plugin_management_service()->is_plugin_active( 'easy-social-share-buttons3/easy-social-share-buttons3.php' ) ) {
				return;
			}

			$this->options = get_option( ESSB3_OPTIONS_NAME );
			$this->hooks();

			do_action( 'boombox/essb/wakeup', $this );
		}

		/**
		 * A dummy magic method to prevent Boombox_Essb from being cloned.
		 *
		 */
		public function __clone () {
			throw new Exception( 'Cloning ' . __CLASS__ . ' is forbidden' );
		}

		/**
		 * Setup Hooks
		 */
		private function hooks () {
			add_action( 'init', array( $this, 'assign_positions' ), 99 );

			add_filter( 'essb4_custom_method_list', array( $this, 'register_position' ), 10, 1 );
			add_filter( 'essb4_custom_positions', array( $this, 'register_display_position' ), 10, 1 );
			add_filter( 'essb_is_theme_integrated', array( $this, 'essb_theme_integrated' ), 10, 1 );
			add_filter( 'essb4_button_positions', array( $this, 'position_options' ), 10, 1 );
			add_filter( 'essb4_button_positions_mobile', array( $this, 'position_options' ), 10, 1 );
			add_filter( 'essb4_position_style_boombox', array( $this, 'essb_position_style_boombox' ), 10, 1 );
			add_filter( 'essb4_get_cached_counters', array( $this, 'boombox_essb_get_cached_counters' ), 10, 1 );
			add_filter( 'essb_opengraph_desc', array( $this, 'fix_user_og_description' ), 10, 1 );

			add_filter( 'boombox/customizer/fields/extras_posts_ranking_system', array( $this, 'add_fake_share_count_to_customizer' ), 10, 3 );
			add_filter( 'boombox/customizer_default_values', array( $this, 'edit_customizer_default_values' ), 10, 1 );
			add_filter( 'boombox/fake_share_count', array( $this, 'get_fake_share_count' ), 10, 1 );
			add_filter( 'boombox/shares_meta_key', array( $this, 'edit_ranking_shares_meta_key' ), 10, 1 );
			add_filter( 'mashsb_opengraph_meta', array( $this, 'remove_mashshare_meta_tags' ), 999, 1 );
			add_filter( 'mashsb_twittercard_meta', array( $this, 'remove_mashshare_meta_tags' ), 999, 1 );
			add_action( 'boombox/tgma/update/easy-social-share-buttons3/easy-social-share-buttons3.php', array( $this, 'plugin_updated' ), 10, 1 );
			add_action( 'admin_notices', array( $this, 'render_amp_share_plugin_warning_message' ) );
			add_filter( 'boombox_conditions_choices', array( $this, 'add_most_shared_to_conditions' ), 10, 1 );
			add_filter( 'boombox_trending_conditions_choices', array( $this, 'add_most_shared_to_conditions' ), 10, 1 );

			if ( boombox_plugin_management_service()->is_plugin_active( 'amp/amp.php' ) && class_exists( 'ESSBAmpSupport' ) ) {
				add_action( 'pre_amp_render_post', array( $this, 'amp_setup_template_hooks' ), 10, 1 );
				add_action( 'wp', array( $this, 'try_to_remove_amp_buttons_from_non_amp_mobile_layout' ) );
			}
		}

		/**
		 * Remove activation notice and make plugin to be integrated from theme
		 *
		 * @param bool $is_integrated Current integration state
		 *
		 * @return bool
		 */
		public function essb_theme_integrated ( $is_integrated ) {
			$is_integrated = true;

			return $is_integrated;
		}

		/**
		 * Check if is rendering buttons
		 *
		 * @return bool
		 */
		public function is_rendering () {
			return (bool)$this->rendering;
		}

		/**
		 * Get plugin options
		 *
		 * @return array
		 */
		public function get_options () {
			return $this->options;
		}

		/**
		 * Setup button
		 *
		 * @param array $button_style Current style
		 *
		 * @return array
		 */
		public function essb_position_style_boombox ( $button_style ) {
			if ( $this->is_rendering() ) {
				$button_style[ 'show_counter' ] = in_array( 'share_count', boombox_get_theme_option( 'single_post_general_share_box_elements' ) );
			}

			return $button_style;
		}

		/**
		 * Overwrite plugin activation callback
		 */
		public function install () {
			$mail_salt_check = get_option( ESSB3_MAIL_SALT );
			if ( !$mail_salt_check || empty( $mail_salt_check ) ) {
				$new_salt = mt_rand();
				update_option( ESSB3_MAIL_SALT, $new_salt );
			}

			$exist_settings = get_option( ESSB3_OPTIONS_NAME );
			if ( !$exist_settings ) {
				$default_options = ' ';

				$options = json_decode( base64_decode( $default_options ), true );
				$options = apply_filters( 'boombox/essb/default_options', $options );
				$default_options = base64_encode( json_encode( $options ) );

				// set that we run plugin for first time
				update_option( ESSB3_FIRST_TIME_NAME, 'false' );
				$options_base = ESSB_Manager::convert_ready_made_option( $default_options );
				if ( $options_base ) {
					update_option( ESSB3_OPTIONS_NAME, $options_base );
				}
			}

			// clear stored add-ons on activation of plugin
			delete_option( 'essb3_addons' );

		}

		/**
		 * Register theme positions
		 *
		 * @param array $methods Current methods
		 *
		 * @return array
		 */
		public function register_position ( $methods ) {
			$methods[ $this->display_position_name ] = __( 'Boombox', 'boombox' );

			return $methods;
		}

		/**
		 * Register theme display positions
		 *
		 * @param array $positions Current positions
		 *
		 * @return array
		 */
		public function register_display_position ( $positions ) {
			$positions[ $this->position_name ] = __( 'Boombox', 'boombox' );

			return $positions;
		}

		/**
		 * Assign positions layouts
		 *
		 * @param array $positions Current positions
		 *
		 * @return array
		 */
		public function position_options ( $positions ) {
			$positions[ $this->position_name ] = array(
				'image' => 'assets/images/display-positions-09.png',
				'label' => __( 'Boombox Position', 'boombox' ),
			);

			return $positions;
		}

		/**
		 * Assign display positions to appropriate positions
		 */
		public function assign_positions () {
			if ( is_admin() && class_exists( 'ESSBOptionsStructureHelper' ) ) {
				essb_prepare_location_advanced_customization( 'where', $this->display_position_name, $this->position_name );
			}
		}

		/**
		 * Render theme position
		 */
		public function render () {
			$general_options = essb_core()->get_general_options();

			if ( is_array( $general_options ) ) {
				if ( in_array( $this->position_name, $general_options[ 'button_position' ] ) ) {
					$this->rendering = true;
					echo essb_core()->generate_share_buttons( $this->position_name );
					$this->rendering = false;
				}
			}
		}

		/**
		 * Adds fake count to total counter and each social network
		 *
		 * @param array $counters Current counters
		 *
		 * @return array
		 */
		public function boombox_essb_get_cached_counters ( $counters ) {
			$share_count = boombox_post_shares_count( $counters[ 'total' ], get_the_ID() );
			if ( $share_count > $counters[ 'total' ] ) {
				$to_add = ceil( $share_count / ( count( $counters ) - 1 ) );
				unset( $counters[ 'total' ] );

				foreach ( $counters as $network_name => $count ) {
					$counters[ $network_name ] = absint( $counters[ $network_name ] ) + $to_add;
				}

				$counters[ 'total' ] = $share_count;
			}

			return $counters;
		}

		/**
		 * Fix og:description meta for user profile
		 *
		 * @param string $og_description Current description
		 *
		 * @return string
		 */
		function fix_user_og_description ( $og_description ) {
			if ( boombox_plugin_management_service()->is_plugin_active( 'buddypress/bp-loader.php' ) && function_exists( 'bp_is_user' ) && bp_is_user() ) {
				$og_description = boombox_get_user_meta_description( bp_displayed_user_id() );
			}

			return $og_description;
		}

		/**
		 * Add options to customizer "Post Ranking System" section
		 *
		 * @param array  $fields   Current fields
		 * @param string $section  Section ID
		 * @param array  $defaults Default values
		 *
		 * @return array
		 */
		public function add_fake_share_count_to_customizer ( $fields, $section, $defaults ) {
			// "ESSB" Fake Share Count
			$fields[] = array(
				'settings' => 'extras_post_ranking_system_essb_fake_share_count',
				'label'    => esc_html__( '"ESSB" Fake Share Count', 'boombox' ),
				'section'  => $section,
				'type'     => 'number',
				'priority' => 205,
				'default'  => $defaults[ 'extras_post_ranking_system_essb_fake_share_count' ],
				'choices'  => array(
					'min'  => 0,
					'step' => 1,
				),
			);

			return $fields;
		}

		/**
		 * Setup customizer default values
		 *
		 * @param array $default_values Current
		 *
		 * @return array
		 */
		public function edit_customizer_default_values ( $default_values ) {
			$default_values[ 'extras_post_ranking_system_essb_fake_share_count' ] = 0;

			return $default_values;
		}

		/**
		 * Edit fake share count
		 *
		 * @param int $fake_count Current fake count
		 *
		 * @return int
		 */
		public function get_fake_share_count ( $fake_count ) {
			$fake_count = absint( boombox_get_theme_option( 'extras_post_ranking_system_essb_fake_share_count' ) );

			return $fake_count;
		}

		/**
		 * Use ESSB meta key for sharing calculation
		 *
		 * @param string $meta_key Current meta key
		 *
		 * @return string
		 */
		public function edit_ranking_shares_meta_key ( $meta_key ) {
			$meta_key = 'essb_c_total';

			return $meta_key;
		}

		/**
		 * Overwrite default options for theme
		 *
		 * @param array $options Current options
		 *
		 * @return array
		 */
		public function default_options ( $options ) {

			$boombox_options = array(
				'display_in_types'                        => array(
					'post', 'page',
				),
				'content_position'                        => 'content_manual',
				'button_position'                         => array(
					$this->position_name,
				),
				'boombox_activate'                        => 'true',
				'boombox_button_style'                    => 'button',
				'boombox_template'                        => '24',
				'boombox_more_button_icon'                => 'plus',
				'boombox_share_button_icon'               => 'share-alt',
				'boombox_share_button_counter'            => 'hidden',
				'boombox_counter_pos'                     => 'hidden',
				'boombox_total_counter_pos'               => 'leftbigicon',
				'boombox_fullwidth_align'                 => 'left',
				'boombox_fullwidth_share_buttons_columns' => 1,
				'boombox_networks'                        => array(
					'facebook',
					'twitter',
				),
				'boombox_button_pos'                      => 'center',
				'boombox_more_button_func'                => 4,
				'boombox_share_button_func'               => 4,
				'boombox_button_width'                    => 'flex',
			);

			if ( boombox_plugin_management_service()->is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
				$boombox_options[ 'display_in_types' ][] = 'product';
			}

			$options = array_merge( $options, $boombox_options );

			return $options;
		}

		/**
		 * Remove 'Mashshare' plugin meta tags
		 *
		 * @param string $meta_html Current html
		 *
		 * @return string
		 */
		public function remove_mashshare_meta_tags ( $meta_html ) {
			$meta_html = '';

			return $meta_html;
		}

		/**
		 * Add/remove hooks on amp template
		 *
		 * @param int $post_id Post ID
		 */
		public function amp_setup_template_hooks ( $post_id ) {
			remove_action( 'amp_post_template_css', array( ESSBAmpSupport::getInstance(), 'amp_load_css' ) );
		}

		/**
		 * Try to remove AMP share buttons from non AMP mobile layouts
		 */
		public function try_to_remove_amp_buttons_from_non_amp_mobile_layout () {
			/**
			 * @var $essb_amp_instance ESSBAmpSupport
			 */
			$essb_amp_instance = ESSBAmpSupport::getInstance();
			if ( $essb_amp_instance->is_active_mobile_support() && !is_amp_endpoint() ) {
				remove_filter( 'the_content', array( $essb_amp_instance, 'amp_display_share' ) );
			}
		}

		/**
		 * Plugin updated callback
		 *
		 * @param string $plugin_main_file Plugin main file
		 */
		public function plugin_updated ( $plugin_main_file ) {

			$plugin_data = array_change_key_case( get_plugin_data( trailingslashit( WP_PLUGIN_DIR ) . $plugin_main_file ) );
			$unsupported_plugin_main_file = 'essb-amp-support/essb-amp-support.php';
			if ( version_compare( $plugin_data[ 'version' ], '5.0', '>=' ) ) {

				$active_plugins_option_name = 'active_plugins';

				if ( is_multisite() ) {
					/***** Network installation */

					/***** Update all blogs in network */
					$blogs = get_sites( array( 'fields' => 'ids' ) );
					foreach ( $blogs as $blog_id ) {
						$active_plugins = get_blog_option( $blog_id, $active_plugins_option_name );
						$essb_amp_support_plugin_key = array_search( $unsupported_plugin_main_file, $active_plugins );
						if ( $essb_amp_support_plugin_key !== false ) {
							unset( $active_plugins[ $essb_amp_support_plugin_key ] );

							$active_plugins = array_values( $active_plugins );
							update_blog_option( $blog_id, $active_plugins_option_name, $active_plugins );

							$essb_options = get_blog_option( $blog_id, ESSB3_OPTIONS_NAME );
							$essb_options[ 'amp_positions' ] = 'true';
							if ( !isset( $essb_options[ 'content_position_amp' ] ) ) {
								$essb_options[ 'content_position_amp' ] = 'content_both';
							}
							update_blog_option( $blog_id, ESSB3_OPTIONS_NAME, $essb_options );
						}
					}

					/***** Disable unsupported plugin in network */
					$multisite_active_plugins_options_name = 'active_sitewide_plugins';
					$network_active_plugins = get_site_option( $multisite_active_plugins_options_name );
					if ( array_key_exists( $unsupported_plugin_main_file, $network_active_plugins ) ) {
						unset( $network_active_plugins[ $unsupported_plugin_main_file ] );

						update_site_option( $multisite_active_plugins_options_name, $network_active_plugins );
					}

				} else {
					/***** Single installation */

					$active_plugins = get_option( $active_plugins_option_name );
					$essb_amp_support_plugin_key = array_search( $unsupported_plugin_main_file, $active_plugins );
					if ( $essb_amp_support_plugin_key !== false ) {
						unset( $active_plugins[ $essb_amp_support_plugin_key ] );

						$active_plugins = array_values( $active_plugins );
						update_option( $active_plugins_option_name, $active_plugins );

						$essb_options = get_option( ESSB3_OPTIONS_NAME );
						$essb_options[ 'amp_positions' ] = 'true';
						if ( !isset( $essb_options[ 'content_position_amp' ] ) ) {
							$essb_options[ 'content_position_amp' ] = 'content_both';
						}
						update_option( ESSB3_OPTIONS_NAME, $essb_options );
					}

				}
			}

		}

		/**
		 * Render admin notice for preventing essb & essb amp support plugins conflict
		 */
		public function render_amp_share_plugin_warning_message () {
			$installed_plugins = get_plugins();
			$essb_plugin_main_file = 'easy-social-share-buttons3/easy-social-share-buttons3.php';
			$essb_amp_plugin_main_file = 'essb-amp-support/essb-amp-support.php';

			if ( !array_key_exists( $essb_amp_plugin_main_file, $installed_plugins ) ) {
				return;
			}

			$essb_plugin_data = array_change_key_case( $installed_plugins[ $essb_plugin_main_file ] );
			if ( version_compare( $essb_plugin_data[ 'version' ], '5.0', '<' ) ) {
				return;
			}

			$essb_amp_plugin_data = array_change_key_case( $installed_plugins[ $essb_amp_plugin_main_file ] );

			$message = sprintf(
				__( '<p>Starting from v5.0 "%1$s" plugin doesn\'t support "%2$s" plugin. Please delete it from <a href="%3$s">plugins</a>.</p><p>Now you can configure AMP share buttons in "%1$s -> Where to Display -> AMP Sharing" section. We strongly recommend do not activate "%2$s" plugin.</p>', 'boombox' ),
				$essb_plugin_data[ 'name' ],
				$essb_amp_plugin_data[ 'name' ],
				admin_url( 'plugins.php' )
			);
			?>
			<div class="notice notice-error"><p><b><?php echo $message; ?></b></p></div>
			<?php
		}

		/**
		 * Add most shared to conditions
		 *
		 * @param array $choices Current choices
		 *
		 * @return array
		 */
		public function add_most_shared_to_conditions ( $choices ) {
			$choices[ 'most_shared' ] = esc_html__( 'Most Shared', 'boombox' );

			return $choices;

		}

	}

}

/**
 * Overwrite "Easy Social Share Buttons" plugin installation function
 */
function essb_active_oninstall () {
	$instance = Boombox_Essb::get_instance();
	add_filter( 'boombox/essb/default_options', array( $instance, 'default_options' ), 10, 1 );
	$instance->install();
}

/**
 * Initialize single instance
 */
if ( boombox_plugin_management_service()->is_plugin_active( 'easy-social-share-buttons3/easy-social-share-buttons3.php' ) ) {
	Boombox_Essb::get_instance();
}