<?php


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

$data    = isset( $data ) && is_array( $data ) ? $data : array( 'available' => false );
$summary = isset( $data['summary'] ) ? $data['summary'] : null;
$nonce   = isset( $data['nonce'] ) ? (string) $data['nonce'] : '';

$fmt_dt = static function ( $v ) {
	return $v ? esc_html( get_date_from_gmt( (string) $v ) ) : '—';
};
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Session Analytics', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:840px;">
		<?php esc_html_e( 'Product AND content engagement + conversion derived from on-site session tracking. Rebuilt nightly; click Rebuild to refresh both now.', 'ai-eshop-optimizer' ); ?>
	</p>

	<p>
		<button type="button" class="button button-primary" id="aieo-sa-rebuild"><?php esc_html_e( 'Rebuild now', 'ai-eshop-optimizer' ); ?></button>
		<span id="aieo-sa-msg" style="margin-left:10px;"></span>
	</p>
	<div id="aieo-sa-progress" style="display:none;max-width:560px;margin:6px 0 0;">
		<div style="background:#e1e1e1;border-radius:6px;height:14px;overflow:hidden;">
			<div id="aieo-sa-bar" style="background:#2271b1;height:100%;width:0;transition:width .3s ease;"></div>
		</div>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Overview', 'ai-eshop-optimizer' ); ?></h3>
		<?php if ( $summary ) : ?>
			<table class="widefat striped" style="max-width:560px;">
				<tbody>
					<tr><td><?php esc_html_e( 'Sessions tracked', 'ai-eshop-optimizer' ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( (int) ( $summary->total_sessions ?? 0 ) ) ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Raw events', 'ai-eshop-optimizer' ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( (int) ( $summary->total_events ?? 0 ) ) ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Journey rows', 'ai-eshop-optimizer' ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( (int) ( $summary->total_journey_records ?? 0 ) ) ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Products with metrics', 'ai-eshop-optimizer' ); ?></td><td class="num"><?php echo esc_html( number_format_i18n( (int) ( $summary->products_with_metrics ?? 0 ) ) ); ?></td></tr>
					<tr><td><?php esc_html_e( 'Metrics last updated', 'ai-eshop-optimizer' ); ?></td><td class="num"><?php echo $fmt_dt( $summary->metrics_last_updated ?? null ); ?></td></tr>
				</tbody>
			</table>
		<?php else : ?>
			<p class="description"><?php esc_html_e( 'No analytics yet — click Rebuild now (needs tracked sessions).', 'ai-eshop-optimizer' ); ?></p>
		<?php endif; ?>
	</div>

	<?php
	$sections = array(
		array( __( 'Top converters (view → cart)', 'ai-eshop-optimizer' ), isset( $data['conversion'] ) ? $data['conversion'] : array(), 'conversion' ),
		array( __( 'Most engaging products', 'ai-eshop-optimizer' ), isset( $data['engagement'] ) ? $data['engagement'] : array(), 'engagement' ),
		array( __( 'Lowest bounce', 'ai-eshop-optimizer' ), isset( $data['bounce'] ) ? $data['bounce'] : array(), 'bounce' ),
	);
	foreach ( $sections as $sec ) :
		list( $title, $rows, $type ) = $sec;
		$export_url = add_query_arg(
			array(
				'action'   => 'aieo_session_analytics_export',
				'type'     => $type,
				'_wpnonce' => $nonce,
			),
			admin_url( 'admin-ajax.php' )
		);
		?>
		<div class="aieo-dmm-card">
			<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;">
				<h3 style="margin:0;"><?php echo esc_html( $title ); ?></h3>
				<?php if ( ! empty( $rows ) ) : ?>
					<a class="button button-small" href="<?php echo esc_url( $export_url ); ?>"><?php esc_html_e( 'Export XLSX', 'ai-eshop-optimizer' ); ?></a>
				<?php endif; ?>
			</div>
			<?php if ( ! empty( $rows ) ) : ?>
				<table class="widefat striped aieo-sa-sortable">
					<thead><tr>
						<th><?php esc_html_e( 'Product', 'ai-eshop-optimizer' ); ?></th>
						<th class="num"><?php esc_html_e( 'Views', 'ai-eshop-optimizer' ); ?></th>
						<?php if ( 'conversion' === $type ) : ?>
							<th class="num"><?php esc_html_e( 'Add-to-cart', 'ai-eshop-optimizer' ); ?></th>
							<th class="num"><?php esc_html_e( 'Conv. rate %', 'ai-eshop-optimizer' ); ?></th>
						<?php elseif ( 'engagement' === $type ) : ?>
							<th class="num"><?php esc_html_e( 'Engagement', 'ai-eshop-optimizer' ); ?></th>
							<th class="num"><?php esc_html_e( 'Avg sec', 'ai-eshop-optimizer' ); ?></th>
							<th class="num"><?php esc_html_e( 'Avg scroll %', 'ai-eshop-optimizer' ); ?></th>
						<?php else : ?>
							<th class="num"><?php esc_html_e( 'Landings', 'ai-eshop-optimizer' ); ?></th>
							<th class="num"><?php esc_html_e( 'Bounces', 'ai-eshop-optimizer' ); ?></th>
							<th class="num"><?php esc_html_e( 'Bounce %', 'ai-eshop-optimizer' ); ?></th>
						<?php endif; ?>
					</tr></thead>
					<tbody>
					<?php foreach ( $rows as $r ) :
						$pid   = (int) ( $r->product_id ?? 0 );
						$name  = ! empty( $r->product_name ) ? $r->product_name : ( '#' . $pid );
						$views = (int) ( $r->total_views ?? 0 );
						?>
						<tr>
							<td data-sort="<?php echo esc_attr( function_exists( 'mb_strtolower' ) ? mb_strtolower( $name ) : strtolower( $name ) ); ?>">
								<?php if ( $pid ) : ?>
									<a href="<?php echo esc_url( get_permalink( $pid ) ); ?>" target="_blank" rel="noopener"><?php echo esc_html( $name ); ?></a>
								<?php else : ?>
									<?php echo esc_html( $name ); ?>
								<?php endif; ?>
							</td>
							<td class="num" data-sort="<?php echo esc_attr( $views ); ?>"><?php echo esc_html( number_format_i18n( $views ) ); ?></td>
							<?php if ( 'conversion' === $type ) :
								$atc = (int) ( $r->total_add_to_cart ?? 0 );
								$cr  = (float) ( $r->conversion_rate_pct ?? 0 );
								?>
								<td class="num" data-sort="<?php echo esc_attr( $atc ); ?>"><?php echo esc_html( number_format_i18n( $atc ) ); ?></td>
								<td class="num" data-sort="<?php echo esc_attr( $cr ); ?>"><?php echo esc_html( number_format_i18n( $cr, 2 ) ); ?></td>
							<?php elseif ( 'engagement' === $type ) :
								$eng  = (float) ( $r->engagement_score ?? 0 );
								$asec = (float) ( $r->avg_seconds_on_page ?? 0 );
								$ascr = (float) ( $r->avg_scroll_pct ?? 0 );
								?>
								<td class="num" data-sort="<?php echo esc_attr( $eng ); ?>"><?php echo esc_html( number_format_i18n( $eng, 2 ) ); ?></td>
								<td class="num" data-sort="<?php echo esc_attr( $asec ); ?>"><?php echo esc_html( number_format_i18n( $asec, 1 ) ); ?></td>
								<td class="num" data-sort="<?php echo esc_attr( $ascr ); ?>"><?php echo esc_html( number_format_i18n( $ascr, 1 ) ); ?></td>
							<?php else :
								$land  = (int) ( $r->landing_count ?? 0 );
								$boun  = (int) ( $r->bounce_count ?? 0 );
								$brate = (float) ( $r->bounce_rate_pct ?? 0 );
								?>
								<td class="num" data-sort="<?php echo esc_attr( $land ); ?>"><?php echo esc_html( number_format_i18n( $land ) ); ?></td>
								<td class="num" data-sort="<?php echo esc_attr( $boun ); ?>"><?php echo esc_html( number_format_i18n( $boun ) ); ?></td>
								<td class="num" data-sort="<?php echo esc_attr( $brate ); ?>"><?php echo esc_html( number_format_i18n( $brate, 2 ) ); ?></td>
							<?php endif; ?>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php else : ?>
				<p class="description"><?php esc_html_e( 'No data yet (rankings need ≥10 views per product for significance).', 'ai-eshop-optimizer' ); ?></p>
			<?php endif; ?>
		</div>
	<?php endforeach; ?>
</div>

<script>
jQuery(function($){
	var $b = $('#aieo-sa-rebuild'), $msg = $('#aieo-sa-msg'),
	    $prog = $('#aieo-sa-progress'), $bar = $('#aieo-sa-bar'),
	    nonce = '<?php echo esc_js( $nonce ); ?>';

	function step( restart ){
		$.post( ajaxurl, { action:'aieo_session_analytics_rebuild', _wpnonce:nonce, restart: restart ? 1 : 0 }, function( resp ){
			if ( ! resp || ! resp.success ) {
				$b.prop('disabled', false); $prog.hide();
				$msg.css('color','#b91c1c').text( ( resp && resp.data && resp.data.message ) || 'Error' );
				return;
			}
			var d = resp.data;
			$msg.css('color','').text( d.message );
			if ( d.complete ) {
				$bar.css('width','100%');
				setTimeout(function(){ location.reload(); }, 700);
				return;
			}
			var pct = d.total > 0 ? Math.min( 99, Math.round( d.processed / d.total * 100 ) ) : 5;
			$bar.css('width', pct + '%');
			setTimeout(function(){ step( false ); }, 350);
		}).fail(function(){
			$b.prop('disabled', false); $prog.hide();
			$msg.css('color','#b91c1c').text('<?php echo esc_js( __( 'Network error.', 'ai-eshop-optimizer' ) ); ?>');
		});
	}

	$b.on('click', function(){
		$b.prop('disabled', true); $prog.show(); $bar.css('width','0');
		$msg.css('color','').text('<?php echo esc_js( __( 'Starting…', 'ai-eshop-optimizer' ) ); ?>');
		step( true );
	});
});
</script>

<?php



$aieo_content_secs = array(
	'engagement' => __( 'Top content by engagement', 'ai-eshop-optimizer' ),
	'demand'     => __( 'Top content by demand', 'ai-eshop-optimizer' ),
	'goals'      => __( 'Top content by goal conversions', 'ai-eshop-optimizer' ),
);
if ( empty( $data['content'] ) ) : ?>
	<h2 style="margin-top:24px;"><?php esc_html_e( 'Content session analytics', 'ai-eshop-optimizer' ); ?></h2>
	<div class="aieo-dmm-card"><p><?php esc_html_e( 'No content vitals yet - they build from tracked page views (nightly, or click Rebuild now above). Once built: top content by engagement, demand and goal conversions, for every post type.', 'ai-eshop-optimizer' ); ?></p></div>
<?php else : ?>
	<h2 style="margin-top:24px;"><?php esc_html_e( 'Content session analytics', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description"><?php esc_html_e( 'Posts, pages and custom types — engagement, demand and goal conversions from the daily content vitals (rebuilt nightly from the same session stream).', 'ai-eshop-optimizer' ); ?></p>
	<?php foreach ( $aieo_content_secs as $aieo_ck => $aieo_ct ) :
		if ( empty( $data['content'][ $aieo_ck ] ) ) { continue; } ?>
		<div class="aieo-dmm-card">
			<h3 style="margin:0 0 8px;"><?php echo esc_html( $aieo_ct ); ?></h3>
			<table class="widefat striped aieo-sa-sortable">
				<thead><tr>
					<th><?php esc_html_e( 'Content', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Type', 'ai-eshop-optimizer' ); ?></th>
					<th class="num"><?php esc_html_e( 'Visitors 30d', 'ai-eshop-optimizer' ); ?></th>
					<th class="num"><?php esc_html_e( 'Engagement', 'ai-eshop-optimizer' ); ?></th>
					<th class="num"><?php esc_html_e( 'Goals 30d', 'ai-eshop-optimizer' ); ?></th>
					<th class="num"><?php esc_html_e( 'Goal rate %', 'ai-eshop-optimizer' ); ?></th>
					<th class="num"><?php esc_html_e( 'Demand', 'ai-eshop-optimizer' ); ?></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $data['content'][ $aieo_ck ] as $aieo_r ) :
					$aieo_cid  = (int) $aieo_r['content_id'];
					$aieo_name = '' !== (string) $aieo_r['title'] ? (string) $aieo_r['title'] : ( '#' . $aieo_cid );
					?>
					<tr>
						<td data-sort="<?php echo esc_attr( function_exists( 'mb_strtolower' ) ? mb_strtolower( $aieo_name ) : strtolower( $aieo_name ) ); ?>">
							<a href="<?php echo esc_url( get_permalink( $aieo_cid ) ); ?>" target="_blank" rel="noopener"><?php echo esc_html( $aieo_name ); ?></a>
						</td>
						<td><?php echo esc_html( $aieo_r['post_type'] ); ?></td>
						<td class="num" data-sort="<?php echo esc_attr( (int) $aieo_r['visitors_30d'] ); ?>"><?php echo esc_html( number_format_i18n( (int) $aieo_r['visitors_30d'] ) ); ?></td>
						<td class="num" data-sort="<?php echo esc_attr( (float) $aieo_r['engagement_score'] ); ?>"><?php echo esc_html( number_format_i18n( (float) $aieo_r['engagement_score'], 2 ) ); ?></td>
						<td class="num" data-sort="<?php echo esc_attr( (int) $aieo_r['goals_30d'] ); ?>"><?php echo esc_html( number_format_i18n( (int) $aieo_r['goals_30d'] ) ); ?></td>
						<td class="num" data-sort="<?php echo esc_attr( (float) $aieo_r['goal_rate_30d'] ); ?>"><?php echo esc_html( number_format_i18n( 100 * (float) $aieo_r['goal_rate_30d'], 2 ) ); ?></td>
						<td class="num" data-sort="<?php echo esc_attr( (int) $aieo_r['content_demand'] ); ?>"><?php echo esc_html( (int) $aieo_r['content_demand'] ); ?></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	<?php endforeach; ?>
<?php endif; ?>

<script>
/* Click-to-sort for the ranking tables. Sorts on each cell's data-sort value
   (the raw number / lowercased name) so locale number formatting never breaks it. */
(function(){
	function sortTable( table, col, th ){
		var numeric = th.classList.contains('num');
		var asc = th.getAttribute('data-dir') !== 'asc';
		var heads = table.querySelectorAll('thead th');
		for ( var i = 0; i < heads.length; i++ ) {
			heads[i].removeAttribute('data-dir');
			var old = heads[i].querySelector('.aieo-sa-arrow');
			if ( old ) { old.parentNode.removeChild( old ); }
		}
		th.setAttribute('data-dir', asc ? 'asc' : 'desc');
		var arrow = document.createElement('span');
		arrow.className = 'aieo-sa-arrow';
		arrow.textContent = asc ? ' ▲' : ' ▼';
		th.appendChild( arrow );
		var tbody = table.querySelector('tbody');
		var rows = Array.prototype.slice.call( tbody.querySelectorAll('tr') );
		rows.sort( function( a, b ){
			var ac = a.children[col], bc = b.children[col];
			var av = ac ? ( ac.getAttribute('data-sort') !== null ? ac.getAttribute('data-sort') : ac.textContent.trim() ) : '';
			var bv = bc ? ( bc.getAttribute('data-sort') !== null ? bc.getAttribute('data-sort') : bc.textContent.trim() ) : '';
			if ( numeric ) {
				var an = parseFloat( av ) || 0, bn = parseFloat( bv ) || 0;
				return asc ? an - bn : bn - an;
			}
			return asc ? String( av ).localeCompare( String( bv ) ) : String( bv ).localeCompare( String( av ) );
		} );
		for ( var j = 0; j < rows.length; j++ ) { tbody.appendChild( rows[j] ); }
	}
	var tables = document.querySelectorAll('table.aieo-sa-sortable');
	for ( var t = 0; t < tables.length; t++ ) {
		( function( table ){
			var ths = table.querySelectorAll('thead th');
			for ( var c = 0; c < ths.length; c++ ) {
				( function( th, col ){
					th.style.cursor = 'pointer';
					th.style.whiteSpace = 'nowrap';
					th.title = '<?php echo esc_js( __( 'Click to sort', 'ai-eshop-optimizer' ) ); ?>';
					th.addEventListener('click', function(){ sortTable( table, col, th ); });
				} )( ths[c], c );
			}
		} )( tables[t] );
	}
})();
</script>
