<?php
/**
 * Plugin Name:       PDFDraft PDF Invoices for WooCommerce
 * Plugin URI:        https://pdfdraft.com/features/woocommerce-integration/
 * Description:       PDFDraft PDF Invoices for WooCommerce.
 * Author:            PDFDraft
 * Author URI:        https://pdfdraft.com
 * Text Domain:       pdfdraft-pdf-invoices-for-woocommerce
 * Domain Path:       /languages
 * Version:           1.0
 * Requires PHP:      7.4.0
 * Requires at least: 6.4
 * License:           GPL-3.0+
 * License URI:       http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * @package           PDFDraft/Woocommerce
 */

defined( 'ABSPATH' ) || exit;

const PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_VERSION     = '1.0';
const PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_FILE = __FILE__;
define( 'PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_DIR', plugin_dir_path( PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_FILE ) );
define( 'PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_URL', plugin_dir_url( PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_PLUGIN_FILE ) );
define( 'PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_SETTINGS_PAGE_SLUG', 'pdfdraft-pdf-invoices-for-woocommerce-settings' );

require_once __DIR__ . '/vendor/autoload.php';

/**
 * Check whether the PDFDraft core plugin is installed (file exists on disk)
 * but not yet active.
 *
 * @return bool
 */
function pdfdraft_woo_core_is_installed(): bool {
	// The main plugin file relative to the plugins directory.
	$file = 'pdfdraft/pdfdraft.php';
	return file_exists( WP_PLUGIN_DIR . '/' . $file );
}

/**
 * Render the admin notice shown when PDFDraft core is missing or inactive.
 * Shows an "Install & Activate" button (from WordPress.org) when the plugin
 * is not installed, or an "Activate" button when it is installed but inactive.
 *
 * @return void
 */
function pdfdraft_woo_missing_core_notice(): void {
	if ( ! current_user_can( 'install_plugins' ) ) {
		return;
	}

	// Do not show the notice on the plugin installer / updater screen —
	// the user is already in the process of installing PDFDraft.
	global $pagenow;
	if ( 'update.php' === $pagenow || 'plugin-install.php' === $pagenow ) {
		return;
	}

	$plugin_file = 'pdfdraft/pdfdraft.php';
	$is_installed = pdfdraft_woo_core_is_installed();

	if ( $is_installed ) {
		// Installed but not active — show Activate button.
		$action_url = wp_nonce_url(
			self_admin_url( 'plugins.php?action=activate&plugin=' . rawurlencode( $plugin_file ) ),
			'activate-plugin_' . $plugin_file
		);
		$action_label = __( 'Activate PDFDraft', 'pdfdraft-pdf-invoices-for-woocommerce' );
	} else {
		// Not installed — show Install & Activate button (pulls from WordPress.org).
		$action_url = wp_nonce_url(
			self_admin_url( 'update.php?action=install-plugin&plugin=pdfdraft' ),
			'install-plugin_pdfdraft'
		);
		$action_label = __( 'Install &amp; Activate PDFDraft', 'pdfdraft-pdf-invoices-for-woocommerce' );
	}

	echo '<div class="notice notice-error" style="display:flex;align-items:center;gap:16px;padding:12px 16px;">';
	echo '<p style="margin:0;flex:1;">';
	echo '<strong>' . esc_html__( 'PDFDraft PDF Invoices for WooCommerce', 'pdfdraft-pdf-invoices-for-woocommerce' ) . '</strong> ';
	echo esc_html__(
		'requires the PDFDraft plugin to be installed and active.',
		'pdfdraft-pdf-invoices-for-woocommerce'
	);
	echo '</p>';
	echo '<a href="' . esc_url( $action_url ) . '" class="button button-primary" style="white-space:nowrap;">';
	echo $action_label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already escaped above
	echo '</a>';
	echo '</div>';
}

add_action(
	'plugins_loaded',
	function () {
		// Guard 1: PDFDraft bootstrap function not available — plugin not active.
		if ( ! function_exists( 'pdfdraft' ) ) {
			add_action( 'admin_notices', 'pdfdraft_woo_missing_core_notice' );
			return;
		}

		// Guard 2: PDFDraft is "active" (function exists) but its autoloader
		// hasn't registered the core traits yet — e.g. a version mismatch or a
		// race condition during first-install.  trait_exists() triggers the
		// autoloader safely and returns false instead of a fatal error.
		if ( ! trait_exists( 'PDFDraft\\Traits\\Hooks' ) ) {
			add_action(
				'admin_notices',
				static function () {
					echo '<div class="notice notice-error"><p>';
					echo '<strong>' . esc_html__( 'PDFDraft PDF Invoices for WooCommerce', 'pdfdraft-pdf-invoices-for-woocommerce' ) . '</strong> ';
					echo esc_html__(
						'could not initialise because a required PDFDraft class is missing. Please ensure PDFDraft is up to date.',
						'pdfdraft-pdf-invoices-for-woocommerce'
					);
					echo '</p></div>';
				}
			);
			return;
		}

		// Guard 3: Catch any remaining class-loading error (e.g. PHP-DI version
		// incompatibility) so it degrades to a notice rather than a white screen.
		try {
			\PDFDraft\Woocommerce\App::instance();
		} catch ( \Throwable $e ) {
			$message = $e->getMessage();
			add_action(
				'admin_notices',
				static function () use ( $message ) {
					echo '<div class="notice notice-error"><p>';
					echo '<strong>' . esc_html__( 'PDFDraft PDF Invoices for WooCommerce', 'pdfdraft-pdf-invoices-for-woocommerce' ) . '</strong> ';
					/* translators: %s: error message */
					echo esc_html( sprintf( __( 'failed to load: %s', 'pdfdraft-pdf-invoices-for-woocommerce' ), $message ) );
					echo '</p></div>';
				}
			);
		}
	},
	20
);
