<?php
/**
 * Plugin Name: Harbor Sync with Attio for WooCommerce
 * Plugin URI:  https://harborplugins.com/plugins/attio-sync
 * Description: Sync WooCommerce customers and orders to Attio CRM natively in real time.
 * Version:     1.0.2
 * Requires at least: 6.2
 * Requires PHP: 8.1
 * Requires Plugins: woocommerce
 * Author:      Harbor Plugins
 * Author URI:  https://harborplugins.com
 * License:     GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: harbor-sync-with-attio-for-woocommerce
 * Domain Path: /languages
 * WC requires at least: 7.0
 * WC tested up to: 10.9
 * @fs_premium_only /includes/class-pro.php, /includes/class-field-mapper.php
 * @fs_premium_only /includes/class-two-way-sync.php, /includes/class-list-automation.php
 * @fs_premium_only /includes/class-enrichment.php, /includes/class-tasks.php
 * @fs_premium_only /includes/class-deals.php
 * @fs_premium_only /assets/admin-pro.js
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

define( 'WCATTIO_VERSION', '1.0.2' );
define( 'WCATTIO_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'WCATTIO_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

// ---------------------------------------------------------------------------
// Freemius SDK — Pro license management
// ---------------------------------------------------------------------------
// Freemius product credentials from dashboard.freemius.com. Both the ID and the
// public key are safe to commit and ship; the secret key must never be here.

defined( 'WCATTIO_FS_PRODUCT_ID' ) || define( 'WCATTIO_FS_PRODUCT_ID', 35546 );
defined( 'WCATTIO_FS_PUBLIC_KEY' ) || define( 'WCATTIO_FS_PUBLIC_KEY', 'pk_7b244ca1a6af0267beeb43b352686' );

if ( ! function_exists( 'wcattio_fs' ) ) {
	/**
	 * Returns the Freemius SDK instance, or null when not yet configured
	 *
	 * @return \Freemius|null
	 */
	function wcattio_fs(): ?\Freemius {
		global $wcattio_fs;

		if ( isset( $wcattio_fs ) ) {
			return $wcattio_fs;
		}

		// Guard: only initialize when real credentials are configured
		$product_id = defined( 'WCATTIO_FS_PRODUCT_ID' ) ? (int) WCATTIO_FS_PRODUCT_ID : 0;
		$public_key = defined( 'WCATTIO_FS_PUBLIC_KEY' ) ? (string) WCATTIO_FS_PUBLIC_KEY : '';

		if ( $product_id <= 0 || '' === $public_key || str_starts_with( $public_key, 'pk_YOUR' ) ) {
			$wcattio_fs = null;
			return null;
		}

		if ( ! function_exists( 'fs_dynamic_init' ) ) {
			require_once WCATTIO_PLUGIN_DIR . 'vendor/freemius/wordpress-sdk/start.php';
		}

		$wcattio_fs = fs_dynamic_init(
			array(
				'id'                  => (string) $product_id,
				// Must equal the WordPress.org / plugin-folder slug so Freemius can
				// map the hosted free plugin to the Freemius product for licensing.
				'slug'                => 'harbor-sync-with-attio-for-woocommerce',
				'type'                => 'plugin',
				'public_key'          => $public_key,
				'is_premium'          => false,
				'premium_suffix'      => 'Pro',
				'is_live'             => true,
				'has_premium_version' => true,
				'has_affiliation'     => 'all',
				'has_addons'          => false,
				'has_paid_plans'      => true,
				'trial'               => array(
					'days'               => 14,
					'is_require_payment' => false,
				),
				'menu'                => array(
					'slug'       => 'wcattio-settings',
					'first-path' => 'admin.php?page=wcattio-settings',
				),
			)
		);

		if ( null !== $wcattio_fs ) {
			$wcattio_fs->add_action( 'after_uninstall', 'wcattio_uninstall_cleanup' );
		}

		return $wcattio_fs;
	}
}

if ( ! function_exists( 'wcattio_is_pro' ) ) {
	/**
	 * Returns true when the site has an active paid Freemius license.
	 *
	 * The result is passed through the 'wcattio_is_pro' filter so Pro features can
	 * be exercised in integration tests (and by advanced users) without a live
	 * Freemius license. The Freemius value is the default.
	 */
	function wcattio_is_pro(): bool {
		$fs     = wcattio_fs();
		$is_pro = null !== $fs && $fs->is_paying();

		/**
		 * Filters whether the current site should be treated as Pro.
		 *
		 * @param bool $is_pro Default from the Freemius license state.
		 */
		return (bool) apply_filters( 'wcattio_is_pro', $is_pro );
	}
}

