<?php
/**
 * ICS CALENDAR PRO // RESOLVE CONFLICTS WITH ACF (FREE) AND SCF
 *
 * This file is installed in `wp-content/mu-plugins` automatically when ICS Calendar Pro
 * is activated, and is removed automatically when the plugin is deactivated.
 *
 * ICS Calendar Pro requires Advanced Custom Fields Pro, which is embedded in the
 * *vendors* folder. If your site has the free Advanced Custom Fields or the forked
 * plugin Secure Custom Fields installed, ICS Calendar Pro will not function properly.
 *
 * This file selectively and temporarily deactivates ACF and SCF _only_ while viewing an
 * ICS Calendar Pro editing screen. It has no impact on the functionality of these plugins
 * anywhere else on your site. ICS Calendar Pro's embedded version of ACF Pro _only_ loads
 * while viewing an ICS Calendar Pro editing screen.
 *
 * Please email info@icscalendar.com for additional information.
 */

// phpcs:disable WordPress.Security.NonceVerification.Recommended
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated

// Don't load directly
if (!defined('ABSPATH')) { exit; }

add_filter('option_active_plugins', function($plugins) {
	global $r34icspro_acf_bypass;
	// This conditional must exactly match the `r34icspro_is_r34icspro()` function!
	if (
		is_admin() &&
		in_array(pathinfo($_SERVER['PHP_SELF'], PATHINFO_BASENAME), array('edit.php', 'post.php', 'post-new.php')) &&
		((!empty($_REQUEST['post_type']) && in_array($_REQUEST['post_type'], array('r34icspro_calendar', 'r34icspro_event'))) ||
		(!empty($_REQUEST['post']) && in_array(get_post_type(intval($_REQUEST['post'])), array('r34icspro_calendar', 'r34icspro_event'))))
	)
	{
		// Remember, $key is NOT the plugin's folder/filename in this array!
		foreach (array('advanced-custom-fields/acf.php', 'secure-custom-fields/secure-custom-fields.php') as $plugin) {
			$key = array_search($plugin, $plugins);
			if ($key !== false) {
				unset($plugins[$key]);
				$r34icspro_acf_bypass = true;
			}
		}
	}
	return $plugins;
});

// Check network active plugins
add_filter('site_option_active_sitewide_plugins', function($plugins, $option, $network_id) {
	// This conditional must exactly match the `r34icspro_is_r34icspro()` function!
	if (
		is_admin() &&
		in_array(pathinfo($_SERVER['PHP_SELF'], PATHINFO_BASENAME), array('edit.php', 'post.php', 'post-new.php')) &&
		((!empty($_REQUEST['post_type']) && in_array($_REQUEST['post_type'], array('r34icspro_calendar', 'r34icspro_event'))) ||
		(!empty($_REQUEST['post']) && in_array(get_post_type(intval($_REQUEST['post'])), array('r34icspro_calendar', 'r34icspro_event'))))
	)
	{
		// Unlike above, the plugin's folder/filename IS the key in this array
		unset($plugins['advanced-custom-fields/acf.php']);
		unset($plugins['secure-custom-fields/secure-custom-fields.php']);
		$r34icspro_acf_bypass = true;
	}
	return $plugins;
}, 10, 3);
