<?php
/**
 * ADDON - POP for Paid Member Subscriptions (CozmosLabs)
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';

$bootstrap = function () {
	if ( ! \WcElectronInvoice\Functions\isPaidMembershipsProActive() ) {
		return;
	}


	require_once __DIR__.'/inc/snippets/council-directive-2006-112-ec.php';
	require_once __DIR__.'/inc/snippets/billing-fields.php';
	require_once __DIR__.'/inc/snippets/billing-fields-in-order.php';

	$mergeFilters = static function ( array $base, array $extra ) {
		foreach ( $extra as $context => $types ) {
			if ( ! isset( $base[ $context ] ) || ! is_array( $base[ $context ] ) ) {
				$base[ $context ] = array();
			}
			foreach ( $types as $type => $items ) {
				if ( ! isset( $base[ $context ][ $type ] ) || ! is_array( $base[ $context ][ $type ] ) ) {
					$base[ $context ][ $type ] = array();
				}
				if ( is_array( $items ) ) {
					$base[ $context ][ $type ] = array_merge( $base[ $context ][ $type ], $items );
				}
			}
		}

		return $base;
	};

	$filters = array(
		'inc'   => array( 'action' => array(), 'filter' => array() ),
		'front' => array( 'action' => array(), 'filter' => array() ),
		'admin' => array( 'action' => array(), 'filter' => array() ),
		'ajax'  => array( 'action' => array(), 'filter' => array() ),
	);

	$alwaysFilters = include \POPxPMPro\Plugin::getPluginDirPath( '/inc/filtersAlways.php' );
	if ( is_array( $alwaysFilters ) ) {
		$filters = $mergeFilters( $filters, $alwaysFilters );
	}

	if ( ! is_admin() ) {
		$frontFilters = include \POPxPMPro\Plugin::getPluginDirPath( '/inc/filtersFront.php' );
		if ( is_array( $frontFilters ) ) {
			$filters = $mergeFilters( $filters, $frontFilters );
		}
	} else {
		$adminFilters = include \POPxPMPro\Plugin::getPluginDirPath( '/inc/filtersAdmin.php' );
		if ( is_array( $adminFilters ) ) {
			$filters = $mergeFilters( $filters, $adminFilters );
		}
	}

	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		$ajaxFilters = include \POPxPMPro\Plugin::getPluginDirPath( '/inc/filtersAjax.php' );
		if ( is_array( $ajaxFilters ) ) {
			$filters = $mergeFilters( $filters, $ajaxFilters );
		}
	}

	$init = new POPxPMPro\Init( new POPxPMPro\Loader(), $filters );
	$init->init();
};

if (did_action('init')) {
	$bootstrap();
} else {
	add_action('init', $bootstrap, 9);
}
