<?php
/**
 * Plugin Name: WebEquipe PDF Search
 * Description: Indexes PDF files and integrates their content into WordPress search results
 * Version: 2.0.1
 * Author: WebEquipe
 * Plugin URI: https://webequipe.com/pdf-search/
 * Author URI: https://webequipe.com
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: webequipe-pdf-search
 * Domain Path: /languages
 * Requires at least: 6.2
 * Requires PHP: 7.4
 *
 * @package WebEquipe\PDFSearch
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Current plugin version.
 */
define( 'WEBEQUIPE_PDF_SEARCH_VERSION', '2.0.1' );

/**
 * Plugin directory path.
 */
define( 'WEBEQUIPE_PDF_SEARCH_DIR', plugin_dir_path( __FILE__ ) );

/**
 * Plugin directory URL.
 */
define( 'WEBEQUIPE_PDF_SEARCH_URL', plugin_dir_url( __FILE__ ) );

if ( ! function_exists( 'webequipe_pdf_search_fs' ) ) {
	/**
	 * Freemius SDK accessor.
	 *
	 * @return \Freemius
	 */
	function webequipe_pdf_search_fs() {
		global $webequipe_pdf_search_fs;

		if ( ! isset( $webequipe_pdf_search_fs ) ) {
			// Include Freemius SDK before init (Composer autoload runs later in run()).
			if ( ! function_exists( 'fs_dynamic_init' ) ) {
				require_once WEBEQUIPE_PDF_SEARCH_DIR . 'vendor/freemius/wordpress-sdk/start.php';
			}

			$webequipe_pdf_search_fs = fs_dynamic_init(
				array(
					'id'                  => '28551',
					'slug'                => 'webequipe-pdf-search',
					'premium_slug'        => 'webequipe-pdf-search-pro',
					'type'                => 'plugin',
					'public_key'          => 'pk_935a93cb7f6cf575c0f5aa0012b98',
					'is_premium'          => false,
					'has_premium_version' => true,
					'has_addons'          => false,
					'has_paid_plans'      => true,
					'anonymous_mode'      => true,
					'menu'                => array(
						'slug'    => 'webequipe-pdf-search',
						'contact' => false,
						'support' => false,
						'pricing' => true,
					),
				)
			);
		}

		return $webequipe_pdf_search_fs;
	}

	webequipe_pdf_search_fs();
	do_action( 'webequipe_pdf_search_fs_loaded' );
}

/**
 * The code that runs during plugin activation.
 *
 * @since 1.0.0
 * @return void
 */
function webequipe_pdf_search_activate() {
	// Start output buffering to prevent any unexpected output.
	ob_start();

	// Load Composer autoloader first.
	$autoloader = WEBEQUIPE_PDF_SEARCH_DIR . 'vendor/autoload.php';
	if ( file_exists( $autoloader ) ) {
		require_once $autoloader;
	}

	// Load plugin classes in correct order.
	$database_file  = WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-database.php';
	$functions_file = WEBEQUIPE_PDF_SEARCH_DIR . 'includes/functions.php';

	if ( ! file_exists( $database_file ) ) {
		ob_end_clean();
		wp_die(
			sprintf(
				/* translators: %s: file path */
				esc_html__( 'Error: Database class file not found at: %s', 'webequipe-pdf-search' ),
				esc_html( $database_file )
			)
		);
	}

	if ( ! file_exists( $functions_file ) ) {
		ob_end_clean();
		wp_die(
			sprintf(
				/* translators: %s: file path */
				esc_html__( 'Error: Functions file not found at: %s', 'webequipe-pdf-search' ),
				esc_html( $functions_file )
			)
		);
	}

	require_once $database_file;
	require_once $functions_file; // Use require_once to prevent redeclaration.

	// Create table and set options.
	if ( ! class_exists( 'WebEquipe\PDFSearch\Database' ) ) {
		ob_end_clean();
		wp_die( esc_html__( 'Error: Database class not found after loading files.', 'webequipe-pdf-search' ) );
	}

	try {
		WebEquipe\PDFSearch\Database::create_table();
		WebEquipe\PDFSearch\Database::backfill_activity_from_files();
		WebEquipe\PDFSearch\Database::set_default_options();
	} catch ( Exception $e ) {
		ob_end_clean();
		wp_die(
			sprintf(
				/* translators: %s: error message */
				esc_html__( 'Error activating WebEquipe PDF Search: %s', 'webequipe-pdf-search' ),
				esc_html( $e->getMessage() )
			)
		);
	} catch ( Error $e ) {
		ob_end_clean();
		wp_die(
			sprintf(
				/* translators: %s: error message */
				esc_html__( 'Fatal error activating WebEquipe PDF Search: %s', 'webequipe-pdf-search' ),
				esc_html( $e->getMessage() )
			)
		);
	}

	// Clean any unexpected output and end buffering.
	ob_end_clean();
}

/**
 * The code that runs during plugin deactivation.
 *
 * @since 1.0.0
 * @return void
 */
function webequipe_pdf_search_deactivate() {
	// Load Database class if not already loaded.
	if ( ! class_exists( 'WebEquipe\PDFSearch\Database' ) ) {
		$database_file = WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-database.php';
		if ( file_exists( $database_file ) ) {
			require_once $database_file;
		}
	}

	// Unschedule cron events.
	wp_clear_scheduled_hook( 'webequipe_pdf_search_background_index' );
	wp_clear_scheduled_hook( 'webequipe_pdf_search_index_pages' );
}

register_activation_hook( __FILE__, 'webequipe_pdf_search_activate' );
register_deactivation_hook( __FILE__, 'webequipe_pdf_search_deactivate' );

