<?php
/**
 * Plugin Name: Product Display
 * Plugin URI: https://wordpress.org/plugins/product-display
 * Description: Advanced product display with multiple layouts including Grid, Table with customization options.
 * Version: 2.5.0
 * Requires at least: 5.9
 * Requires PHP: 7.2
 * Author: wpazleen
 * Author URI: https://profiles.wordpress.org/wpazleen
 * Text Domain: product-display
 * Domain Path: /languages/
 * License: GPL v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

// Exit if accessed directly.
if ( ! defined('ABSPATH') ) {
	exit;
}

// Define plugin constants.
define('PRODDISP_VERSION', '2.5.0');
define('PRODDISP_MIN_PRO_VERSION', '1.2.2'); // Minimum required PRO version for compatibility
define('PRODDISP_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('PRODDISP_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('PRODDISP_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PRODDISP_PLUGIN_BASENAME', plugin_basename(__FILE__));
define('PRODDISP_PLUGIN_FILE', __FILE__);

// Composer autoload
if ( file_exists(__DIR__ . '/vendor/autoload.php') ) {
	require_once __DIR__ . '/vendor/autoload.php';
}


if ( ! function_exists( 'pd_fs' ) ) {
	// Create a helper function for easy SDK access.
	function pd_fs() {
		global $pd_fs;

		if ( ! isset( $pd_fs ) ) {
			// Include Freemius SDK.
			require_once __DIR__ . '/vendor/freemius/start.php';
			$pd_fs = fs_dynamic_init( array(
				'id'                  => '19582',
				'slug'                => 'product-display',
				'type'                => 'plugin',
				'public_key'          => 'pk_5e7406cb0a5b592c68a76ad7b706c',
				'is_premium'          => false,
				'has_premium_version' => true,
				'has_addons'          => false,
				'has_paid_plans'      => true,
				'is_org_compliant'    => true,
				'menu'                => array(
					'slug'           => 'product-display',
					'first-path'     => 'admin.php?page=product-display',
					'contact'    => false,
					'support'        => false,
					'account'        => false,
				),

				'parallel_activation' => array(
                    'enabled'                  => true,
                    'premium_version_basename' => 'product-display-pro/product-display-pro.php',
                ),

			) );
		}

		return $pd_fs;
	}

	// Init Freemius only if Pro plugin is not active.
	if ( ! is_plugin_active( 'product-display-pro/product-display-pro.php' ) ) {
		pd_fs();
		// Signal that SDK was initiated.
		do_action( 'pd_fs_loaded' );
	}
}


/**
 * Get Freemius instance
 *
 * @return object|null Freemius instance or null
 */
function get_freemius_instance() {
	return product_display_get_freemius_instance();
}

/**
 * Helper function to check if Freemius is available (either from Free or Pro).
 *
 * @since 1.7.0
 * @return object|null Freemius SDK object or null.
 */
function product_display_get_freemius_instance() {
	// If Pro is active, get Freemius instance from Pro
	if ( is_plugin_active( 'product-display-pro/product-display-pro.php' ) ) {
		// Pro handles Freemius, so get it from Pro's function
		if ( function_exists( 'product_display_pro_get_freemius_instance' ) ) {
			return product_display_pro_get_freemius_instance();
		}
		// Fallback: try to get Pro's Freemius instance directly
		return function_exists( 'pd_pro_fs' ) ? pd_pro_fs() : null;
	}
	
	// Otherwise, Free handles it
	return function_exists( 'pd_fs' ) ? pd_fs() : null;
}

//

/**
 * Check Pro version compatibility and deactivate if incompatible.
 * 
 * @since 1.7.0
 */
