<?php
/**
 * Plugin Name: Askany
 * Plugin URI: https://wordpress.org/plugins/askany
 * Description: Complete AI chatbot solution with live agent handoff, WooCommerce integration, PDF knowledge base, and multi-provider AI support (OpenAI, DeepSeek, Gemini, OpenRouter, X.AI). WooCommerce Integration with RAG + SSE Architecture.
 * Version: 1.12.0
 * Requires at least: 5.9
 * Requires PHP:      7.4
 * Author: wpazleen
 * Author URI: https://profiles.wordpress.org/wpazleen
 * Text Domain: askany
 * Domain Path:       /languages/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 *
 * @package Askany
 */

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

if ( ! function_exists( 'ask_fs' ) ) { // Freemium SDK function also prefixed.
	/**
	 * Freemius SDK.
	 *
	 * @since 1.0.0
	 * @return object Freemius SDK object.
	 */
	function ask_fs() {
		global $ask_fs;

		if ( ! isset( $ask_fs ) ) {
			// Include Freemius SDK.
			require_once __DIR__ . '/vendor/freemius/start.php';

			$ask_fs = fs_dynamic_init( array(
				'id'                  => '19140',
				'slug'                => 'askany',
				'type'                => 'plugin',
				'public_key'          => 'pk_b10a2efc2cbbc0d7d714b234b31ee',
				'is_premium'          => false,
				'has_premium_version' => true,
				'has_addons'          => false,
				'has_paid_plans'      => true,
				'is_org_compliant'    => true,
				'menu'                => array(
					'slug'           => 'askany-settings',
					'first-path'     => 'admin.php?page=askany-settings',
					'contact'    => false,
					'support'        => false,
					'account'        => false,
				),

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

			) );
		}

		return $ask_fs;
	}

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

/**
 * 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 askany_get_freemius_instance() {
	// If Pro is active, get Freemius instance from Pro
	if ( is_plugin_active( 'askany-pro/askany-pro.php' ) ) {
		// Pro handles Freemius, so get it from Pro's function
		if ( function_exists( 'askany_pro_get_freemius_instance' ) ) {
			return askany_pro_get_freemius_instance();
		}
		// Fallback: try to get Pro's Freemius instance directly
		return function_exists( 'ask_pro_fs' ) ? ask_pro_fs() : null;
	}
	
	// Otherwise, Free handles it
	return function_exists( 'ask_fs' ) ? ask_fs() : null;
}

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

	// Check if Pro plugin is active
	if ( ! is_plugin_active( 'askany-pro/askany-pro.php' ) ) {
		return;
	}

	// Get Pro version from constant
	$pro_version = defined( 'ASKANYPRO_VERSION' ) ? ASKANYPRO_VERSION : '0.0.0';
	if ( ! $pro_version || $pro_version === '0.0.0' ) {
		return;
	}

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

	// Check if Pro version is below 1.1.0 (incompatible)
	if ( version_compare( $pro_version, ASKANY_MIN_PRO_VERSION, '<' ) ) {
		// Deactivate the Pro plugin
		deactivate_plugins( 'askany-pro/askany-pro.php' );
		
		// Set flag to show upgrade notice
		update_option( 'askany_pro_upgrade_required', true );
		update_option( 'askany_pro_old_version', $pro_version );
		
		// Add admin notice
		add_action( 'admin_notices', function() use ( $pro_version ) {
			echo '<div class="notice notice-error"><p>';
			printf( 
				__( '<strong>Askany Pro v%s has been deactivated!</strong> It\'s incompatible with Askany Free v%s. Please upgrade to Pro v%s or higher.', 'askany' ),
				esc_html( $pro_version ),
				esc_html( ASKANY_VERSION ),
				esc_html( ASKANY_MIN_PRO_VERSION )
			);
			echo '</p></div>';
		});
	}
}
add_action( 'admin_init', 'askany_check_pro_version_compatibility' );

/**
 * Clear Pro upgrade flags when compatible version is detected.
 * 
 * @since 1.7.0
 */
function askany_clear_pro_upgrade_flags() {
	// Clear upgrade flags if they exist
	if ( get_option( 'askany_pro_upgrade_required' ) ) {
		delete_option( 'askany_pro_upgrade_required' );
	}
	
	if ( get_option( 'askany_pro_upgrade_notice_dismissed' ) ) {
		delete_option( 'askany_pro_upgrade_notice_dismissed' );
	}
	
	if ( get_option( 'askany_pro_old_version' ) ) {
		delete_option( 'askany_pro_old_version' );
	}
}

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

	$old_version = get_option( 'askany_pro_old_version', '1.0.0' );
	
	?>
	<div id="askany-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 _e( 'Askany Pro Upgrade Required!', 'askany' ); ?>
				</h3>
				<p style="margin: 0 0 15px 0; font-size: 14px;">
					<?php 
					printf( 
						__( 'Your Askany Pro v%s is incompatible with the new Askany Free v%s. The Pro version has been automatically deactivated to prevent conflicts.', 'askany' ),
						'<strong>' . esc_html( $old_version ) . '</strong>',
						'<strong>' . esc_html( ASKANY_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 _e( '🔄 Download Pro v' . ASKANY_MIN_PRO_VERSION . '+', 'askany' ); ?>
					</a>
					<span style="color: #666; font-size: 12px;">
						<?php _e( 'Login to your Freemius account to get the latest version', 'askany' ); ?>
					</span>
				</div>
			</div>
			<button type="button" class="notice-dismiss" onclick="askanyDismissProUpgradeNotice()">
				<span class="screen-reader-text"><?php _e( 'Dismiss this notice.', 'askany' ); ?></span>
			</button>
		</div>
	</div>

	<script type="text/javascript">
	function askanyDismissProUpgradeNotice() {
		jQuery.post(ajaxurl, {
			action: 'askany_dismiss_pro_upgrade_notice',
			nonce: '<?php echo wp_create_nonce( 'askany_dismiss_notice' ); ?>'
		}, function(response) {
			if (response.success) {
				jQuery('#askany-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('#askany-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('#askany-pro-upgrade-notice').fadeOut();
		});
	}
	</script>

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

/**
 * Dismiss Pro upgrade notice via AJAX.
 * 
 * @since 1.7.0
 */
function askany_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, 'askany_dismiss_notice' ) ) {
		wp_send_json_error( array( 'message' => 'Security check failed' ) );
		return;
	}

	// Mark notice as dismissed
	update_option( 'askany_pro_upgrade_notice_dismissed', true );
	
	wp_send_json_success( array( 'message' => 'Notice dismissed successfully' ) );
}
add_action( 'wp_ajax_askany_dismiss_pro_upgrade_notice', 'askany_dismiss_pro_upgrade_notice' );

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

	// Check if Free version is 1.7.0+ and Pro version is below 1.1.0
	$free_version = ASKANY_VERSION;
	if ( version_compare( $free_version, '1.7.0', '>=' ) && version_compare( $pro_version, ASKANY_MIN_PRO_VERSION, '<' ) ) {
		// Deactivate the Pro plugin immediately
		deactivate_plugins( 'askany-pro/askany-pro.php' );
		
		// Set upgrade flags
		update_option( 'askany_pro_upgrade_required', true );
		update_option( 'askany_pro_old_version', $pro_version );
		
		// Show error message with wp_die
		wp_die(
			sprintf(
				__( '<h1>Activation Failed!</h1><p><strong>Askany Pro v%s</strong> is incompatible with <strong>Askany 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>', 'askany' ),
				esc_html( $pro_version ),
				esc_html( $free_version ),
				esc_html( ASKANY_MIN_PRO_VERSION ),
				esc_url( admin_url( 'plugins.php' ) )
			),
			__( 'Plugin Activation Error', 'askany' ),
			array( 'back_link' => true )
		);
	} else if ( version_compare( $free_version, '1.7.0', '>=' ) && version_compare( $pro_version, ASKANY_MIN_PRO_VERSION, '>=' ) ) {
		// Compatible Pro version activated - clear any existing upgrade flags
		askany_clear_pro_upgrade_flags();
	}
}
add_action( 'activate_askany-pro/askany-pro.php', 'askany_prevent_old_pro_activation' );

// Define plugin constants.
define('ASKANY_VERSION', '1.12.0');
define('ASKANY_MIN_PRO_VERSION', '1.1.0');
define('ASKANY_PLUGIN_FILE', __FILE__);
define('ASKANY_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ASKANY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('ASKANY_PLUGIN_BASENAME', plugin_basename(__FILE__));

if ( file_exists(__DIR__ . '/vendor/autoload.php') ) {
	require_once __DIR__ . '/vendor/autoload.php';
}
/**
 * Loads a required file from the includes directory.
 *
 * @param string $file The file to load.
 * @return void
 */
function askany_load_file( $file ) {
	$file_path = ASKANY_PLUGIN_DIR . 'includes/' . $file;
	if ( file_exists( $file_path ) ) {
		require_once $file_path;
	} else {
		// translators: %s: The name of the file that couldn't be found
		$message = sprintf(
			__( 'Error: Required file %s not found. Please reinstall the plugin.', 'askany' ),
			esc_html( $file )
		);
		wp_die( wp_kses_post( $message ) );
	}
}


/**
 * Load required plugin files.
 *
 * @throws Exception If any files fail to load properly.
 * @return void
 */
try {
	// Provider classes.
	askany_load_file('providers/interface-ai-provider.php');
	askany_load_file('providers/class-abstract-provider.php');
	askany_load_file('providers/class-openai-provider.php');
	askany_load_file('providers/class-deepseek-provider.php');
	askany_load_file('providers/class-gemini-provider.php');
	askany_load_file('providers/class-claude-provider.php');
	askany_load_file('providers/class-grok-provider.php');
	askany_load_file('providers/class-openrouter-provider.php');
	askany_load_file('providers/class-provider-factory.php');

	// Core classes.
	askany_load_file('class-database.php');
	askany_load_file('class-database-manager.php');
	askany_load_file('class-session-manager.php');
	askany_load_file('class-api-manager.php');
	askany_load_file('class-encryption-handler.php');
	askany_load_file('class-rate-limiter.php');

	// RAG (Retrieval-Augmented Generation) classes.
	askany_load_file('class-embedding-manager.php');
	askany_load_file('class-vector-search.php');
	askany_load_file('class-chunker.php');

	// Content handling classes.
	askany_load_file('class-content-indexer.php');
	askany_load_file('class-pdf-handler.php');
	askany_load_file('class-pdf-upload-handler.php');
	askany_load_file('class-external-sources-handler.php');

	// UI and interaction classes.
	askany_load_file('class-assets-manager.php');
	askany_load_file('class-shortcode-handler.php');
	askany_load_file('class-ajax-handler.php');
	askany_load_file('class-sse-handler.php');
	askany_load_file('class-admin-pages.php');
	askany_load_file('class-slack-notifier.php');
	askany_load_file('class-woocommerce-handler.php');
	askany_load_file('class-news-handler.php');

	// Main plugin class (load last as it depends on all others).
	askany_load_file('class-plugin.php');

} catch ( Exception $e ) {
	// translators: %s: The error message from the exception
	$error_message = sprintf(
		__( 'Error loading Askany plugin: %s', 'askany' ),
		esc_html( $e->getMessage() )
	);
	wp_die( wp_kses_post( $error_message ) );
}



/**
 * Initialize the plugin.
 *
 * @return void
 */
function askany_init() {
	try {
		// Check if class exists.
		if ( ! class_exists('Askany\\Plugin') ) {
			throw new Exception('Plugin class not found');
		}

		// Get plugin instance using the singleton pattern.
		$plugin = \Askany\Plugin::get_instance();

		// Check if instance was created successfully.
		if ( ! $plugin instanceof \Askany\Plugin ) {
			throw new Exception('Failed to initialize plugin');
		}

		// Initialize the plugin.
		$plugin->init();
	} catch ( Exception $e ) {

		// Add admin notice for administrators.
		if ( is_admin() && current_user_can( 'manage_options' ) ) {
			add_action( 'admin_notices', function () use ( $e ) {
				// translators: %s: The error message from the exception
				$error_message = sprintf(
					__( 'Askany Plugin Error: %s', 'askany' ),
					esc_html( $e->getMessage() )
				);
				printf(
					'<div class="notice notice-error"><p>%s</p></div>',
					esc_html( $error_message )
				);
			});
		}
	}
}

// Hook into WordPress.
add_action('plugins_loaded', 'askany_init');
