<?php
/**
 * UABB Analytics.
 *
 * @package UABB
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'UABB_Analytics' ) ) {

	/**
	 * Class UABB_Analytics
	 *
	 * Handles analytics-related functionality for the Ultimate Addons for Beaver Builder plugin.
	 *
	 * @since 1.36.16
	 */
	class UABB_Analytics {

		/**
		 * UABB Analytics constructor.
		 *
		 * Initializing UABB Analytics.
		 *
		 * @since 1.36.16
		 * @access public
		 */
		public function __construct() {

			// BSF Analytics Tracker.
			if ( ! class_exists( 'BSF_Analytics_Loader' ) ) {
				require_once BB_ULTIMATE_ADDON_DIR . 'admin/bsf-analytics/class-bsf-analytics-loader.php';
			}

			if ( 'yes' === get_option( 'uabb_analytics_optin', false ) ) {
				add_action( 'shutdown', array( $this, 'maybe_run_uabb_widgets_usage_check' ) );
			}

			$bsf_analytics = BSF_Analytics_Loader::get_instance();

			$bsf_analytics->set_entity(
				array(
					'uabb' => array(
						'product_name'        => 'Ultimate Addons for Beaver Builder',
						'path'                => BB_ULTIMATE_ADDON_DIR . 'admin/bsf-analytics',
						'author'              => 'Brainstorm Force',
						'time_to_display'     => '+24 hours',
						'deactivation_survey' => array(
							array(
								'id'                => 'deactivation-survey-bb-ultimate-addon',
								'popup_logo'        => BB_ULTIMATE_ADDON_URL . 'assets/images/uabb.svg',
								'plugin_slug'       => 'bb-ultimate-addon',
								'plugin_version'    => BB_ULTIMATE_ADDON_VER,
								'popup_title'       => 'Quick Feedback',
								'support_url'       => 'https://www.ultimatebeaver.com/contact/',
								'popup_description' => 'If you have a moment, please share why you are deactivating Ultimate Addons for Beaver Builder:',
								'show_on_screens'   => array( 'plugins' ),
							),
						),
						'hide_optin_checkbox' => true,
					),
				)
			);

			add_filter( 'bsf_core_stats', array( $this, 'add_uabb_analytics_data' ) );
		}

		/**
		 * Check the page on which module check needs to be run.
		 */
		public function maybe_run_uabb_widgets_usage_check() {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( is_admin() && isset( $_GET['page'] ) && 'uabb-builder-settings' === $_GET['page'] ) {
				$this->uabb_check_widgets_data_usage();
			}
		}

		/**
		 * Check the usage module from option table; if not found then fetch module usage again.
		 */
		public function uabb_check_widgets_data_usage() {

			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$transient_key = 'uabbpro_module_usage_data';
			$module_usage  = get_transient( $transient_key );

			if ( false === $module_usage || false === get_option( 'uabbpro_module_usage_data_option' ) ) {
				$filtered_module_usage = $this->get_uabb_module_usage();

				set_transient(
					$transient_key,
					$filtered_module_usage,
					MONTH_IN_SECONDS
				);

				update_option( 'uabbpro_module_usage_data_option', $filtered_module_usage );
			}
		}

		/**
		 * Get UABB module usage statistics.
		 *
		 * @return array
		 */
		public function get_uabb_module_usage() {

			if ( ! class_exists( 'FLBuilder' ) || ! class_exists( 'FLBuilderModel' ) ) {
				return array();
			}

			$uabb_modules_usage = array();

			$args = array(
				'post_type'      => FLBuilderModel::get_post_types(),
				'post_status'    => 'publish',
				'meta_key'       => '_fl_builder_enabled',
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
				'meta_value'     => '1',
				'posts_per_page' => -1,
			);

			$query = new WP_Query( $args );

			if ( ! empty( $query->posts ) ) {
				foreach ( $query->posts as $post ) {

					$meta = get_post_meta( $post->ID, '_fl_builder_data', true );

					if ( ! is_array( $meta ) && ! is_object( $meta ) ) {
						continue;
					}

					foreach ( (array) $meta as $node ) {

						if ( ! isset( $node->type ) || 'module' !== $node->type ) {
							continue;
						}

						if ( ! isset( $node->settings->type ) ) {
							continue;
						}

						$module_type = $node->settings->type;

						if ( $this->is_uabb_module( $module_type ) ) {

							if ( ! isset( $uabb_modules_usage[ $module_type ] ) ) {
								$uabb_modules_usage[ $module_type ] = 0;
							}

							$uabb_modules_usage[ $module_type ]++;
						}
					}
				}
			}

			arsort( $uabb_modules_usage );

			return $uabb_modules_usage;
		}

		/**
		 * Check if a module is a UABB module.
		 *
		 * @param string $module_type Module slug.
		 * @return bool
		 */
		private function is_uabb_module( $module_type ) {

			$all_modules = \BB_Ultimate_Addon_Helper::get_all_modules();

			foreach ( $all_modules as $pattern => $module_data ) {
				if ( 0 === strpos( $module_type, $pattern ) ) {
					return true;
				}
			}

			return false;
		}

		/**
		 * Callback function to add specific analytics data.
		 *
		 * @param array $stats_data Existing stats data.
		 * @return array
		 */
		public function add_uabb_analytics_data( $stats_data ) {

			$stats_data['plugin_data']['uabb'] = array(
				'pro_version'           => BB_ULTIMATE_ADDON_VER,
				'site_language'         => get_locale(),
				'beaverbuilder_version' => defined( 'FL_BUILDER_VERSION' ) ? FL_BUILDER_VERSION : '',
			);

			$fetch_uabb_data = $this->uabb_get_module_usage();

			foreach ( $fetch_uabb_data as $key => $value ) {
				$stats_data['plugin_data']['uabb']['numeric_values'][ $key ] = $value;
			}

			return $stats_data;
		}

		/**
		 * Fetch module usage data.
		 *
		 * @return array
		 */
		private function uabb_get_module_usage() {
			return get_option( 'uabbpro_module_usage_data_option', array() );
		}
	}
}

new UABB_Analytics();