function product_display_check_pro_version_compatibility() {
	// Only run this check if Free version is 2.2.1 or higher
	$free_version = PRODDISP_VERSION;
	if ( version_compare( $free_version, '2.2.1', '<' ) ) {
		return;
	}

	// Check if Pro plugin is active
	if ( ! is_plugin_active( 'product-display-pro/product-display-pro.php' ) ) {
		// Pro is not active, clear any existing flags
		product_display_clear_pro_upgrade_flags();
		return;
	}

	// Get Pro version from constant
	$pro_version = defined( 'PRODDISP_PRO_VERSION' ) ? PRODDISP_PRO_VERSION : '0.0.0';
	if ( ! $pro_version || $pro_version === '0.0.0' ) {
		// Pro constant not yet defined, skip check for now
		return;
	}

	// Check if Pro version is compatible (1.2.2 or higher)
	if ( version_compare( $pro_version, PRODDISP_MIN_PRO_VERSION, '>=' ) ) {
		// Pro version is compatible - clear any existing upgrade flags
		product_display_clear_pro_upgrade_flags();
		return;
	}

	// Check if Pro version is below 1.2.2 (incompatible)
	if ( version_compare( $pro_version, PRODDISP_MIN_PRO_VERSION, '<' ) ) {
		// Deactivate the Pro plugin
		deactivate_plugins( 'product-display-pro/product-display-pro.php' );
		
		// Set flag to show upgrade notice
		update_option( 'product_display_pro_upgrade_required', true );
		update_option( 'product_display_pro_old_version', $pro_version );
		
		// Add admin notice
		add_action( 'admin_notices', function() use ( $pro_version ) {
			echo '<div class="notice notice-error"><p>';
			echo wp_kses_post( sprintf(
				__( '<strong>Product Display Pro v%s has been deactivated!</strong> It\'s incompatible with Product Display Free v%s. Please upgrade to Pro v%s or higher.', 'product-display' ),
				esc_html( $pro_version ),
				esc_html( PRODDISP_VERSION ),
				esc_html( PRODDISP_MIN_PRO_VERSION )
			) );
			echo '</p></div>';
		});
	}
}
add_action( 'admin_init', 'product_display_check_pro_version_compatibility' );

/**
 * Clear Pro upgrade flags when compatible version is detected.
 * 
 * @since 1.7.0
 */
function product_display_clear_pro_upgrade_flags() {
	// Clear upgrade flags if they exist
	if ( get_option( 'product_display_pro_upgrade_required' ) ) {
		delete_option( 'product_display_pro_upgrade_required' );
	}
	
	if ( get_option( 'product_display_pro_upgrade_notice_dismissed' ) ) {
		delete_option( 'product_display_pro_upgrade_notice_dismissed' );
	}
	
	if ( get_option( 'product_display_pro_old_version' ) ) {
		delete_option( 'product_display_pro_old_version' );
	}
}

/**
 * Show Pro upgrade notice.
 * 
 * @since 1.7.0
 */
function product_display_show_pro_upgrade_notice() {
	// Only show if upgrade is required and notice hasn't been dismissed
	if ( ! get_option( 'product_display_pro_upgrade_required' ) || get_option( 'product_display_pro_upgrade_notice_dismissed' ) ) {
		return;
	}

	$old_version = get_option( 'product_display_pro_old_version', '1.0.0' );
	
	?>
	<div id="product-display-pro-upgrade-notice" class="notice notice-warning is-dismissible" style="position: relative; padding: 20px; border-left: 4px solid #ffba00;">
		<div style="display: flex; align-items: center; gap: 15px;">
			<div style="font-size: 24px;">🚀</div>
			<div style="flex: 1;">
				<h3 style="margin: 0 0 10px 0; color: #d63638;">
					<?php esc_html_e( 'Product Display Pro Upgrade Required!', 'product-display' ); ?>
				</h3>
				<p style="margin: 0 0 15px 0; font-size: 14px;">
					<?php 
					echo wp_kses_post( sprintf(
						__( 'Your Product Display Pro v%s is incompatible with the new Product Display Free v%s. The Pro version has been automatically deactivated to prevent conflicts.', 'product-display' ),
						'<strong>' . esc_html( $old_version ) . '</strong>',
						'<strong>' . esc_html( PRODDISP_VERSION ) . '</strong>'
					) );
					?>
				</p>
				<div style="display: flex; gap: 10px; align-items: center;">
					<a href="https://customers.freemius.com/" target="_blank" class="button button-primary" style="background: #d63638; border-color: #d63638;">
						<?php echo esc_html( sprintf( __( '🔄 Download Pro v%s+', 'product-display' ), PRODDISP_MIN_PRO_VERSION ) ); ?>
					</a>
					<span style="color: #666; font-size: 12px;">
						<?php esc_html_e( 'Login to your Freemius account to get the latest version', 'product-display' ); ?>
					</span>
				</div>
			</div>
			<button type="button" class="notice-dismiss" onclick="productDisplayDismissProUpgradeNotice()">
				<span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'product-display' ); ?></span>
			</button>
		</div>
	</div>

	<script type="text/javascript">
	function productDisplayDismissProUpgradeNotice() {
		jQuery.post(ajaxurl, {
			action: 'product_display_dismiss_pro_upgrade_notice',
			nonce: <?php echo wp_json_encode( wp_create_nonce( 'product_display_dismiss_notice' ) ); ?>
		}, function(response) {
			if (response.success) {
				jQuery('#product-display-pro-upgrade-notice').fadeOut();
			} else {
				console.error('Failed to dismiss notice:', response.data ? response.data.message : 'Unknown error');
				// Still hide the notice on client side to prevent user frustration
				jQuery('#product-display-pro-upgrade-notice').fadeOut();
			}
		}).fail(function(xhr, status, error) {
			console.error('AJAX request failed:', error);
			// Still hide the notice on client side to prevent user frustration
			jQuery('#product-display-pro-upgrade-notice').fadeOut();
		});
	}
	</script>

	<style>
	#product-display-pro-upgrade-notice .notice-dismiss {
		position: absolute;
		top: 10px;
		right: 10px;
	}
	</style>
	<?php
}
add_action( 'admin_notices', 'product_display_show_pro_upgrade_notice' );

