<?php
/**
 * Class VSERPB_UX_Enhancements
 *
 * Implements four user-experience improvements:
 *  1. Activation notice with live Google Rich Results Test link
 *  2. Schema preview metabox on the WooCommerce product edit page
 *  3. Schema status column in the WooCommerce Products list table
 *  4. Dashboard schema counter widget on the plugin settings page
 */

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

class VSERPB_UX_Enhancements {

	/**
	 * Transient key for the activation notice flag.
	 */
	const ACTIVATION_NOTICE_TRANSIENT = 'vserpb_activation_notice';

	/**
	 * Boot all hooks.
	 */
	public static function init() {
		// 1. Activation notice.
		register_activation_hook(
			VSERPB_PLUGIN_FILE,
			array( __CLASS__, 'set_activation_flag' )
		);
		add_action( 'admin_notices', array( __CLASS__, 'show_activation_notice' ) );
		add_action( 'wp_ajax_vserpb_dismiss_activation_notice', array( __CLASS__, 'dismiss_activation_notice' ) );

		// 2. Schema preview metabox (product edit screen).
		add_action( 'add_meta_boxes', array( __CLASS__, 'register_schema_preview_metabox' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_ux_assets' ) );

		// 3. Schema status column on the Products list table.
		add_filter( 'manage_product_posts_columns', array( __CLASS__, 'add_schema_column_header' ) );
		add_action( 'manage_product_posts_custom_column', array( __CLASS__, 'render_schema_column_cell' ), 10, 2 );

		// 4. Dashboard counter is rendered inline inside the settings page
		//    (hooked via action added from the settings class — see below).
		add_action( 'vserpb_after_settings_header', array( __CLASS__, 'render_dashboard_counter' ) );
		}

	// =========================================================================
	// 1. ACTIVATION NOTICE
	// =========================================================================

	/**
	 * Set a transient so the notice appears once after activation.
	 */
	public static function set_activation_flag() {
		set_transient( self::ACTIVATION_NOTICE_TRANSIENT, '1', DAY_IN_SECONDS );
	}

	
	/**
	 * Render the activation banner with a pre-filled Rich Results Test link.
	 */
	public static function show_activation_notice() {
		if ( ! get_transient( self::ACTIVATION_NOTICE_TRANSIENT ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$site_url       = rawurlencode( home_url() );
		$rich_test_url  = 'https://search.google.com/test/rich-results?url=' . $site_url;
		$schema_val_url = 'https://validator.schema.org/#url=' . $site_url;
		$dismiss_nonce  = wp_create_nonce( 'vserpb_dismiss_activation_notice' );
		?>
		<div class="notice vserpb-activation-notice is-dismissible" id="vserpb-activation-banner" style="border-left-color:#3858e9;padding:16px 20px;">
			<div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
				<span style="font-size:28px;">🚀</span>
				<div>
					<strong style="font-size:15px;">
						<?php esc_html_e( 'Voidek Auto Schema Generator is now active!', 'voidek-serp-schema-builder' ); ?>
					</strong>
					<p style="margin:6px 0 0;">
						<?php esc_html_e( 'Your schema markup is being generated. Verify it instantly:', 'voidek-serp-schema-builder' ); ?>
						&nbsp;
						<a href="<?php echo esc_url( $rich_test_url ); ?>" target="_blank" rel="noopener noreferrer"
						   style="font-weight:600;color:#3858e9;">
							🔍 <?php esc_html_e( 'Google Rich Results Test', 'voidek-serp-schema-builder' ); ?>
						</a>
						&nbsp;&nbsp;
						<a href="<?php echo esc_url( $schema_val_url ); ?>" target="_blank" rel="noopener noreferrer"
						   style="font-weight:600;color:#3858e9;">
							✅ <?php esc_html_e( 'Schema Markup Validator', 'voidek-serp-schema-builder' ); ?>
						</a>
					</p>
				</div>
				<button type="button" class="notice-dismiss vserpb-dismiss-btn"
				        data-nonce="<?php echo esc_attr( $dismiss_nonce ); ?>"
				        style="margin-left:auto;">
					<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'voidek-serp-schema-builder' ); ?></span>
				</button>
			</div>
		</div>
		<?php
	}

	/**
	 * AJAX handler — dismiss the activation notice permanently.
	 */
	public static function dismiss_activation_notice() {
		check_ajax_referer( 'vserpb_dismiss_activation_notice', 'nonce' );
		delete_transient( self::ACTIVATION_NOTICE_TRANSIENT );
		wp_send_json_success();
	}

	// =========================================================================
	// 2. SCHEMA PREVIEW METABOX
	// =========================================================================

	/**
	 * Register the metabox on the WooCommerce product edit screen.
	 * Always registers — content area explains if schema is disabled.
	 */
	public static function register_schema_preview_metabox() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}
		add_meta_box(
			'vserpb_schema_preview',
			'<span style="display:inline-flex;align-items:center;gap:8px;">'
				. '<span style="color:#3858e9;" class="dashicons dashicons-editor-code"></span>'
				. esc_html__( 'Schema Preview (JSON-LD)', 'voidek-serp-schema-builder' )
			. '</span>',
			array( __CLASS__, 'render_schema_preview_metabox' ),
			'product',
			'normal',
			'low'
		);
	}

	/**
	 * Render the collapsible schema preview metabox content.
	 * Wrapped in try/catch so any sub-class exception shows a clean error
	 * instead of a white screen.
	 *
	 * @param WP_Post $post Current post object.
	 */
	public static function render_schema_preview_metabox( $post ) {
		$product_id = (int) $post->ID;
		$settings   = get_option( 'vserpb_product_schema', array() );

		// If schema is disabled in settings, show a friendly notice.
		if ( empty( $settings['vserpb_enable_schema'] ) ) {
			?>
			<p class="vserpb-schema-empty" style="margin:10px 0;">
				⚠️ <?php
				printf(
					wp_kses(
						/* translators: %s settings page link */
						__( 'Product Schema is currently <strong>disabled</strong>. <a href="%s">Enable it in settings</a> to see the preview.', 'voidek-serp-schema-builder' ),
						array( 'strong' => array(), 'a' => array( 'href' => array() ) )
					),
					esc_url( admin_url( 'admin.php?page=voidek-serp-schema-builder' ) )
				);
				?>
			</p>
			<?php
			return;
		}

		// Safely generate schema — catch any exception from sub-classes.
		$schema = null;
		$error  = '';
		try {
			$schema = Vserpb_Product_Schema::vserpb_generate_schema( $product_id );
		} catch ( Throwable $e ) {
			$error = $e->getMessage();
		}

		$json          = ( $schema && is_array( $schema ) )
			? wp_json_encode( $schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE )
			: '';
		$product_url   = get_permalink( $product_id );
		$rich_test_url = 'https://search.google.com/test/rich-results?url=' . rawurlencode( $product_url );
		?>
		<div class="vserpb-schema-preview-wrap">
			<div class="vserpb-schema-preview-toolbar">
				<span class="vserpb-schema-preview-badge">
					<?php if ( $json ) : ?>
						<span style="color:#46b450;">&#10003; <?php esc_html_e( 'Schema Active', 'voidek-serp-schema-builder' ); ?></span>
					<?php else : ?>
						<span style="color:#dc3232;">&#10007; <?php esc_html_e( 'Schema Inactive', 'voidek-serp-schema-builder' ); ?></span>
					<?php endif; ?>
				</span>
				<?php if ( $json ) : ?>
					<a href="<?php echo esc_url( $rich_test_url ); ?>" target="_blank" rel="noopener noreferrer"
					   class="button button-small vserpb-test-link">
						🔍 <?php esc_html_e( 'Test in Google Rich Results', 'voidek-serp-schema-builder' ); ?>
					</a>
					<button type="button" class="button button-small vserpb-copy-schema" data-target="vserpb-json-output">
						📋 <?php esc_html_e( 'Copy JSON', 'voidek-serp-schema-builder' ); ?>
					</button>
				<?php endif; ?>
			</div>

			<?php if ( $error ) : ?>
				<div class="notice notice-error inline" style="margin:10px 0;">
					<p><strong><?php esc_html_e( 'Schema generation error:', 'voidek-serp-schema-builder' ); ?></strong> <?php echo esc_html( $error ); ?></p>
				</div>
			<?php elseif ( $json ) : ?>
				<details class="vserpb-schema-details" open>
					<summary class="vserpb-schema-summary">
						<?php esc_html_e( 'View JSON-LD Output', 'voidek-serp-schema-builder' ); ?>
						<span class="vserpb-toggle-icon">▲</span>
					</summary>
					<div class="vserpb-schema-code-wrap">
						<pre id="vserpb-json-output" class="vserpb-schema-code"><?php echo esc_html( $json ); ?></pre>
					</div>
				</details>
			<?php else : ?>
				<p class="vserpb-schema-empty">
					<?php esc_html_e( 'No schema output could be generated for this product. Make sure it is published and has required fields (name, price).', 'voidek-serp-schema-builder' ); ?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	// =========================================================================
	// 3. SCHEMA STATUS COLUMN IN PRODUCTS LIST
	// =========================================================================

	/**
	 * Add a "Schema" column header to the WooCommerce products list.
	 *
	 * @param  array $columns Existing columns.
	 * @return array Modified columns.
	 */
	public static function add_schema_column_header( $columns ) {
		// Insert after the 'name' column.
		$new = array();
		foreach ( $columns as $key => $label ) {
			$new[ $key ] = $label;
			if ( 'name' === $key ) {
				$new['vserpb_schema_status'] = '<span class="dashicons dashicons-editor-code" title="' . esc_attr__( 'Schema Status', 'voidek-serp-schema-builder' ) . '"></span> ' . esc_html__( 'Schema', 'voidek-serp-schema-builder' );
			}
		}
		return $new;
	}

	/**
	 * Render the schema status cell for each product row.
	 *
	 * @param string $column    Column slug.
	 * @param int    $post_id   Post / product ID.
	 */
	public static function render_schema_column_cell( $column, $post_id ) {
		if ( 'vserpb_schema_status' !== $column ) {
			return;
		}

		$settings    = get_option( 'vserpb_product_schema', array() );
		$schema_on   = ! empty( $settings['vserpb_enable_schema'] );

		if ( $schema_on ) {
			// A schema will be output for this product.
			$site_url  = rawurlencode( get_permalink( $post_id ) );
			$test_url  = 'https://search.google.com/test/rich-results?url=' . $site_url;
			echo '<a href="' . esc_url( $test_url ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr__( 'Schema active — click to test', 'voidek-serp-schema-builder' ) . '" class="vserpb-col-status vserpb-col-active">
					<span class="dashicons dashicons-yes-alt" style="color:#46b450;font-size:20px;"></span>
				  </a>';
		} else {
			echo '<span class="vserpb-col-status vserpb-col-inactive" title="' . esc_attr__( 'Schema inactive', 'voidek-serp-schema-builder' ) . '">
					<span class="dashicons dashicons-minus" style="color:#aaa;font-size:20px;"></span>
				  </span>';
		}
	}

	// =========================================================================
	// 4. DASHBOARD SCHEMA COUNTER
	// =========================================================================

	/**
	 * Render the schema coverage counter widget.
	 * Called via the `vserpb_after_settings_header` action hook.
	 */
	public static function render_dashboard_counter() {
		$settings      = get_option( 'vserpb_product_schema', array() );
		$product_on    = ! empty( $settings['vserpb_enable_schema'] );
		$article_on    = ! empty( $settings['asm_enable_schema'] );
		$review_on     = ! empty( $settings['rsm_enable_schema'] );

		// Count published products.
		$product_count = 0;
		if ( $product_on && class_exists( 'WooCommerce' ) ) {
			$product_count = (int) wp_count_posts( 'product' )->publish;
		}

		// Count published posts (articles).
		$article_count = 0;
		if ( $article_on ) {
			$article_count = (int) wp_count_posts( 'post' )->publish;
		}

		// Count reviews with schema.
		$review_count = 0;
		if ( $review_on && class_exists( 'WooCommerce' ) ) {
			$review_count = (int) get_comments( array(
				'post_type' => 'product',
				'status'    => 'approve',
				'count'     => true,
			) );
		}

		$total = $product_count + $article_count;
		?>
		<div class="vserpb-counter-widget">
			<h3 class="vserpb-counter-title">
				<span class="dashicons dashicons-chart-bar"></span>
				<?php esc_html_e( 'Schema Coverage', 'voidek-serp-schema-builder' ); ?>
			</h3>
			<div class="vserpb-counter-grid">
				<div class="vserpb-counter-card <?php echo $product_on ? 'vserpb-counter-active' : 'vserpb-counter-off'; ?>">
					<span class="vserpb-counter-number"><?php echo $product_on ? esc_html( $product_count ) : '—'; ?></span>
					<span class="vserpb-counter-label">
						<?php esc_html_e( 'Products', 'voidek-serp-schema-builder' ); ?>
					</span>
					<span class="vserpb-counter-status">
						<?php echo $product_on ? '✅ ' . esc_html__( 'Active', 'voidek-serp-schema-builder' ) : '⏸ ' . esc_html__( 'Inactive', 'voidek-serp-schema-builder' ); ?>
					</span>
				</div>

				<div class="vserpb-counter-card <?php echo $article_on ? 'vserpb-counter-active' : 'vserpb-counter-off'; ?>">
					<span class="vserpb-counter-number"><?php echo $article_on ? esc_html( $article_count ) : '—'; ?></span>
					<span class="vserpb-counter-label">
						<?php esc_html_e( 'Articles', 'voidek-serp-schema-builder' ); ?>
					</span>
					<span class="vserpb-counter-status">
						<?php echo $article_on ? '✅ ' . esc_html__( 'Active', 'voidek-serp-schema-builder' ) : '⏸ ' . esc_html__( 'Inactive', 'voidek-serp-schema-builder' ); ?>
					</span>
				</div>

				<div class="vserpb-counter-card <?php echo $review_on ? 'vserpb-counter-active' : 'vserpb-counter-off'; ?>">
					<span class="vserpb-counter-number"><?php echo $review_on ? esc_html( $review_count ) : '—'; ?></span>
					<span class="vserpb-counter-label">
						<?php esc_html_e( 'Reviews', 'voidek-serp-schema-builder' ); ?>
					</span>
					<span class="vserpb-counter-status">
						<?php echo $review_on ? '✅ ' . esc_html__( 'Active', 'voidek-serp-schema-builder' ) : '⏸ ' . esc_html__( 'Inactive', 'voidek-serp-schema-builder' ); ?>
					</span>
				</div>

				<div class="vserpb-counter-card vserpb-counter-total">
					<span class="vserpb-counter-number"><?php echo esc_html( $total ); ?></span>
					<span class="vserpb-counter-label">
						<?php esc_html_e( 'Total Pages with Schema', 'voidek-serp-schema-builder' ); ?>
					</span>
					<span class="vserpb-counter-status">
						<?php esc_html_e( 'Combined', 'voidek-serp-schema-builder' ); ?>
					</span>
				</div>
			</div>
		</div>
		<?php
	}

	// =========================================================================
	// ASSETS
	// =========================================================================

	/**
	 * Enqueue UX-specific CSS + JS on relevant admin screens.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public static function enqueue_ux_assets( $hook ) {
		// Load on product edit screens, products list, and plugin settings page.
		$load_on = array( 'post.php', 'post-new.php', 'edit.php', 'toplevel_page_voidek-serp-schema-builder' );

		if ( ! in_array( $hook, $load_on, true ) ) {
			return;
		}

		// On post.php / post-new.php only load for the 'product' post type.
		if ( in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
			$screen = get_current_screen();
			if ( ! $screen || 'product' !== $screen->post_type ) {
				return;
			}
		}

		wp_enqueue_style(
			'vserpb-ux-enhancements',
			VSERPB_PLUGIN_URL . 'assets/css/vserpb-ux-enhancements.css',
			array(),
			VSERPB_VERSION
		);

		wp_enqueue_script(
			'vserpb-ux-enhancements',
			VSERPB_PLUGIN_URL . 'assets/js/vserpb-ux-enhancements.js',
			array( 'jquery' ),
			VSERPB_VERSION,
			true
		);

		wp_localize_script(
			'vserpb-ux-enhancements',
			'vserpb_ux',
			array(
				'ajax_url'      => admin_url( 'admin-ajax.php' ),
				'dismiss_nonce' => wp_create_nonce( 'vserpb_dismiss_activation_notice' ),
				'copied'        => esc_html__( 'Copied!', 'voidek-serp-schema-builder' ),
				'copy'          => esc_html__( 'Copy JSON', 'voidek-serp-schema-builder' ),
			)
		);
	}
}

VSERPB_UX_Enhancements::init();
