<?php
/**
 * Dashboard settings class for usage statistics display.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Dashboard page for displaying usage statistics and achievements.
 *
 * @since 1.0.0
 */
class Settings_Dashboard extends Settings_Base {

	/**
	 * PayPal hosted button ID for donations.
	 *
	 * @var string
	 */
	private const PAYPAL_HOSTED_BUTTON_ID = 'DJ9GULXH8TZWC';

	/**
	 * Usage stats instance.
	 *
	 * @var Usage_Stats
	 */
	private Usage_Stats $usage_stats;

	/**
	 * Achievements instance.
	 *
	 * @var Achievements
	 */
	private Achievements $achievements;

	/**
	 * Cached dashboard data.
	 *
	 * @var array|null
	 */
	private ?array $dashboard_data = null;

	const CACHE_KEY = 'agenticwp_dashboard_data';
	const CACHE_TTL = 300;

	/**
	 * Initialize dashboard and register hooks.
	 */
	public function __construct() {
		$this->usage_stats  = Usage_Stats::get_instance();
		$this->achievements = Achievements::get_instance();

		add_action( 'admin_menu', array( $this, 'add_admin_menu' ), 9 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_dashboard_assets' ) );
		add_action( 'wp_ajax_agenticwp_get_chart_data', array( $this, 'handle_get_chart_data' ) );
		add_action( 'agentic_wp_after_tool_execution', array( $this, 'invalidate_cache' ), 30, 0 );
		add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widget' ) );
	}

	/**
	 * Registers the WordPress dashboard widget.
	 *
	 * @return void
	 */
	public function add_dashboard_widget(): void {
		if ( current_user_can( 'manage_options' ) ) {
			wp_add_dashboard_widget( 'agenticwp_stats_widget', __( 'Agentic WP Stats', 'agenticwp' ), array( $this, 'render_dashboard_widget' ) );
		}
	}

	/**
	 * Renders the WordPress dashboard widget content.
	 *
	 * @return void
	 */
	public function render_dashboard_widget(): void {
		$data       = $this->get_dashboard_data();
		$user_level = $this->usage_stats->get_user_level();
		$summary    = $this->achievements->get_achievement_summary();
		$stats      = array(
			array( $data['lifetime']['posts_created'], __( 'Drafts', 'agenticwp' ) ),
			array( $this->usage_stats->get_current_streak(), __( 'Day Streak', 'agenticwp' ) ),
			array( $summary['unlocked'] . '/' . $summary['total'], __( 'Achievements', 'agenticwp' ) ),
		);
		?>
		<div class="agenticwp-widget">
			<div class="agenticwp-widget-level">
				<?php /* translators: %d: level number */ ?>
				<span class="agenticwp-widget-level-badge"><?php printf( esc_html__( 'Level %d', 'agenticwp' ), (int) $user_level['level'] ); ?></span>
				<span class="agenticwp-widget-level-name"><?php echo esc_html( $user_level['name'] ); ?></span>
			</div>
			<div class="agenticwp-widget-stats">
				<?php foreach ( $stats as list( $value, $label ) ) : ?>
					<div class="agenticwp-widget-stat">
						<span class="agenticwp-widget-stat-value"><?php echo esc_html( is_numeric( $value ) ? number_format_i18n( $value ) : $value ); ?></span>
						<span class="agenticwp-widget-stat-label"><?php echo esc_html( $label ); ?></span>
					</div>
				<?php endforeach; ?>
				<a href="https://www.paypal.com/donate/?hosted_button_id=<?php echo esc_attr( self::PAYPAL_HOSTED_BUTTON_ID ); ?>" target="_blank" rel="noopener" class="agenticwp-widget-stat agenticwp-widget-stat--support">
					<span class="agenticwp-widget-stat-icon dashicons dashicons-heart"></span>
					<span class="agenticwp-widget-stat-label"><?php esc_html_e( 'Support', 'agenticwp' ); ?></span>
				</a>
			</div>
			<p class="agenticwp-widget-footer">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=agenticwp-dashboard' ) ); ?>"><?php esc_html_e( 'View Full Dashboard', 'agenticwp' ); ?> &rarr;</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Invalidates the dashboard cache.
	 *
	 * @return void
	 */
	public function invalidate_cache(): void {
		delete_transient( self::CACHE_KEY );
	}

	/**
	 * Get cached dashboard data with transient and in-memory caching.
	 *
	 * @return array Dashboard data including stats, daily, weekly, and lifetime.
	 */
	private function get_dashboard_data(): array {
		if ( null !== $this->dashboard_data ) {
			return $this->dashboard_data;
		}

		$cached = get_transient( self::CACHE_KEY );
		if ( false !== $cached && is_array( $cached ) ) {
			$this->dashboard_data = $cached;
			return $this->dashboard_data;
		}

		$stats                = $this->usage_stats->get_stats();
		$this->dashboard_data = array(
			'stats'    => $stats,
			'daily'    => $this->usage_stats->get_daily_stats(),
			'weekly'   => $this->usage_stats->get_weekly_stats(),
			'lifetime' => $stats['lifetime'],
			'streaks'  => $stats['streaks'],
		);
		set_transient( self::CACHE_KEY, $this->dashboard_data, self::CACHE_TTL );

		return $this->dashboard_data;
	}

	/**
	 * Add dashboard menu page.
	 *
	 * @return void
	 */
	public function add_admin_menu(): void {
		add_menu_page( __( 'Agentic WP Dashboard', 'agenticwp' ), __( 'Agentic WP', 'agenticwp' ), 'manage_options', 'agenticwp-dashboard', array( $this, 'render_dashboard' ), 'dashicons-superhero-alt', 30 );
		add_submenu_page( 'agenticwp-dashboard', __( 'Dashboard', 'agenticwp' ), __( 'Dashboard', 'agenticwp' ), 'manage_options', 'agenticwp-dashboard', array( $this, 'render_dashboard' ) );
	}

	/**
	 * Enqueue dashboard-specific assets.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_dashboard_assets( string $hook ): void {
		$version  = get_file_data( plugin_dir_path( __DIR__ ) . 'agenticwp.php', array( 'Version' => 'Version' ) )['Version'] ?: '1.0.0';
		$base_url = plugin_dir_url( __DIR__ );

		// Enqueue widget styles on WordPress dashboard.
		if ( 'index.php' === $hook ) {
			wp_enqueue_style( 'agenticwp-widget', $base_url . 'assets/css/admin/widget.css', array(), $version );
			return;
		}

		if ( 'toplevel_page_agenticwp-dashboard' !== $hook ) {
			return;
		}

		wp_enqueue_style( 'agenticwp-dashboard', $base_url . 'assets/css/admin/dashboard.css', array(), $version );
		wp_enqueue_script( 'chartjs', $base_url . 'assets/js/vendor/chart.min.js', array(), '4.4.1', true );
		wp_enqueue_script( 'agenticwp-dashboard-charts', $base_url . 'assets/js/admin/dashboard-charts.js', array( 'jquery', 'chartjs' ), $version, true );
		wp_enqueue_script( 'agenticwp-dashboard-gamification', $base_url . 'assets/js/admin/dashboard-gamification.js', array( 'jquery' ), $version, true );
		wp_enqueue_script( 'agenticwp-tip-jar', $base_url . 'assets/js/admin/tip-jar.js', array(), $version, true );
		wp_localize_script( 'agenticwp-tip-jar', 'agenticwp_tip_jar', array( 'version' => $version ) );

		$data = $this->get_dashboard_data();
		wp_localize_script(
			'agenticwp-dashboard-charts',
			'agenticwpDashboard',
			array(
				'ajaxUrl'         => admin_url( 'admin-ajax.php' ),
				'chartNonce'      => wp_create_nonce( 'agenticwp_chart_data' ),
				'daily'           => $data['daily'],
				'weekly'          => $data['weekly'],
				'lifetime'        => $data['lifetime'],
				'newAchievements' => $this->get_and_clear_new_achievements(),
			)
		);
	}

	/**
	 * Gets and clears newly unlocked achievements for display.
	 *
	 * @return array Array of achievement data to display.
	 */
	private function get_and_clear_new_achievements(): array {
		$transient_key   = 'agenticwp_new_achievements_' . get_current_user_id();
		$achievement_ids = get_transient( $transient_key );

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

		delete_transient( $transient_key );

		$achievements = array();
		foreach ( $achievement_ids as $id ) {
			$achievement = $this->achievements->get_achievement( $id );
			if ( $achievement ) {
				$achievements[] = array(
					'id'          => $id,
					'name'        => $achievement['name'],
					'description' => $achievement['description'],
					'tier'        => $achievement['tier'],
					'tierName'    => $this->achievements->get_tier_info( $achievement['tier'] )['name'],
					'icon'        => $achievement['icon'],
				);
			}
		}

		return $achievements;
	}

	/**
	 * Render the dashboard page.
	 *
	 * @return void
	 */
	public function render_dashboard(): void {
		$data       = $this->get_dashboard_data();
		$user_level = $this->usage_stats->get_user_level();
		?>
		<div class="wrap agenticwp-dashboard-wrap">
			<header class="agenticwp-dashboard-header">
				<div class="agenticwp-header-content">
					<h1><?php esc_html_e( 'Dashboard', 'agenticwp' ); ?></h1>
					<p class="agenticwp-current-date"><span class="dashicons dashicons-calendar"></span> <?php echo esc_html( wp_date( 'l, F j, Y' ) ); ?></p>
				</div>
			</header>
			<?php $this->render_tip_jar_banner(); ?>
			<div class="agenticwp-dashboard-bento">
				<?php $this->render_overview_cards( $data['lifetime'], $data['streaks'] ); ?>
				<?php $this->render_level_card( $user_level, $data['lifetime']['total_tool_calls'] ); ?>
				<div class="agenticwp-bento-item agenticwp-span-8 agenticwp-span-mobile-12"><?php $this->render_activity_section(); ?></div>
				<div class="agenticwp-bento-item agenticwp-span-4 agenticwp-span-mobile-12"><?php $this->render_achievements_section(); ?></div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the level card (compact version in stat card row).
	 *
	 * @param array $user_level User level info.
	 * @param int   $total_calls Total tool calls.
	 * @return void
	 */
	private function render_level_card( array $user_level, int $total_calls ): void {
		$is_max   = $user_level['level'] >= 7;
		$progress = $is_max ? 100 : min( 100, (int) ( ( $total_calls - $user_level['min'] ) / ( $user_level['max'] - $user_level['min'] + 1 ) * 100 ) );
		?>
		<div class="agenticwp-level-card">
			<?php /* translators: %d: user level number */ ?>
			<span class="agenticwp-level-card-badge"><?php printf( esc_html__( 'Level %d', 'agenticwp' ), (int) $user_level['level'] ); ?></span>
			<span class="agenticwp-level-card-name"><?php echo esc_html( $user_level['name'] ); ?></span>
			<div class="agenticwp-level-card-progress">
				<div class="agenticwp-level-card-progress-bar" style="width: <?php echo esc_attr( $progress ); ?>%;"></div>
			</div>
			<span class="agenticwp-level-card-calls">
				<?php
				if ( $is_max ) {
					/* translators: %s: number of tasks completed */
					printf( esc_html__( '%s tasks completed', 'agenticwp' ), esc_html( number_format_i18n( $total_calls ) ) );
				} else {
					/* translators: %1$s: current number of tasks completed, %2$s: total tasks needed for next level */
					printf( esc_html__( '%1$s / %2$s tasks completed', 'agenticwp' ), esc_html( number_format_i18n( $total_calls ) ), esc_html( number_format_i18n( $user_level['max'] + 1 ) ) );
				}
				?>
			</span>
		</div>
		<?php
	}

	/**
	 * Render overview stat cards.
	 *
	 * @param array $lifetime Lifetime stats.
	 * @param array $streaks  Streak data.
	 * @return void
	 */
	private function render_overview_cards( array $lifetime, array $streaks ): void {
		$current_streak = $this->usage_stats->get_current_streak();
		$cards          = array(
			array( 'edit', __( 'Drafts Created', 'agenticwp' ), $lifetime['posts_created'] ),
			array( 'admin-page', __( 'Edits Automated', 'agenticwp' ), $lifetime['posts_edited'] ),
			array( 'calendar-alt', __( 'Current Streak', 'agenticwp' ), $current_streak, _n( 'day', 'days', $current_streak, 'agenticwp' ), $current_streak > 0, $streaks['longest_streak'] ),
			array( 'search', __( 'Meta Descriptions', 'agenticwp' ), $lifetime['meta_descriptions'] ),
		);

		foreach ( $cards as $card ) {
			$has_streak  = ! empty( $card[4] );
			$best_streak = $card[5] ?? 0;
			?>
			<div class="agenticwp-stat-card<?php echo $has_streak ? ' agenticwp-stat-card--streak' : ''; ?>">
				<?php if ( $has_streak ) : ?>
					<span class="agenticwp-flame-particle"></span><span class="agenticwp-flame-particle"></span><span class="agenticwp-flame-particle"></span>
				<?php endif; ?>
				<div class="agenticwp-stat-card-icon"><span class="dashicons dashicons-<?php echo esc_attr( $card[0] ); ?>"></span></div>
				<div class="agenticwp-stat-card-content">
					<span class="agenticwp-stat-card-value"><?php echo esc_html( number_format_i18n( $card[2] ) ); ?>
					<?php
					if ( ! empty( $card[3] ) ) :
						?>
						<span class="agenticwp-stat-card-suffix"><?php echo esc_html( $card[3] ); ?></span><?php endif; ?></span>
					<span class="agenticwp-stat-card-label"><?php echo esc_html( $card[1] ); ?></span>
					<?php if ( $best_streak ) : ?>
						<?php /* translators: %d: best streak in days */ ?>
						<span class="agenticwp-stat-card-best"><?php printf( esc_html__( 'Best: %d days', 'agenticwp' ), (int) $best_streak ); ?></span>
					<?php endif; ?>
				</div>
			</div>
			<?php
		}
	}

	/**
	 * Render the tip jar banner.
	 *
	 * @return void
	 */
	private function render_tip_jar_banner(): void {
		?>
		<div class="agenticwp-tip-jar" data-tip-jar>
			<div class="agenticwp-tip-jar-icon"><span class="dashicons dashicons-heart"></span></div>
			<div class="agenticwp-tip-jar-content">
				<span class="agenticwp-tip-jar-title"><?php esc_html_e( 'Enjoying Agentic WP?', 'agenticwp' ); ?></span>
				<span class="agenticwp-tip-jar-message"><?php esc_html_e( 'Your support helps fund new features and improvements.', 'agenticwp' ); ?></span>
			</div>
			<div class="agenticwp-tip-jar-action">
				<form action="https://www.paypal.com/donate/?hosted_button_id=<?php echo esc_attr( self::PAYPAL_HOSTED_BUTTON_ID ); ?>" method="post" target="_blank">
					<input type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif" name="submit" title="<?php esc_attr_e( 'Donate with PayPal', 'agenticwp' ); ?>" alt="<?php esc_attr_e( 'Donate with PayPal button', 'agenticwp' ); ?>">
				</form>
			</div>
			<button type="button" class="agenticwp-tip-jar-dismiss" aria-label="<?php esc_attr_e( 'Dismiss tip jar', 'agenticwp' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
		</div>
		<?php
	}

	/**
	 * Render the activity section with charts.
	 *
	 * @return void
	 */
	private function render_activity_section(): void {
		?>
		<div class="agenticwp-activity-section">
			<div class="agenticwp-section-header">
				<h2><?php esc_html_e( 'Recent Activity', 'agenticwp' ); ?></h2>
				<div class="agenticwp-chart-toggle">
					<button type="button" class="active" data-period="7d"><?php esc_html_e( '7 Days', 'agenticwp' ); ?></button>
					<button type="button" data-period="30d"><?php esc_html_e( '30 Days', 'agenticwp' ); ?></button>
					<button type="button" data-period="12w"><?php esc_html_e( '12 Weeks', 'agenticwp' ); ?></button>
				</div>
			</div>
			<div class="agenticwp-chart-container"><canvas id="agenticwp-daily-chart" height="280"></canvas></div>
			<div class="agenticwp-chart-container" style="display: none;"><canvas id="agenticwp-weekly-chart" height="280"></canvas></div>
			<div class="agenticwp-chart-container agenticwp-distribution-container">
				<h3><?php esc_html_e( 'Activity Distribution', 'agenticwp' ); ?></h3>
				<canvas id="agenticwp-distribution-chart" height="200"></canvas>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the achievements section.
	 *
	 * @return void
	 */
	private function render_achievements_section(): void {
		$summary     = $this->achievements->get_achievement_summary();
		$next_badges = $this->achievements->get_next_achievements( 3 );
		$recent      = $this->achievements->get_recent_achievements( 5 );
		?>
		<div class="agenticwp-achievements-section">
			<h2><?php esc_html_e( 'Achievements', 'agenticwp' ); ?></h2>
			<div class="agenticwp-achievements-summary">
				<div class="agenticwp-achievement-count">
					<span class="agenticwp-achievement-count-value"><?php echo esc_html( $summary['unlocked'] ); ?></span>
					<span class="agenticwp-achievement-count-total">/<?php echo esc_html( $summary['total'] ); ?></span>
				</div>
				<span class="agenticwp-achievement-count-label"><?php esc_html_e( 'Achievements Unlocked', 'agenticwp' ); ?></span>
			</div>
			<?php if ( $next_badges ) : ?>
				<div class="agenticwp-next-achievements">
					<h3><?php esc_html_e( 'Up Next', 'agenticwp' ); ?></h3>
					<?php foreach ( $next_badges as $id => $a ) : ?>
						<?php $tier = $this->achievements->get_tier_info( $a['tier'] ); ?>
						<div class="agenticwp-achievement-progress-card" data-achievement="<?php echo esc_attr( $id ); ?>" data-progress="<?php echo esc_attr( $a['percentage'] ); ?>">
							<div class="agenticwp-achievement-progress-icon-wrapper"><?php echo $this->achievements->get_tier_badge_svg( $a['tier'], 44 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?><span class="agenticwp-achievement-progress-emoji"><?php echo esc_html( $a['icon'] ); ?></span></div>
							<div class="agenticwp-achievement-progress-info">
								<span class="agenticwp-achievement-progress-name"><?php echo esc_html( $a['name'] ); ?></span>
								<span class="agenticwp-achievement-progress-desc"><?php echo esc_html( $a['description'] ); ?></span>
								<div class="agenticwp-achievement-progress-bar-wrapper">
									<div class="agenticwp-achievement-progress-bar"><div class="agenticwp-achievement-progress-bar-fill" style="--progress-width: <?php echo esc_attr( $a['percentage'] ); ?>%; background-color: <?php echo esc_attr( $tier['color'] ); ?>;"></div></div>
									<?php /* translators: 1: current progress, 2: target */ ?>
									<span class="agenticwp-achievement-progress-text"><?php printf( esc_html__( '%1$s / %2$s', 'agenticwp' ), esc_html( number_format_i18n( $a['current'] ) ), esc_html( number_format_i18n( $a['target'] ) ) ); ?></span>
								</div>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
			<?php if ( $recent ) : ?>
				<div class="agenticwp-recent-achievements">
					<h3><?php esc_html_e( 'Recently Unlocked', 'agenticwp' ); ?></h3>
					<?php foreach ( $recent as $id => $a ) : ?>
						<div class="agenticwp-achievement-badge" data-achievement="<?php echo esc_attr( $id ); ?>">
							<div class="agenticwp-achievement-badge-icon-wrapper"><?php echo $this->achievements->get_tier_badge_svg( $a['tier'], 40 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?><span class="agenticwp-achievement-badge-emoji"><?php echo esc_html( $a['icon'] ); ?></span></div>
							<div class="agenticwp-achievement-badge-info">
								<span class="agenticwp-achievement-badge-name"><?php echo esc_html( $a['name'] ); ?></span>
								<span class="agenticwp-achievement-badge-tier"><?php echo esc_html( $this->achievements->get_tier_info( $a['tier'] )['name'] ); ?></span>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles AJAX request for chart data.
	 *
	 * @return void
	 */
	public function handle_get_chart_data(): void {
		check_ajax_referer( 'agenticwp_chart_data', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'agenticwp' ) ) );
		}

		$period = isset( $_POST['period'] ) ? sanitize_text_field( wp_unslash( $_POST['period'] ) ) : '7d';
		wp_send_json_success(
			array(
				'daily'    => $this->get_daily_data_for_period( $period ),
				'weekly'   => $this->usage_stats->get_weekly_stats(),
				'lifetime' => $this->usage_stats->get_lifetime_stats(),
			)
		);
	}

	/**
	 * Gets daily data for a specific period.
	 *
	 * @param string $period Period identifier (7d, 30d).
	 * @return array Daily stats array.
	 */
	private function get_daily_data_for_period( string $period ): array {
		$days      = '30d' === $period ? 30 : 7;
		$all_daily = $this->usage_stats->get_daily_stats();
		$result    = array();
		$default   = array(
			'tool_calls'    => 0,
			'posts_created' => 0,
		);

		for ( $i = $days - 1; $i >= 0; $i-- ) {
			$date            = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
			$result[ $date ] = $all_daily[ $date ] ?? $default;
		}
		return $result;
	}
}
