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

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

if ( ! class_exists( 'UAEL_Analytics' ) ) {
	/**
	 * Class UAEL_Analytics
	 *
	 * Handles analytics-related functionality for the Ultimate Addons for Elementor plugin.
	 *
	 * @since 1.39.3
	 */
	class UAEL_Analytics {

		/**
		 * UAEL Analytics constructor.
		 *
		 * Initializing UAEL Analytics.
		 *
		 * @since 1.39.3
		 * @access public
		 */
		public function __construct() {
			// Load analytics events class.
			if ( ! class_exists( 'UAEL_Analytics_Events' ) ) {
				require_once UAEL_DIR . 'classes/class-uael-analytics-events.php';
			}

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

			$bsf_analytics = BSF_Analytics_Loader::get_instance();

			$bsf_analytics->set_entity(
				array(
					'uae' => array(
						'product_name'        => 'Ultimate Addons for Elementor Pro',
						'path'                => UAEL_DIR . 'admin/bsf-analytics',
						'author'              => 'Ultimate Addons for Elementor',
						'time_to_display'     => '+24 hours',
						'deactivation_survey' => array(
							array(
								'id'                => 'deactivation-survey-ultimate-elementor', // 'deactivation-survey-<your-plugin-slug>'
								'popup_logo'        => UAEL_URL . 'assets/images/settings/logo.svg',
								'plugin_slug'       => 'ultimate-elementor', // <your-plugin-slug>
								'plugin_version'    => UAEL_VER,
								'popup_title'       => 'Quick Feedback',
								'support_url'       => 'https://ultimateelementor.com/contact/',
								'popup_description' => 'If you have a moment, please share why you are deactivating Ultimate Addons for Elementor Pro:',
								'show_on_screens'   => array( 'plugins' ),
							),
						),
						'hide_optin_checkbox' => true,
					),
				)
			);

			add_filter( 'bsf_core_stats', array( $this, 'add_uae_analytics_data' ) );

			// Detect state-based events on admin load (dedup prevents repeat tracking).
			$this->detect_state_events();
		}

		/**
		 * Migrates analytics tracking option from 'bsf_usage_optin' to 'uae_usage_optin'.
		 *
		 * Checks if the old analytics tracking option ('bsf_usage_optin') is set to 'yes'
		 * and if the new option ('uae_usage_optin') is not already set.
		 * If so, updates the new tracking option to 'yes' to maintain user consent during migration.
		 *
		 * @since 1.39.8
		 * @access public
		 *
		 * @return void
		 */
		public function maybe_migrate_analytics_tracking() {
			$old_tracking = get_option( 'bsf_usage_optin', false );
			$new_tracking = get_option( 'uae_usage_optin', false );
			if ( 'yes' === $old_tracking && false === $new_tracking ) {
				update_option( 'uae_usage_optin', 'yes' );
				$time = get_option( 'bsf_usage_installed_time' );
				update_option( 'bsf_usage_installed_time', $time );
			}
		}

		/**
		 * Callback function to add specific analytics data.
		 *
		 * @param array $stats_data existing stats_data.
		 * @since 1.39.3
		 * @return array
		 */
		public function add_uae_analytics_data( $stats_data ) {
			$stats_data['plugin_data']['uae'] = array(
				'free_version'          => ( defined( 'HFE_VER' ) ? HFE_VER : '' ),
				'pro_version'           => UAEL_VER,
				'site_language'         => get_locale(),
				'elementor_version'     => ( defined( 'ELEMENTOR_VERSION' ) ? ELEMENTOR_VERSION : '' ),
				'elementor_pro_version' => ( defined( 'ELEMENTOR_PRO_VERSION' ) ? ELEMENTOR_PRO_VERSION : '' ),
				'onboarding_triggered'  => ( 'yes' === get_option( 'uaepro_onboarding_triggered' ) ) ? 'yes' : 'no',
				'active_theme'          => get_template(),
				'is_white_labeled'      => $this->is_white_labeled(),
			);

			$fetch_elementor_data = $this->uael_get_widgets_usage();
			foreach ( $fetch_elementor_data as $key => $value ) {
				$stats_data['plugin_data']['uae']['numeric_values'][ $key ] = $value;
			}

			// Add KPI tracking data.
			$kpi_data = $this->get_kpi_tracking_data();
			if ( ! empty( $kpi_data ) ) {
				$stats_data['plugin_data']['uae']['kpi_records'] = $kpi_data;
			}

			// Flush pending events into payload (only if any exist).
			$pending_events = UAEL_Analytics_Events::flush_pending();
			if ( ! empty( $pending_events ) ) {
				$stats_data['plugin_data']['uae']['events_record'] = $pending_events;
			}
			return $stats_data;
		}

		/**
		 * Detect state-based events that can't use direct hooks.
		 * Uses dedup in UAEL_Analytics_Events::track() — safe to call repeatedly.
		 *
		 * @since 1.44.2
		 * @return void
		 */
		private function detect_state_events() {
			// onboarding_completed: detect completed state.
			if ( 'yes' === get_option( 'uaepro_onboarding_triggered' ) ) {
				UAEL_Analytics_Events::track( 'onboarding_completed' );
			}
		}

		/**
		 * Check if the plugin is white labeled.
		 *
		 * @since 1.44.2
		 * @return bool
		 */
		private function is_white_labeled() {
			if ( class_exists( '\UltimateElementor\Classes\UAEL_Helper' )
				&& method_exists( '\UltimateElementor\Classes\UAEL_Helper', 'get_white_labels' )
			) {
				$branding = \UltimateElementor\Classes\UAEL_Helper::get_white_labels();
				return ! empty( $branding['plugin']['name'] );
			}
			return false;
		}

		/**
		 * Get KPI tracking data for the last 2 days (excluding today).
		 *
		 * Reads pre-recorded daily snapshots from the database.
		 * Each day's data was captured on that actual day via cron.
		 *
		 * @since 1.43.1
		 * @return array KPI data organized by date.
		 */
		private function get_kpi_tracking_data() {
			$snapshots = get_option( 'uael_kpi_daily_snapshots', array() );

			if ( empty( $snapshots ) || ! is_array( $snapshots ) ) {
				return array();
			}

			$kpi_data = array();
			$today    = current_time( 'Y-m-d' );

			// Only send data for dates that have actual per-day snapshots.
			for ( $i = 1; $i <= 2; $i++ ) {
				$date = gmdate( 'Y-m-d', strtotime( $today . ' -' . $i . ' days' ) );

				if ( ! isset( $snapshots[ $date ]['numeric_values'] ) ) {
					continue;
				}

				$kpi_data[ $date ] = $snapshots[ $date ];
			}

			return $kpi_data;
		}

		/**
		 * Fetch Elementor widget usage data.
		 *
		 * @since 1.39.3
		 * @return array Widget usage data.
		 */
		private function uael_get_widgets_usage() {
				$get_widgets = get_option( 'uaepro_widgets_usage_data_option', array() );
				return $get_widgets;
		}
	}
}
new UAEL_Analytics();