/**
 * Dismiss Pro upgrade notice via AJAX.
 * 
 * @since 1.7.0
 */
function product_display_dismiss_pro_upgrade_notice() {
	// Check if user has proper capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( 'Insufficient permissions' );
	}

	// Verify nonce with proper sanitization
	$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
	
	if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'product_display_dismiss_notice' ) ) {
		wp_send_json_error( array( 'message' => 'Security check failed' ) );
		return;
	}

	// Mark notice as dismissed
	update_option( 'product_display_pro_upgrade_notice_dismissed', true );
	
	wp_send_json_success( array( 'message' => 'Notice dismissed successfully' ) );
}
add_action( 'wp_ajax_product_display_dismiss_pro_upgrade_notice', 'product_display_dismiss_pro_upgrade_notice' );

/**
 * Prevent activation of old Pro versions.
 * 
 * @since 1.7.0
 */
function product_display_prevent_old_pro_activation() {
	// Get Pro version being activated
	$pro_version = defined( 'PRODDISP_PRO_VERSION' ) ? PRODDISP_PRO_VERSION : '0.0.0';
	
	if ( ! $pro_version || $pro_version === '0.0.0' ) {
		return;
	}

	// Check if Free version is 2.2.1+ and Pro version is below 1.2.2
	$free_version = PRODDISP_VERSION;
	if ( version_compare( $free_version, '2.2.1', '>=' ) && version_compare( $pro_version, PRODDISP_MIN_PRO_VERSION, '<' ) ) {
		// Deactivate the Pro plugin immediately
		deactivate_plugins( 'product-display-pro/product-display-pro.php' );
		
		// Set upgrade flags
		update_option( 'product_display_pro_upgrade_required', true );
		update_option( 'product_display_pro_old_version', $pro_version );
		
		// Show error message with wp_die
		wp_die(
			wp_kses_post( sprintf(
				__( '<h1>Activation Failed!</h1><p><strong>Product Display Pro v%s</strong> is incompatible with <strong>Product Display Free v%s</strong>.</p><p>Please upgrade to <strong>Pro v%s or higher</strong> from your <a href="https://customers.freemius.com/" target="_blank">Freemius account</a>.</p><p><a href="%s" class="button">← Go Back</a></p>', 'product-display' ),
				esc_html( $pro_version ),
				esc_html( $free_version ),
				esc_html( PRODDISP_MIN_PRO_VERSION ),
				esc_url( admin_url( 'plugins.php' ) )
			) ),
			esc_html__( 'Plugin Activation Error', 'product-display' ),
			array( 'back_link' => true )
		);
	} else if ( version_compare( $free_version, '2.2.1', '>=' ) && version_compare( $pro_version, PRODDISP_MIN_PRO_VERSION, '>=' ) ) {
		// Compatible Pro version activated - clear any existing upgrade flags
		product_display_clear_pro_upgrade_flags();
	}
}
add_action( 'activate_product-display-pro/product-display-pro.php', 'product_display_prevent_old_pro_activation' );

/**
 * Clear upgrade flags when Pro plugin is properly loaded with compatible version.
 * This runs after all plugins are loaded to ensure Pro constants are available.
 * 
 * @since 1.7.0
 */
