<?php

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

class AIEO_DMM_Session_Analytics extends AIEO_DMM_Module_Base {

	public function get_id()       { return 'session_analytics'; }
	public function get_label()    { return __( 'Session Analytics', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 35; } 
	public function get_group()    { return 'attribution'; }

	public function render_subtab() {
		$proc = $this->processor();
		$data = array( 'available' => false );

		if ( $proc ) {
			
			$proc->create_stored_procedures();
			$data = array(
				'available'  => true,
				'summary'    => $proc->get_analytics_summary(),
				'conversion' => $proc->get_product_rankings( 'conversion', 'top', 20 ),
				'engagement' => $proc->get_product_rankings( 'engagement', 'top', 20 ),
				'bounce'     => $proc->get_product_rankings( 'bounce', 'top', 20 ),
				'nonce'      => wp_create_nonce( 'aieo_session_analytics' ),
			);
		}

		
		
		
		
		global $wpdb;
		$vt = $wpdb->prefix . 'aieo_core_content_vitals';
		$data['content'] = array();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $vt ) ) === $vt ) {
			foreach ( array(
				'engagement' => 'engagement_score',
				'demand'     => 'content_demand',
				'goals'      => 'goals_30d',
			) as $k => $col ) {
				
				$rows = $wpdb->get_results(
					"SELECT content_id, post_type, title, visitors_30d, engagement_score,
							goals_30d, goal_rate_30d, content_demand
					   FROM `{$vt}`
					  WHERE visitors_30d > 0
					  ORDER BY `{$col}` DESC, visitors_30d DESC
					  LIMIT 20",
					ARRAY_A
				);
				if ( ! empty( $rows ) ) {
					$data['content'][ $k ] = $rows;
				}
			}
		}

		$this->render_template( 'session-analytics.php', array( 'data' => $data ) );
	}

	
	private function processor() {
		if ( ! class_exists( 'AIEO_Session_Analytics_Processor' ) ) {
			$f = AIEO_DIR . 'includes/class-session-analytics-processor.php';
			if ( file_exists( $f ) ) {
				require_once $f;
			}
		}
		return class_exists( 'AIEO_Session_Analytics_Processor' )
			? AIEO_Session_Analytics_Processor::get_instance()
			: null;
	}
}
