<?php
/**
 * FinalPOS Plugin Lifecycle Management
 *
 * Handles plugin activation, deactivation, and uninstallation.
 * Following WordPress best practices:
 * - Activation: Set up initial state, redirect to setup
 * - Deactivation: Pause integrations, clean temp data, preserve user settings
 * - Uninstallation: Full cleanup (handled in uninstall.php)
 *
 * @package FinalPOS
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class FinalPOS_Lifecycle
 *
 * Manages plugin lifecycle events.
 */
class FinalPOS_Lifecycle {
	/**
	 * Instance of the class
	 *
	 * @var FinalPOS_Lifecycle
	 */
	private static $instance = null;

	/**
	 * Get the singleton instance
	 *
	 * @return FinalPOS_Lifecycle
	 */
	public static function get_instance() {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Class constructor
	 */
	private function __construct() {
		// Hook into admin notices to display reactivation errors.
		add_action( 'admin_notices', array( $this, 'display_reactivation_error' ) );
	}

	/**
	 * Handles plugin activation.
	 *
	 * Sets up initial state and schedules redirect to setup wizard.
	 *
	 * @return void
	 */
	public static function activate() {
		set_transient( FINALPOS_TRANSIENT_ACTIVATION_REDIRECT, true, 30 );
	}

	/**
	 * Restore the WooCommerce API key to read-write, activate all webhooks, and reinitiate sync on reactivation.
	 *
	 * This is the reverse of deactivate() - restores full functionality.
	 *
	 * @return void
	 */
	public static function reactivate() {
		// Only proceed if we're reactivating after a deactivation (not first-time activation).
		if ( ! get_option( FINALPOS_OPTION_JWT_TOKEN ) ) {
			return;
		}

		global $wpdb;

		// Restore API key to read-write.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->prefix}woocommerce_api_keys SET permissions = %s WHERE description LIKE %s",
				'read_write',
				FINALPOS_API_DESCRIPTION_PATTERN
			)
		);

		// Restore all webhooks to active.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->prefix}wc_webhooks SET status = %s WHERE name LIKE %s",
				'active',
				FINALPOS_WEBHOOK_NAME_PATTERN
			)
		);

		// Only attempt sync if wizard was previously completed.
		if ( get_option( FINALPOS_OPTION_CURRENT_STAGE ) === FINALPOS_STAGE_COMPLETE ) {

			try {
				$consumer_key    = get_option( FINALPOS_OPTION_CONSUMER_KEY );
				$consumer_secret = get_option( FINALPOS_OPTION_CONSUMER_SECRET );
				$site_url        = trailingslashit( home_url() );
				$company_id      = FinalPOS_Common::get_parsed_jwt_data( 'company' )['id'] ?? '';

				if ( empty( $company_id ) ) {
					throw new Exception( 'Company ID not found in token.' );
				}

				$data = array(
					'apiCredentials' => array(
						'url'      => $site_url,
						'key'      => $consumer_key,
						'secret'   => $consumer_secret,
						'platform' => 'woo-commerce',
					),
				);

				$endpoint = "v1/api/woo-sync/$company_id";
				$headers  = FinalPOS_Common::get_auth_headers();

				$response = FinalPOS_Common::api_request( $endpoint, 'PUT', $data, $headers );

				if ( is_wp_error( $response ) ) {
					throw new Exception( $response->get_error_message() );
				}

				if ( ! $response['success'] ) {
					throw new Exception( $response['message'] ?? 'Failed to initialize sync.' );
				}
			} catch ( Exception $e ) {
				// Store the error state for display on next admin page load.
				update_option( FINALPOS_OPTION_REACTIVATION_ERROR, true );
			}
		}
	}

	/**
	 * Display reactivation error notice if it exists
	 *
	 * @return void
	 */
	public function display_reactivation_error() {
		if ( get_option( FINALPOS_OPTION_REACTIVATION_ERROR ) ) {
			?>
			<div class="notice notice-error">
				<p><?php echo esc_html__( 'Could not resync your products, orders and customers after reactivation of the Final POS plugin. Please check your WooCommerce configuration in your account at', 'finalpos' ); ?> <a href="https://hub.finalpos.com" target="_blank">hub.finalpos.com</a>.</p>
			</div>
			<?php
			// Clear the error state after displaying.
			delete_option( FINALPOS_OPTION_REACTIVATION_ERROR );
		}
	}

	/**
	 * Handle plugin deactivation.
	 *
	 * Following WordPress best practices:
	 * - Pause external integrations (webhooks)
	 * - Restrict API permissions (read-only)
	 * - Clean up temporary transients
	 * - Preserve user settings (for potential reactivation)
	 *
	 * This is reversible - reactivate() restores full functionality.
	 *
	 * @return void
	 */
	public static function deactivate() {
		global $wpdb;

		// Make API key read-only (prevents write operations while plugin is inactive).
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->prefix}woocommerce_api_keys SET permissions = %s WHERE description LIKE %s",
				'read',
				FINALPOS_API_DESCRIPTION_PATTERN
			)
		);

		// Pause all webhooks (stops webhook deliveries while plugin is inactive).
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->prefix}wc_webhooks SET status = %s WHERE name LIKE %s",
				'paused',
				FINALPOS_WEBHOOK_NAME_PATTERN
			)
		);

		// Clean up temporary transients (not needed while plugin is inactive).
		delete_transient( FINALPOS_TRANSIENT_ACTIVATION_REDIRECT );

		// Clean up any pending auth nonce transients.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				'_transient_' . FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . '%',
				'_transient_timeout_' . FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . '%'
			)
		);

		// Note: We intentionally DO NOT delete user options/settings here.
		// User data is preserved for potential reactivation.
		// Full cleanup only happens on uninstall (see uninstall.php).
	}
}
