<?php
/**
 * WooCommerce webhook management.
 *
 * Registers and manages WooCommerce webhooks that deliver
 * order events to the MEM platform.
 *
 * @package Memwc_Connector
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class Memwc_Webhooks
 *
 * Handles WooCommerce webhook registration and removal.
 */
class Memwc_Webhooks {

	/**
	 * Webhook topics to register.
	 *
	 * These map to WooCommerce webhook events that MEM needs to receive.
	 *
	 * @var array
	 */
	private static $webhook_topics = array(
		'order.created',
		'order.updated',
	);

	/**
	 * WooCommerce REST API version for webhook payloads.
	 *
	 * @var int
	 */
	const WEBHOOK_API_VERSION = 3;

	/**
	 * Register WooCommerce webhooks for MEM.
	 *
	 * Creates webhooks that deliver order events directly to the MEM platform.
	 * The webhook secret is used by MEM to verify the request authenticity via
	 * the X-WC-Webhook-Signature header.
	 *
	 * @param string $delivery_url The MEM endpoint URL for webhook delivery.
	 * @param string $secret       The store secret used as webhook signing key.
	 * @return array|WP_Error Array of webhook IDs on success, WP_Error on failure.
	 */
	public static function register_webhooks( $delivery_url, $secret ) {
		if ( empty( $delivery_url ) || empty( $secret ) ) {
			return new WP_Error(
				'mem_invalid_webhook_params',
				__( 'Webhook delivery URL and secret are required.', 'my-easy-monogram' )
			);
		}

		if ( ! class_exists( 'WC_Webhook' ) ) {
			return new WP_Error(
				'mem_wc_webhook_missing',
				__( 'WooCommerce webhook class is not available. Please ensure WooCommerce is active.', 'my-easy-monogram' )
			);
		}

		// Remove any existing MEM webhooks first to prevent duplicates.
		self::remove_all_webhooks();

		$webhook_ids = array();

		foreach ( self::$webhook_topics as $topic ) {
			$webhook = new WC_Webhook();
			$webhook->set_name(
				sprintf(
					/* translators: %s: webhook event name (e.g., "Order Created") */
					__( 'My Easy Monogram — %s', 'my-easy-monogram' ),
					ucwords( str_replace( '.', ' ', $topic ) )
				)
			);
			$webhook->set_topic( $topic );
			$webhook->set_delivery_url( $delivery_url );
			$webhook->set_secret( $secret );
			$webhook->set_status( 'active' );
			$webhook->set_user_id( get_current_user_id() );
			$webhook->set_api_version( self::WEBHOOK_API_VERSION );
			$webhook->save();

			if ( $webhook->get_id() ) {
				$webhook_ids[] = $webhook->get_id();
			}
		}

		if ( empty( $webhook_ids ) ) {
			return new WP_Error(
				'mem_webhook_creation_failed',
				__( 'Failed to create WooCommerce webhooks.', 'my-easy-monogram' )
			);
		}

		update_option( 'memwc_connector_webhook_ids', $webhook_ids, false );

		return $webhook_ids;
	}

	/**
	 * Remove all MEM-registered webhooks.
	 *
	 * Deletes all webhooks that were created by this plugin,
	 * identified by the stored webhook IDs.
	 *
	 * @return void
	 */
	public static function remove_all_webhooks() {
		if ( ! function_exists( 'wc_get_webhook' ) || ! class_exists( 'WC_Data_Store' ) ) {
			delete_option( 'memwc_connector_webhook_ids' );
			return;
		}

		// Collect IDs from the stored option AND any orphaned MEM webhooks by name.
		$stored_ids = get_option( 'memwc_connector_webhook_ids', array() );
		$all_ids    = is_array( $stored_ids ) ? $stored_ids : array();

		try {
			$data_store   = WC_Data_Store::load( 'webhook' );
			$searched_ids = $data_store->search_webhooks( [
				'search' => 'My Easy Monogram',
				'limit'  => -1,
			] );
			if ( is_array( $searched_ids ) ) {
				$all_ids = array_unique( array_merge( $all_ids, $searched_ids ) );
			}
		} catch ( Exception $e ) {
			// Fall through with stored IDs only.
		}

		foreach ( $all_ids as $webhook_id ) {
			$webhook = wc_get_webhook( absint( $webhook_id ) );
			if ( $webhook ) {
				$webhook->delete( true );
			}
		}

		delete_option( 'memwc_connector_webhook_ids' );
	}

	/**
	 * Get the registered webhook topics.
	 *
	 * @return array
	 */
	public static function get_webhook_topics() {
		return self::$webhook_topics;
	}
}
