<?php
/**
 * Downgrade admin notice
 *
 * Shown in the admin when a previously paying license has reverted to the
 * free plan. Premium-side detection writes a persistent flag to the
 * options table; this notice only reads that flag, so it works even
 * after premium controllers have been physically removed from the build.
 *
 * Options used:
 *  - slidemind_downgrade_notice_pending   (set to 1 by the premium watcher)
 *  - slidemind_downgrade_notice_dismissed (set to 1 here on dismiss)
 *
 * @package SlideMind\Admin
 * @since   0.5.0
 */

namespace SlideMind\Admin;

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

class DowngradeNotice {

	const PENDING_OPTION   = 'slidemind_downgrade_notice_pending';
	const DISMISSED_OPTION = 'slidemind_downgrade_notice_dismissed';
	const DISMISS_ACTION   = 'slidemind_dismiss_downgrade_notice';

	public function __construct() {
		add_action( 'admin_notices', [ $this, 'maybe_render' ] );
		add_action( 'admin_init', [ $this, 'maybe_handle_dismiss' ] );
	}

	/**
	 * Renders the notice on SlideMind admin pages when a downgrade is pending
	 * and the user has not dismissed it.
	 */
	public function maybe_render(): void {
		if ( ! current_user_can( 'manage_slidemind_settings' ) ) {
			return;
		}

		if ( ! $this->is_pending() ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		$screen_id = $screen && isset( $screen->id ) ? (string) $screen->id : '';
		if ( strpos( $screen_id, 'slidemind' ) === false ) {
			return;
		}

		$counts = $this->collect_counts();

		$pricing_url = \SlideMind\Core\FeatureGate::get_upgrade_url();
		$export_url  = admin_url( 'admin.php?page=slidemind-settings#data' );
		$dismiss_url = wp_nonce_url(
			add_query_arg( self::DISMISS_ACTION, '1' ),
			self::DISMISS_ACTION
		);
		?>
		<div class="notice notice-info">
			<p>
				<strong><?php esc_html_e( 'Your SlideMind license has changed.', 'slidemind' ); ?></strong>
				<?php esc_html_e( 'Your content stays intact in the database and will become editable again as soon as you reactivate a Pro license. In the meantime, you can export everything as JSON.', 'slidemind' ); ?>
			</p>
			<ul style="list-style: disc; margin-left: 20px;">
				<?php if ( $counts['courses'] > 0 || $counts['modules'] > 0 || $counts['slides'] > 0 || $counts['templates'] > 0 ) : ?>
					<li>
						<?php
						echo esc_html(
							sprintf(
								/* translators: 1: courses count, 2: modules count, 3: slides count, 4: templates count */
								__( '%1$d courses, %2$d modules, %3$d slides, %4$d custom templates', 'slidemind' ),
								(int) $counts['courses'],
								(int) $counts['modules'],
								(int) $counts['slides'],
								(int) $counts['templates']
							)
						);
						?>
					</li>
				<?php endif; ?>
				<?php if ( $counts['memory_variables'] > 0 ) : ?>
					<li>
						<?php
						echo esc_html(
							sprintf(
								/* translators: %d: memory variable count */
								_n(
									'%d learner memory variable preserved',
									'%d learner memory variables preserved',
									(int) $counts['memory_variables'],
									'slidemind'
								),
								(int) $counts['memory_variables']
							)
						);
						?>
					</li>
				<?php endif; ?>
			</ul>
			<p>
				<?php if ( ! empty( $pricing_url ) ) : ?>
					<a href="<?php echo esc_url( $pricing_url ); ?>" class="button button-primary">
						<?php esc_html_e( 'Reactivate Pro', 'slidemind' ); ?>
					</a>
				<?php endif; ?>
				<a href="<?php echo esc_url( $export_url ); ?>" class="button">
					<?php esc_html_e( 'Export my data', 'slidemind' ); ?>
				</a>
				<a href="<?php echo esc_url( $dismiss_url ); ?>" style="margin-left: 12px;">
					<?php esc_html_e( 'Dismiss', 'slidemind' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Handles the dismiss link click.
	 */
	public function maybe_handle_dismiss(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Dismissal endpoint uses its own nonce verified below.
		if ( ! isset( $_GET[ self::DISMISS_ACTION ] ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_slidemind_settings' ) ) {
			return;
		}

		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, self::DISMISS_ACTION ) ) {
			return;
		}

		update_option( self::DISMISSED_OPTION, 1, false );
		delete_option( self::PENDING_OPTION );

		$redirect = remove_query_arg( [ self::DISMISS_ACTION, '_wpnonce' ] );
		wp_safe_redirect( $redirect );
		exit;
	}

	private function is_pending(): bool {
		if ( ! get_option( self::PENDING_OPTION ) ) {
			return false;
		}
		if ( get_option( self::DISMISSED_OPTION ) ) {
			return false;
		}
		return true;
	}

	/**
	 * Collects live counters shown in the notice body.
	 *
	 * @return array<string, int>
	 */
	private function collect_counts(): array {
		$plugin = \SlideMind\Plugin::instance();
		$repo   = $plugin->get_config_repository();
		$tm     = $plugin->get_template_manager();

		$custom_templates = 0;
		foreach ( $tm->get_all() as $tpl ) {
			if ( empty( $tpl['is_default'] ) ) {
				$custom_templates++;
			}
		}

		global $wpdb;
		$table = $wpdb->prefix . 'slidemind_learner_memory';
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned table, count query.
		$memory = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) );
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		return [
			'courses'          => count( $repo->get_courses( 'any' ) ),
			'modules'          => count( $repo->get_all_modules( 'any' ) ),
			'slides'           => count( $repo->get_all_slides( 'any' ) ),
			'templates'        => $custom_templates,
			'memory_variables' => $memory,
		];
	}
}