/**
 * Begins execution of the plugin.
 *
 * @since 1.0.0
 * @return void
 */
function webequipe_pdf_search_run() {
	// Check PHP version.
	if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
		add_action(
			'admin_notices',
			function () {
				echo '<div class="notice notice-error"><p>';
				echo esc_html__( 'WebEquipe PDF Search requires PHP 7.4 or higher. Please upgrade your PHP version.', 'webequipe-pdf-search' );
				echo '</p></div>';
			}
		);
		return;
	}

	// Check WordPress version.
	if ( version_compare( get_bloginfo( 'version' ), '6.2', '<' ) ) {
		add_action(
			'admin_notices',
			function () {
				echo '<div class="notice notice-error"><p>';
				echo esc_html__( 'WebEquipe PDF Search requires WordPress 6.2 or higher. Please upgrade WordPress.', 'webequipe-pdf-search' );
				echo '</p></div>';
			}
		);
		return;
	}

	// Load Composer autoloader.
	if ( file_exists( WEBEQUIPE_PDF_SEARCH_DIR . 'vendor/autoload.php' ) ) {
		require_once WEBEQUIPE_PDF_SEARCH_DIR . 'vendor/autoload.php';
	} else {
		add_action(
			'admin_notices',
			function () {
				echo '<div class="notice notice-error"><p>';
				echo esc_html__( 'WebEquipe PDF Search: Required dependencies are missing. Please reinstall the plugin.', 'webequipe-pdf-search' );
				echo '</p></div>';
			}
		);
		return;
	}

	// Load plugin classes (use require_once to prevent redeclaration).
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-database.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/functions.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-pdf-indexer.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-pdf-search.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-admin-settings.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-public-display.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-search-template.php';
	require_once WEBEQUIPE_PDF_SEARCH_DIR . 'includes/class-pro-launch-banner.php';

	// Load translations on init (WP 6.7+ safe). WordPress.org auto-loads translations,
	// but the Pro/self-hosted (Freemius) build needs this to load bundled .mo files.
	add_action(
		'init',
		function () {
			// phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound -- Required so the self-hosted/Pro (Freemius) build loads bundled translations; redundant but harmless on WordPress.org.
			load_plugin_textdomain(
				'webequipe-pdf-search',
				false,
				dirname( plugin_basename( __FILE__ ) ) . '/languages'
			);
		}
	);

	// Avada: define fusion_get_post_content_excerpt before the theme loads so we can return
	// our full HTML block for PDF results instead of Avada stripping/trimming it to plain text.
	add_action(
		'plugins_loaded',
		'webequipe_pdf_search_avada_excerpt_compat',
		1
	);

	// Ensure database schema is current after upgrades.
	add_action(
		'plugins_loaded',
		function () {
			if ( class_exists( 'WebEquipe\PDFSearch\Database' ) ) {
				// Activity log table is created outside version bumps so code updates on 1.2.0 still get the table.
				WebEquipe\PDFSearch\Database::create_activity_table();
				WebEquipe\PDFSearch\Database::ensure_activity_log_ready();

				$installed = get_option( 'webequipe_pdf_search_version', '0' );
				if ( version_compare( $installed, WEBEQUIPE_PDF_SEARCH_VERSION, '<' ) ) {
					WebEquipe\PDFSearch\Database::create_table();
					WebEquipe\PDFSearch\Database::ensure_activity_log_ready();
					update_option( 'webequipe_pdf_search_version', WEBEQUIPE_PDF_SEARCH_VERSION );
				}
			}
		},
		5
	);

	// Initialize classes after WordPress is fully loaded.
	add_action(
		'plugins_loaded',
		function () {
			// Initialize classes.
			new WebEquipe\PDFSearch\PDF_Indexer();
			new WebEquipe\PDFSearch\PDF_Search();
			new WebEquipe\PDFSearch\Admin_Settings();
			new WebEquipe\PDFSearch\Public_Display();
			new WebEquipe\PDFSearch\Search_Template();
			new WebEquipe\PDFSearch\Pro_Launch_Banner();
		},
		10
	);
}

/**
 * Avada compatibility: provide fusion_get_post_content_excerpt so PDF results show full block.
 *
 * Avada uses this function for grid/archive excerpts and strips HTML + truncates. By defining
 * it before the theme (priority 1), we return our full post_content for PDF search results;
 * for other posts we use the_excerpt() so normal excerpts still work.
 *
 * @since 1.0.1
 */
function webequipe_pdf_search_avada_excerpt_compat() {
	if ( function_exists( 'fusion_get_post_content_excerpt' ) ) {
		return;
	}

	/**
	 * Avada excerpt function (defined here so theme skips defining it).
	 *
	 * @param int    $limit      Character limit (unused; signature required by Avada).
	 * @param bool   $strip_html Whether to strip HTML (unused; signature required by Avada).
	 * @param string $page_id    Optional page ID (unused; signature required by Avada).
	 * @return string
	 */
	// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed, Squiz.Commenting.FunctionComment.Missing -- Avada theme API; docblock above; name/signature fixed by theme.
	function fusion_get_post_content_excerpt( $limit = 285, $strip_html = true, $page_id = '' ) {
		global $post;
		if ( ! $post ) {
			return '';
		}
		// PDF search results: return full HTML block so Avada shows meta + preview + excerpt.
		if ( is_search() && isset( $post->is_pdf_result ) && $post->is_pdf_result && ! empty( $post->post_content ) ) {
			return $post->post_content;
		}
		// Other posts: use WordPress excerpt (same approach as Relevanssi/Avada docs).
		ob_start();
		the_excerpt();
		return ob_get_clean();
	}
}

webequipe_pdf_search_run();
