<?php
/**
 * Sifency Addons Widget Analytics Tracker
 *
 * Tracks widget usage, page performance, and provides analytics dashboard.
 *
 * @package Sifency_Addons
 * @subpackage Analytics
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_Widget_Analytics {

	/**
	 * Initialize analytics tracking
	 */
	public static function init() {
		add_action( 'elementor/editor/after_save', array( __CLASS__, 'track_widgets_on_save' ) );
		add_action( 'elementor/frontend/after_enqueue_styles', array( __CLASS__, 'track_widgets_frontend' ) );
		add_filter( 'sifency_addons/analytics_data', array( __CLASS__, 'get_analytics_data' ) );
	}

	/**
	 * Track widgets when page is saved in Elementor editor
	 */
	public static function track_widgets_on_save( $post ) {
		if ( ! $post ) {
			return;
		}

		// Get all widgets used on this page
		$widgets = self::get_page_widgets( $post->ID );

		if ( ! empty( $widgets ) ) {
			self::record_widget_usage( $post->ID, $widgets );
		}
	}

	/**
	 * Track widgets when page is viewed on frontend
	 */
	public static function track_widgets_frontend() {
		global $post;

		if ( ! $post ) {
			return;
		}

		// Get all widgets rendered on this page
		$widgets = self::get_page_widgets( $post->ID );

		if ( ! empty( $widgets ) ) {
			self::record_widget_usage( $post->ID, $widgets );
		}
	}

	/**
	 * Get widgets used on a specific page
	 */
	public static function get_page_widgets( $post_id ) {
		if ( ! class_exists( '\Elementor\Plugin' ) ) {
			return array();
		}

		$elementor_instance = \Elementor\Plugin::instance();
		$document           = $elementor_instance->documents->get( $post_id );

		if ( ! $document || ! $document->is_built_with_elementor() ) {
			return array();
		}

		$widgets_data = $document->get_elements_data();
		$widgets      = array();

		self::extract_widgets_recursive( $widgets_data, $widgets );

		return $widgets;
	}

	/**
	 * Recursively extract widget names from elements
	 */
	private static function extract_widgets_recursive( $elements, &$widgets ) {
		foreach ( $elements as $element ) {
			if ( isset( $element['widgetType'] ) ) {
				$widget_name = $element['widgetType'];
				if ( ! isset( $widgets[ $widget_name ] ) ) {
					$widgets[ $widget_name ] = 0;
				}
				$widgets[ $widget_name ]++;
			}

			if ( isset( $element['elements'] ) ) {
				self::extract_widgets_recursive( $element['elements'], $widgets );
			}
		}
	}

	/**
	 * Record widget usage in database
	 */
	private static function record_widget_usage( $post_id, $widgets ) {
		$analytics_option = get_option( 'sifency_addons_widget_analytics', array() );

		if ( ! is_array( $analytics_option ) ) {
			$analytics_option = array();
		}

		foreach ( $widgets as $widget_name => $count ) {
			if ( ! isset( $analytics_option[ $widget_name ] ) ) {
				$analytics_option[ $widget_name ] = array(
					'name'        => $widget_name,
					'usage_count' => 0,
					'pages'       => array(),
					'first_used'  => current_time( 'mysql' ),
					'last_used'   => current_time( 'mysql' ),
				);
			}

			$analytics_option[ $widget_name ]['usage_count']++;
			$analytics_option[ $widget_name ]['last_used'] = current_time( 'mysql' );

			if ( ! in_array( $post_id, $analytics_option[ $widget_name ]['pages'], true ) ) {
				$analytics_option[ $widget_name ]['pages'][] = $post_id;
			}
		}

		update_option( 'sifency_addons_widget_analytics', $analytics_option );
	}

	/**
	 * Get analytics data
	 */
	public static function get_analytics_data() {
		$analytics = get_option( 'sifency_addons_widget_analytics', array() );

		// Sort by usage count
		uasort(
			$analytics,
			function( $a, $b ) {
				return $b['usage_count'] - $a['usage_count'];
			}
		);

		return array(
			'total_widgets_used' => count( $analytics ),
			'total_usages'       => array_sum( array_column( $analytics, 'usage_count' ) ),
			'widgets'            => $analytics,
			'most_used'          => array_slice( $analytics, 0, 10, true ),
			'least_used'         => array_slice( $analytics, -5, 5, true ),
		);
	}

	/**
	 * Reset analytics
	 */
	public static function reset_analytics() {
		delete_option( 'sifency_addons_widget_analytics' );
	}

	/**
	 * Get widget usage by category
	 */
	public static function get_usage_by_category() {
		if ( ! function_exists( 'Sifency_Addons_Get_All_Widgets' ) ) {
			return array();
		}

		$all_widgets = Sifency_Addons_Get_All_Widgets();
		$analytics   = get_option( 'sifency_addons_widget_analytics', array() );
		$by_category = array();

		foreach ( $all_widgets as $category => $widgets ) {
			$by_category[ $category ] = array(
				'total'       => count( $widgets ),
				'used'        => 0,
				'usage_count' => 0,
			);

			foreach ( $widgets as $widget_key => $widget_data ) {
				if ( isset( $analytics[ $widget_data['class'] ] ) ) {
					$by_category[ $category ]['used']++;
					$by_category[ $category ]['usage_count'] += $analytics[ $widget_data['class'] ]['usage_count'];
				}
			}
		}

		return $by_category;
	}

	/**
	 * Render analytics dashboard
	 */
	public static function render_dashboard() {
		$analytics_data = self::get_analytics_data();
		$category_data  = self::get_usage_by_category();
		?>
		<div class="sifency-analytics-dashboard">
			<h2><?php esc_html_e( 'Widget Analytics', 'sifency-addons' ); ?></h2>

			<!-- Summary Stats -->
			<div class="analytics-stats-grid">
				<div class="stat-card">
					<div class="stat-value"><?php echo count( $analytics_data['widgets'] ); ?></div>
					<div class="stat-label"><?php esc_html_e( 'Widgets Used', 'sifency-addons' ); ?></div>
				</div>
				<div class="stat-card">
					<div class="stat-value">
						<?php echo esc_html( array_sum( array_column( $analytics_data['widgets'], 'usage_count' ) ) ); ?>
					</div>
					<div class="stat-label"><?php esc_html_e( 'Total Uses', 'sifency-addons' ); ?></div>
				</div>
				<div class="stat-card">
					<div class="stat-value"><?php echo count( array_unique( array_merge( ...array_column( $analytics_data['widgets'], 'pages' ) ) ) ); ?></div>
					<div class="stat-label"><?php esc_html_e( 'Pages Using Widgets', 'sifency-addons' ); ?></div>
				</div>
			</div>

			<!-- Most Used Widgets -->
			<div class="analytics-section">
				<h3><?php esc_html_e( 'Most Used Widgets', 'sifency-addons' ); ?></h3>
				<table class="analytics-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Widget', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Usage Count', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Pages', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Last Used', 'sifency-addons' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $analytics_data['most_used'] as $widget_name => $widget_data ) : ?>
							<tr>
								<td><?php echo esc_html( $widget_name ); ?></td>
								<td><?php echo esc_html( $widget_data['usage_count'] ); ?></td>
								<td><?php echo count( $widget_data['pages'] ); ?></td>
								<td><?php echo esc_html( $widget_data['last_used'] ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<!-- Category Usage -->
			<div class="analytics-section">
				<h3><?php esc_html_e( 'Usage by Category', 'sifency-addons' ); ?></h3>
				<table class="analytics-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Category', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Total Widgets', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Used', 'sifency-addons' ); ?></th>
							<th><?php esc_html_e( 'Total Uses', 'sifency-addons' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $category_data as $category => $data ) : ?>
							<tr>
								<td><?php echo esc_html( $category ); ?></td>
								<td><?php echo esc_html( $data['total'] ); ?></td>
								<td><?php echo esc_html( $data['used'] ); ?></td>
								<td><?php echo esc_html( $data['usage_count'] ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<!-- Reset Button -->
			<div class="analytics-actions">
				<button class="button button-secondary" id="reset-analytics">
					<?php esc_html_e( 'Reset Analytics', 'sifency-addons' ); ?>
				</button>
			</div>
		</div>

		<script type="text/javascript">
			jQuery(document).ready(function($) {
				$('#reset-analytics').on('click', function(e) {
					e.preventDefault();
					if ( confirm('<?php esc_attr_e( 'Reset all analytics data? This cannot be undone.', 'sifency-addons' ); ?>') ) {
						// Make AJAX call to reset
						$.post(ajaxurl, {
							action: 'sifency_reset_analytics',
							nonce: '<?php echo esc_js( wp_create_nonce( 'sifency_reset_analytics' ) ); ?>'
						}, function(response) {
							if (response.success) {
								location.reload();
							}
						});
					}
				});
			});
		</script>
		<?php
	}
}
Sifency_Addons_Widget_Analytics::init();