function product_display_clear_flags_on_plugins_loaded() {
	// Check if Pro is active and compatible
	if ( is_plugin_active( 'product-display-pro/product-display-pro.php' ) ) {
		$pro_version = defined( 'PRODDISP_PRO_VERSION' ) ? PRODDISP_PRO_VERSION : '0.0.0';
		
		// If Pro version is compatible, clear any lingering flags
		if ( $pro_version && version_compare( $pro_version, PRODDISP_MIN_PRO_VERSION, '>=' ) ) {
			product_display_clear_pro_upgrade_flags();
		}
	} else {
		// Pro is not active, clear flags
		product_display_clear_pro_upgrade_flags();
	}
}
add_action( 'plugins_loaded', 'product_display_clear_flags_on_plugins_loaded', 20 );

/**
 * Manual cleanup function - can be called via URL parameter for debugging.
 * Usage: Add ?proddisp_clear_flags=1 to any admin URL
 * 
 * @since 1.7.0
 */
function product_display_manual_clear_flags() {
	if ( isset( $_GET['proddisp_clear_flags'] ) && current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin-only debug utility, capability check is sufficient
		product_display_clear_pro_upgrade_flags();
		wp_die( 'Product Display: All upgrade flags have been cleared. <a href="' . esc_url( admin_url() ) . '">Go to Dashboard</a>' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static string with escaped URL.
	}
}
add_action( 'admin_init', 'product_display_manual_clear_flags', 1 );
//


if ( ! class_exists( 'PRODDISP_Free_Loader' ) ) {
	/**
	 * Main class for Product Display Free version.
	 *
	 * This class handles the initialization of the plugin, checks for WooCommerce,
	 * and sets up hooks for activation and loading.
	 */
	class PRODDISP_Free_Loader {
		/**
		 * The single instance of the class.
		 *
		 * @var PRODDISP_Free_Loader
		 */
		public function __construct() {
			// Register hooks
			add_action('before_woocommerce_init', array( $this, 'declare_hpos_compatibility' ));
			add_action('init', array( $this, 'init_loader' )); // Changed from plugins_loaded to init
			add_action('admin_init', array( $this, 'activation_redirect' ));
			register_activation_hook(__FILE__, array( 'PRODDISP_Free_Loader', 'activate' ));
		}

		/**
		 * Check if WooCommerce is active.
		 */
		public function check_woocommerce_active() {
			if ( ! class_exists('WooCommerce') ) {
				// Hook the notice to admin_notices but ensure it runs after init
				add_action('admin_notices', array( $this, 'woocommerce_missing_notice' ));
				return false;
			}
			return true;
		}

		/**
		 * Display admin notice if WooCommerce is not active.
		 */
		public function woocommerce_missing_notice() {
			?>
			<div class="error">
				<p><?php esc_html_e('Product Display requires WooCommerce to be installed and active.', 'product-display'); ?></p>
			</div>
			<?php
		}

		/**
		 * Declare HPOS compatibility.
		 */
		public function declare_hpos_compatibility() {
			if ( class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil') ) {
				\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
			}
		}

		/**
		 * Load plugin files and Initialize the plugin.
		 */
		public function init_loader() {
			if ( $this->check_woocommerce_active() ) {
				// Include required files.
				require_once PRODDISP_PLUGIN_DIR . 'inc/class-proddisp-loader.php';

				// Initialize the loader.
				PRODDISP_Loader::get_instance();
				do_action('proddisp_free_loaded');
			}
		}

		/**
		 * Redirect to settings page after activation.
		 */
		public function activation_redirect() {
			$redirect = absint(get_option('proddisp_activation_redirect', 0));

			if ( 1 === $redirect ) {
				// Delete the option.
				delete_option('proddisp_activation_redirect');

				// Get total showcase count
				$showcases = get_option('proddisp_saved_showcases', array());
				$total_showcases = count($showcases);

				if ( 0 === $total_showcases ) {
					// No showcases - redirect to get started page
					wp_safe_redirect(admin_url('admin.php?page=product-display&view=get-started'));
				} else {
					// Has showcases - redirect to main plugin page
					wp_safe_redirect(admin_url('admin.php?page=product-display'));
				}
				exit;
			}
		}

		/**
		 * Activation hook.
		 */
		public static function activate() {
			// Activation tasks.
			$instance = new self();
			if ( $instance->check_woocommerce_active() ) {
				update_option('proddisp_activation_redirect', 1);
				if ( ! get_option('proddisp_activated_at') ) {
					update_option('proddisp_activated_at', time());
				}
			}
		}
	}
}

// Initialize the plugin loader
new PRODDISP_Free_Loader();