<?php

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

class AIEO_DMM_Plugin_Usage extends AIEO_DMM_Module_Base {

	const TABLE          = 'aieo_admin_audit';
	const SCHEMA_OPTION  = 'aieo_admin_audit_db';
	const SCHEMA_VERSION = 1;
	const LAST_TAB_META  = 'aieo_dmm_last_tab';  
	const SESSION_META   = 'aieo_audit_session'; 
	const SEEN_META      = 'aieo_audit_seen';    
	const SESSION_GAP    = 1800;                 
	const RETENTION_DAYS = 180;
	const CRON_HOOK      = 'aieo_admin_audit_prune';

	public function get_id()       { return 'plugin_usage'; }
	public function get_label()    { return __( 'Plugin Usage', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 8; } 
	public function get_group()    { return 'tools'; }

	
	public static function table() {
		global $wpdb;
		return $wpdb->prefix . self::TABLE;
	}

	public function register_hooks() {
		
		
		add_action( 'admin_init', array( $this, 'maybe_install' ), 1 );
		add_action( 'admin_init', array( $this, 'log_visit' ), 20 );

		
		add_action( self::CRON_HOOK, array( $this, 'prune' ) );
		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CRON_HOOK );
		}
	}

	
	
	

	public function maybe_install() {
		if ( (int) get_option( self::SCHEMA_OPTION ) >= self::SCHEMA_VERSION ) { return; }

		global $wpdb;
		$table   = self::table();
		$collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			user_id BIGINT UNSIGNED NOT NULL,
			page VARCHAR(64) NOT NULL DEFAULT '',
			tab VARCHAR(64) NOT NULL DEFAULT '',
			session_id INT UNSIGNED NOT NULL DEFAULT 0,
			viewed_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY user_time (user_id, viewed_at),
			KEY viewed (viewed_at),
			KEY tab (tab)
		) {$collate};";

		if ( function_exists( 'aieo_dbdelta' ) ) {
			aieo_dbdelta( $sql );
		} else {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			dbDelta( $sql );
		}
		update_option( self::SCHEMA_OPTION, self::SCHEMA_VERSION, false );
	}

	
	
	

	
	public function log_visit() {
		if ( wp_doing_ajax() ) { return; }
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && strtoupper( (string) $_SERVER['REQUEST_METHOD'] ) !== 'GET' ) { return; }

		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; 
		if ( $page === '' || ( strpos( $page, 'ai-eshop-' ) !== 0 && strpos( $page, 'aieo-' ) !== 0 ) ) { return; }

		$uid = get_current_user_id();
		if ( ! $uid ) { return; }

		$tab = isset( $_GET['dmm_tab'] ) ? sanitize_key( wp_unslash( $_GET['dmm_tab'] ) ) : ''; 

		
		$now  = time();
		$seen = (int) get_user_meta( $uid, self::SEEN_META, true );
		$sess = (int) get_user_meta( $uid, self::SESSION_META, true );
		if ( ! $sess || ( $now - $seen ) > self::SESSION_GAP ) {
			$sess++;
			update_user_meta( $uid, self::SESSION_META, $sess );
		}
		update_user_meta( $uid, self::SEEN_META, $now );

		global $wpdb;
		$wpdb->insert(
			self::table(),
			array(
				'user_id'    => $uid,
				'page'       => $page,
				'tab'        => $tab,
				'session_id' => $sess,
				'viewed_at'  => current_time( 'mysql', true ), 
			),
			array( '%d', '%s', '%s', '%d', '%s' )
		);

		
		if ( $page === AIEO_DMM::MENU_SLUG && $tab !== '' ) {
			update_user_meta( $uid, self::LAST_TAB_META, $tab );
		}
	}

	
	public static function last_tab_for_user( $uid ) {
		return $uid ? (string) get_user_meta( (int) $uid, self::LAST_TAB_META, true ) : '';
	}

	public function prune() {
		global $wpdb;
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - self::RETENTION_DAYS * DAY_IN_SECONDS );
		
		$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::table() . ' WHERE viewed_at < %s', $cutoff ) );
	}

	
	
	

	
	private function page_labels() {
		return array(
			'ai-eshop-optimizer'          => __( 'Data Prep & Analytics', 'ai-eshop-optimizer' ),
			'ai-eshop-dmm'                => __( 'e-Shop Manager', 'ai-eshop-optimizer' ),
			'ai-eshop-chat'               => __( 'AI Chat', 'ai-eshop-optimizer' ),
			'aieo-iapi'                   => __( 'Interactivity (IAPI)', 'ai-eshop-optimizer' ),
			'aieo-recommendations-cache'  => __( 'Recommendations Cache', 'ai-eshop-optimizer' ),
		);
	}

	public function render_subtab() {
		if ( ! current_user_can( 'manage_options' ) ) {
			echo '<div class="aieo-dmm-section"><div class="aieo-dmm-card"><h3 style="margin-top:0;">'
				. esc_html__( 'Plugin usage', 'ai-eshop-optimizer' ) . '</h3><p>'
				. esc_html__( 'This panel is available to site administrators only.', 'ai-eshop-optimizer' )
				. '</p></div></div>';
			return;
		}

		$this->maybe_install();

		
		$ranges = array( 7 => __( '7 days', 'ai-eshop-optimizer' ), 30 => __( '30 days', 'ai-eshop-optimizer' ), 90 => __( '90 days', 'ai-eshop-optimizer' ), 365 => __( '1 year', 'ai-eshop-optimizer' ), 0 => __( 'All time', 'ai-eshop-optimizer' ) );
		$days   = isset( $_GET['audit_days'] ) ? max( 0, min( 3650, (int) $_GET['audit_days'] ) ) : 30; 
		if ( ! isset( $ranges[ $days ] ) ) { $ranges[ $days ] = sprintf(  __( '%d days', 'ai-eshop-optimizer' ), $days ); }

		$r          = $this->report( $days );
		$mod_labels = AIEO_DMM::instance()->get_modules();
		$page_lbl   = $this->page_labels();
		$base_url   = AIEO_DMM::instance()->get_subtab_url( $this->get_id() );

		$card_label = function ( $tab ) use ( $mod_labels ) {
			return ( $tab !== '' && isset( $mod_labels[ $tab ] ) ) ? $mod_labels[ $tab ]->get_label() : ( $tab !== '' ? $tab : '—' );
		};
		$ago = function ( $gmt ) {
			if ( empty( $gmt ) ) { return '—'; }
			$ts = strtotime( $gmt . ' UTC' );
			return $ts ? sprintf(  __( '%s ago', 'ai-eshop-optimizer' ), human_time_diff( $ts ) ) : '—';
		};
		?>
		<div class="aieo-dmm-section">
			<div class="aieo-dmm-card" id="aieo-card-plugin-usage">
				<h3 style="margin-top:0;"><?php esc_html_e( 'Plugin usage', 'ai-eshop-optimizer' ); ?></h3>
				<p class="description" style="max-width:820px;">
					<?php esc_html_e( 'Who is using the plugin, and which panels. Admin page views only — no customer data. Visible to site administrators.', 'ai-eshop-optimizer' ); ?>
				</p>

				<p style="margin:12px 0 4px;">
					<?php
					foreach ( $ranges as $d => $lbl ) {
						$url = esc_url( add_query_arg( 'audit_days', $d, $base_url ) );
						$on  = ( (int) $d === (int) $days );
						echo '<a href="' . $url . '" class="button' . ( $on ? ' button-primary' : '' ) . '" style="margin:0 4px 4px 0;">' . esc_html( $lbl ) . '</a>';
					}
					?>
				</p>

				<?php
				
				$stat = function ( $label, $value ) {
					echo '<div style="flex:1 1 150px;min-width:150px;background:#f6f7f7;border:1px solid #e2e4e7;border-radius:8px;padding:14px 16px;">';
					echo '<div style="font-size:26px;font-weight:600;line-height:1.1;color:#1d2327;">' . esc_html( $value ) . '</div>';
					echo '<div style="font-size:12px;color:#646970;margin-top:4px;">' . esc_html( $label ) . '</div>';
					echo '</div>';
				};
				?>
				<div style="display:flex;gap:12px;flex-wrap:wrap;margin:14px 0 6px;">
					<?php
					$stat( __( 'Page views', 'ai-eshop-optimizer' ),   number_format_i18n( (int) $r['totals']['visits'] ) );
					$stat( __( 'Active users', 'ai-eshop-optimizer' ), number_format_i18n( (int) $r['totals']['users'] ) );
					$stat( __( 'Sessions', 'ai-eshop-optimizer' ),     number_format_i18n( (int) $r['totals']['sessions'] ) );
					$stat( __( 'Cards opened', 'ai-eshop-optimizer' ), number_format_i18n( (int) $r['totals']['cards'] ) );
					?>
				</div>

				<?php if ( empty( $r['per_user'] ) ) : ?>
					<p class="description" style="margin-top:16px;"><?php esc_html_e( 'No activity recorded in this window yet — usage is logged from now on.', 'ai-eshop-optimizer' ); ?></p>
				<?php else : ?>

					<h4 style="margin:22px 0 6px;"><?php esc_html_e( 'By user', 'ai-eshop-optimizer' ); ?></h4>
					<table class="widefat striped" style="max-width:900px;">
						<thead><tr>
							<th><?php esc_html_e( 'User', 'ai-eshop-optimizer' ); ?></th>
							<th><?php esc_html_e( 'Role', 'ai-eshop-optimizer' ); ?></th>
							<th style="text-align:right;"><?php esc_html_e( 'Views', 'ai-eshop-optimizer' ); ?></th>
							<th style="text-align:right;"><?php esc_html_e( 'Sessions', 'ai-eshop-optimizer' ); ?></th>
							<th><?php esc_html_e( 'Last active', 'ai-eshop-optimizer' ); ?></th>
							<th><?php esc_html_e( 'Most-used card', 'ai-eshop-optimizer' ); ?></th>
						</tr></thead>
						<tbody>
						<?php foreach ( $r['per_user'] as $row ) :
							$u    = get_userdata( (int) $row['user_id'] );
							$name = $u ? $u->display_name : sprintf(  __( 'User #%d (removed)', 'ai-eshop-optimizer' ), (int) $row['user_id'] );
							$role = $u && ! empty( $u->roles ) ? implode( ', ', $u->roles ) : '—';
							$top  = isset( $r['user_top'][ $row['user_id'] ] ) ? $card_label( $r['user_top'][ $row['user_id'] ] ) : '—';
							?>
							<tr>
								<td><?php echo esc_html( $name ); ?></td>
								<td><?php echo esc_html( $role ); ?></td>
								<td style="text-align:right;"><?php echo esc_html( number_format_i18n( (int) $row['visits'] ) ); ?></td>
								<td style="text-align:right;"><?php echo esc_html( number_format_i18n( (int) $row['sessions'] ) ); ?></td>
								<td><?php echo esc_html( $ago( $row['last_seen'] ) ); ?></td>
								<td><?php echo esc_html( $top ); ?></td>
							</tr>
						<?php endforeach; ?>
						</tbody>
					</table>

					<div style="display:flex;gap:28px;flex-wrap:wrap;">
						<div>
							<h4 style="margin:22px 0 6px;"><?php esc_html_e( 'Most-used cards', 'ai-eshop-optimizer' ); ?></h4>
							<table class="widefat striped" style="min-width:360px;">
								<thead><tr>
									<th><?php esc_html_e( 'Card', 'ai-eshop-optimizer' ); ?></th>
									<th style="text-align:right;"><?php esc_html_e( 'Views', 'ai-eshop-optimizer' ); ?></th>
									<th style="text-align:right;"><?php esc_html_e( 'Users', 'ai-eshop-optimizer' ); ?></th>
								</tr></thead>
								<tbody>
								<?php foreach ( $r['top_cards'] as $c ) : ?>
									<tr>
										<td><?php echo esc_html( $card_label( $c['tab'] ) ); ?></td>
										<td style="text-align:right;"><?php echo esc_html( number_format_i18n( (int) $c['visits'] ) ); ?></td>
										<td style="text-align:right;"><?php echo esc_html( number_format_i18n( (int) $c['users'] ) ); ?></td>
									</tr>
								<?php endforeach; ?>
								</tbody>
							</table>
						</div>
						<div>
							<h4 style="margin:22px 0 6px;"><?php esc_html_e( 'By page', 'ai-eshop-optimizer' ); ?></h4>
							<table class="widefat striped" style="min-width:300px;">
								<thead><tr>
									<th><?php esc_html_e( 'Page', 'ai-eshop-optimizer' ); ?></th>
									<th style="text-align:right;"><?php esc_html_e( 'Views', 'ai-eshop-optimizer' ); ?></th>
								</tr></thead>
								<tbody>
								<?php foreach ( $r['by_page'] as $p ) :
									$plabel = isset( $page_lbl[ $p['page'] ] ) ? $page_lbl[ $p['page'] ] : $p['page'];
									?>
									<tr>
										<td><?php echo esc_html( $plabel ); ?></td>
										<td style="text-align:right;"><?php echo esc_html( number_format_i18n( (int) $p['visits'] ) ); ?></td>
									</tr>
								<?php endforeach; ?>
								</tbody>
							</table>
						</div>
					</div>

				<?php endif; ?>

				<p class="description" style="margin-top:18px;">
					<?php echo esc_html( sprintf(  __( 'Data is kept for %d days, then pruned automatically.', 'ai-eshop-optimizer' ), self::RETENTION_DAYS ) ); ?>
				</p>
			</div>
		</div>
		<?php
	}

	
	
	

	
	private function report( $days ) {
		global $wpdb;
		$t = self::table();

		$where = '1=1';
		$args  = array();
		if ( $days > 0 ) {
			$where  = 'viewed_at >= %s';
			$args[] = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS );
		}

		
		$totals = $wpdb->get_row(
			$args
				? $wpdb->prepare( "SELECT COUNT(*) visits, COUNT(DISTINCT user_id) users, COUNT(DISTINCT CONCAT(user_id,'-',session_id)) sessions, COUNT(DISTINCT CASE WHEN tab<>'' THEN tab END) cards FROM {$t} WHERE {$where}", $args )
				: "SELECT COUNT(*) visits, COUNT(DISTINCT user_id) users, COUNT(DISTINCT CONCAT(user_id,'-',session_id)) sessions, COUNT(DISTINCT CASE WHEN tab<>'' THEN tab END) cards FROM {$t}",
			ARRAY_A
		);

		$per_user = $wpdb->get_results(
			$args
				? $wpdb->prepare( "SELECT user_id, COUNT(*) visits, COUNT(DISTINCT session_id) sessions, MAX(viewed_at) last_seen FROM {$t} WHERE {$where} GROUP BY user_id ORDER BY visits DESC", $args )
				: "SELECT user_id, COUNT(*) visits, COUNT(DISTINCT session_id) sessions, MAX(viewed_at) last_seen FROM {$t} GROUP BY user_id ORDER BY visits DESC",
			ARRAY_A
		);

		$top_cards = $wpdb->get_results(
			$args
				? $wpdb->prepare( "SELECT tab, COUNT(*) visits, COUNT(DISTINCT user_id) users FROM {$t} WHERE {$where} AND tab<>'' GROUP BY tab ORDER BY visits DESC LIMIT 20", $args )
				: "SELECT tab, COUNT(*) visits, COUNT(DISTINCT user_id) users FROM {$t} WHERE tab<>'' GROUP BY tab ORDER BY visits DESC LIMIT 20",
			ARRAY_A
		);

		$by_page = $wpdb->get_results(
			$args
				? $wpdb->prepare( "SELECT page, COUNT(*) visits FROM {$t} WHERE {$where} GROUP BY page ORDER BY visits DESC", $args )
				: "SELECT page, COUNT(*) visits FROM {$t} GROUP BY page ORDER BY visits DESC",
			ARRAY_A
		);

		
		$rows = $wpdb->get_results(
			$args
				? $wpdb->prepare( "SELECT user_id, tab, COUNT(*) c FROM {$t} WHERE {$where} AND tab<>'' GROUP BY user_id, tab", $args )
				: "SELECT user_id, tab, COUNT(*) c FROM {$t} WHERE tab<>'' GROUP BY user_id, tab",
			ARRAY_A
		);
		
		$user_top = array();
		$best     = array();
		foreach ( (array) $rows as $row ) {
			$uid = (int) $row['user_id'];
			if ( ! isset( $best[ $uid ] ) || (int) $row['c'] > $best[ $uid ] ) {
				$best[ $uid ]     = (int) $row['c'];
				$user_top[ $uid ] = $row['tab'];
			}
		}

		return array(
			'totals'    => $totals ? $totals : array( 'visits' => 0, 'users' => 0, 'sessions' => 0, 'cards' => 0 ),
			'per_user'  => (array) $per_user,
			'top_cards' => (array) $top_cards,
			'by_page'   => (array) $by_page,
			'user_top'  => $user_top,
		);
	}
}