/**
 * Declare WooCommerce HPOS (High Performance Order Storage) compatibility
 */
add_action(
	'before_woocommerce_init',
	static function (): void {
		if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
				'custom_order_tables',
				__FILE__,
				true
			);
		}
	}
);

/**
 * Show an admin notice when WooCommerce is not active
 */
function wcattio_woocommerce_missing_notice(): void {
	echo '<div class="notice notice-error"><p>' .
		esc_html__(
			'Harbor Sync with Attio for WooCommerce requires WooCommerce to be installed and active.',
			'harbor-sync-with-attio-for-woocommerce'
		) .
		'</p></div>';
}

/**
 * Returns true when WooCommerce is available
 */
function wcattio_woocommerce_is_active(): bool {
	return class_exists( 'WooCommerce' );
}

/**
 * Boot the plugin after all plugins have loaded.
 * Priority 20 ensures WooCommerce (which loads at priority 10) is fully initialized.
 */
function wcattio_init_plugin(): void {
	// Initialize Freemius at boot so its menu/opt-in/license hooks register on every
	// request once credentials are configured. Returns (and does nothing) while the
	// WCATTIO_FS_* constants are unset, so this is a safe no-op until Pro is wired.
	wcattio_fs();

	if ( ! wcattio_woocommerce_is_active() ) {
		add_action( 'admin_notices', 'wcattio_woocommerce_missing_notice' );
		return;
	}

	require_once WCATTIO_PLUGIN_DIR . 'includes/class-install.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-attio-client.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-sync-log.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-customer-stats.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-sync-customer.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-sync-order.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-bulk-sync.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-sync-queue.php';

	// Pro-only files are stripped from the free build (see @fs_premium_only above);
	// load them only when present rather than requiring them unconditionally
	foreach ( array( 'class-field-mapper.php', 'class-two-way-sync.php', 'class-list-automation.php', 'class-enrichment.php', 'class-tasks.php', 'class-deals.php', 'class-pro.php' ) as $pro_file ) {
		$pro_path = WCATTIO_PLUGIN_DIR . 'includes/' . $pro_file;
		if ( file_exists( $pro_path ) ) {
			require_once $pro_path;
		}
	}

	require_once WCATTIO_PLUGIN_DIR . 'includes/class-admin-settings.php';
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-harbor-attio-sync.php';

	// Run DB upgrade when schema version is behind
	if ( WooAttioSync_Install::needs_upgrade() ) {
		WooAttioSync_Install::activate();
	}

	WooAttioSync::get_instance();

	add_action(
		'wcattio_cleanup_logs',
		static function (): void {
			WooAttioSync_Sync_Log::clear_old_logs( 30 );
		}
	);
}
add_action( 'plugins_loaded', 'wcattio_init_plugin', 20 );

/**
 * Removes all plugin data on uninstall.
 *
 * Registered both via register_uninstall_hook() (used when no uninstall.php exists)
 * and via Freemius' after_uninstall action (Freemius deployments reject zips that
 * contain uninstall.php). The cleanup itself is idempotent, so running twice is safe.
 */
function wcattio_uninstall_cleanup(): void {
	require_once WCATTIO_PLUGIN_DIR . 'includes/class-install.php';
	WooAttioSync_Install::uninstall();
}

/**
 * Activation hook
 */
register_activation_hook(
	__FILE__,
	static function (): void {
		require_once plugin_dir_path( __FILE__ ) . 'includes/class-install.php';
		WooAttioSync_Install::activate();

		if ( ! wp_next_scheduled( 'wcattio_cleanup_logs' ) ) {
			wp_schedule_event( time(), 'daily', 'wcattio_cleanup_logs' );
		}

		register_uninstall_hook( __FILE__, 'wcattio_uninstall_cleanup' );
	}
);

/**
 * Deactivation hook — cancel all pending sync jobs and the log-cleanup cron
 */
register_deactivation_hook(
	__FILE__,
	static function (): void {
		if ( function_exists( 'as_unschedule_all_actions' ) ) {
			as_unschedule_all_actions( '', array(), 'wcattio' );
		}
		wp_clear_scheduled_hook( 'wcattio_cleanup_logs' );
		if ( class_exists( 'WooAttioSync_Bulk_Sync' ) ) {
			delete_transient( WooAttioSync_Bulk_Sync::LOCK_CUSTOMERS );
			delete_transient( WooAttioSync_Bulk_Sync::LOCK_ORDERS );
		}
	}
);
