<?php
/**
 * Admin functions
 *
 * Functions for the admin back end components only.
 *
 * @package SimpleCalendar/Admin/Functions
 */

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

use SimpleCalendar\Admin\Notice;
use SimpleCalendar\Add_On_Google_Pro;
use SimpleCalendar\Simple_Calendar_Appointment;
/**
 * Get settings pages and tabs.
 *
 * @since  3.0.0
 *
 * @return array
 */
function simcal_get_admin_pages()
{
	$objects = \SimpleCalendar\plugin()->objects;
	return $objects instanceof \SimpleCalendar\Objects ? $objects->get_admin_pages() : [];
}

/**
 * Get a settings page tab.
 *
 * @since  3.0.0
 *
 * @param  string $page
 *
 * @return null|\SimpleCalendar\Abstracts\Admin_Page
 */
function simcal_get_admin_page($page)
{
	$objects = \SimpleCalendar\plugin()->objects;
	return $objects instanceof \SimpleCalendar\Objects ? $objects->get_admin_page($page) : null;
}

/**
 * Get a field.
 *
 * @since  3.0.0
 *
 * @param  array  $args
 * @param  string $name
 *
 * @return null|\SimpleCalendar\Abstracts\Field
 */
function simcal_get_field($args, $name = '')
{
	$objects = \SimpleCalendar\plugin()->objects;
	return $objects instanceof \SimpleCalendar\Objects ? $objects->get_field($args, $name) : null;
}

/**
 * Print a field.
 *
 * @since  3.0.0
 *
 * @param  array  $args
 * @param  string $name
 *
 * @return void
 */
function simcal_print_field($args, $name = '')
{
	$field = simcal_get_field($args, $name);

	if ($field instanceof \SimpleCalendar\Abstracts\Field) {
		$field->html();
	}
}

/**
 * Sanitize a variable of unknown type.
 *
 * Recursive helper function to sanitize a variable from input,
 * which could also be a multidimensional array of variable depth.
 *
 * @since  3.0.0
 *
 * @param  mixed  $var  Variable to sanitize.
 * @param  string $func Function to use for sanitizing text strings (default 'sanitize_text_field')
 *
 * @return array|string Sanitized variable
 */
function simcal_sanitize_input($var, $func = 'sanitize_text_field')
{
	if (is_null($var)) {
		return '';
	}

	if (is_bool($var)) {
		if ($var === true) {
			return 'yes';
		} else {
			return 'no';
		}
	}

	if (is_string($var) || is_numeric($var)) {
		$func = is_string($func) && function_exists($func) ? $func : 'sanitize_text_field';
		return call_user_func($func, trim(strval($var)));
	}

	if (is_object($var)) {
		$var = (array) $var;
	}

	if (is_array($var)) {
		$array = [];
		foreach ($var as $k => $v) {
			$array[$k] = simcal_sanitize_input($v);
		}
		return $array;
	}

	return '';
}

/**
 * Whether the installed Google Calendar Pro add-on meets a minimum version.
 *
 * If the Pro add-on isn't active/loaded (constant not defined), this returns true.
 *
 * @since 4.0.0
 *
 * @param string $min_version Minimum required version (default 2.0.0).
 * @return bool
 */
function simcal_is_google_calendar_pro_version_compatible($min_version = '2.0.0')
{
	if (!defined('SIMPLE_CALENDAR_GOOGLE_PRO_VERSION')) {
		return true;
	}

	$installed = (string) SIMPLE_CALENDAR_GOOGLE_PRO_VERSION;
	$min = is_string($min_version) && $min_version !== '' ? $min_version : '2.0.0';

	// If version string is missing/unexpected, fail closed (require update).
	if ($installed === '') {
		return false;
	}

	return version_compare($installed, $min, '>=');
}

function simcal_is_google_calendar_book_an_appointment_version_compatible($min_version = '2.0.0')
{
	if (!defined('SIMPLE_CALENDAR_APPOINTMENT_VERSION')) {
		return true;
	}

	$installed = (string) SIMPLE_CALENDAR_APPOINTMENT_VERSION;
	$min = is_string($min_version) && $min_version !== '' ? $min_version : '2.0.0';

	// If version string is missing/unexpected, fail closed (require update).
	if ($installed === '') {
		return false;
	}

	return version_compare($installed, $min, '>=');
}

/**
 * Check if a screen is a plugin admin view.
 * Returns the screen id if true, false (bool) if not.
 *
 * @since  3.0.0
 *
 * @return string|bool
 */
function simcal_is_admin_screen()
{
	$view = function_exists('get_current_screen') ? get_current_screen() : false;

	if ($view instanceof WP_Screen) {
		// Screens used by this plugin.
		$screens = [
			'customize',
			'calendar',
			'calendar_page_simple-calendar_add_ons',
			'calendar_page_simple-calendar_settings',
			'calendar_page_simple-calendar_misc_settings',
			'calendar_page_simple-calendar_tools',
			'edit-calendar',
			'edit-calendar_category',
		];
		if (in_array($view->id, $screens)) {
			return $view->id;
		}
	}

	return false;
}

/**
 * Update add-on.
 *
 * @since 3.0.0
 *
 * @param string $_api_url     The URL pointing to the custom API end
 * @param string $_plugin_file Path to the plugin file.
 * @param array  $_api_data    Optional data to send with API calls.
 *
 * @return \SimpleCalendar\Admin\Updater
 */
function simcal_addon_updater($_api_url, $_plugin_file, $_api_data = null)
{
	return new \SimpleCalendar\Admin\Updater($_api_url, $_plugin_file, $_api_data);
}

/**
 * Get add-on license key.
 *
 * @since  3.0.0
 *
 * @param  string $addon Unique add-on id.
 *
 * @return null|string
 */
function simcal_get_license_key($addon)
{
	$licenses = get_option('simple-calendar_settings_licenses', []);
	if (isset($licenses['keys'][$addon])) {
		return empty($licenses['keys'][$addon]) ? null : $licenses['keys'][$addon];
	}
	return null;
}

/**
 * Get add-on license status.
 *
 * Without passing arguments returns all the statuses array.
 *
 * @since  3.0.0
 *
 * @param  null|string $addon Unique add-on slug.
 *
 * @return array|string
 */
function simcal_get_license_status($addon = null)
{
	$licenses = get_option('simple-calendar_licenses_status', []);
	return isset($licenses[$addon]) ? $licenses[$addon] : $licenses;
}

/**
 * Get Connect page field definitions.
 *
 * Mirrors the classic `settings_fields()` pattern (field definitions in PHP, extensible via hooks),
 * but intended for the Connect onboarding UI.
 *
 * @since 4.0.0
 *
 * @return array
 */
function simcal_connect_settings_fields()
{
	$fields = [
		'google' => [
			'name' => __('Google Calendar', 'google-calendar-events'),
			'fields' => [
				'api_key' => [
					'id' => 'sc_google_api_key',
					'name' => 'simple-calendar_settings_feeds[google][api_key]',
					'type' => 'password',
					'label' => __('Google API Key', 'google-calendar-events'),
				],
			],
		],
	];

	return apply_filters('simcal_connect_settings_fields', $fields);
}

/**
 * Back-compat wrapper for suggested name.
 *
 * Guarded to avoid fatal redeclare collisions if another plugin/theme
 * defines the same helper.
 *
 * @since 4.0.0
 *
 * @return array
 */
if (!function_exists('connect_settings_fields')) {
	function connect_settings_fields()
	{
		return simcal_connect_settings_fields();
	}
}

/**
 * Hash scheme for storing "verified" Connect Google API key fingerprint.
 *
 * @since 4.0.0
 */
const SIMCAL_CONNECT_GOOGLE_API_KEY_VERIFY_SCHEME = 'simcal_connect_google_api_key';

/**
 * Mark the given API key as verified for Connect / core onboarding progress.
 *
 * @since 4.0.0
 *
 * @param string $api_key Raw API key (trimmed internally).
 */
function simcal_mark_connect_google_api_key_verified($api_key)
{
	$k = trim((string) $api_key);
	if ($k === '') {
		return;
	}
	update_option(
		'simple_calendar_connect_core_api_key_verified_hash',
		wp_hash($k, SIMCAL_CONNECT_GOOGLE_API_KEY_VERIFY_SCHEME),
		false,
	);
}

/**
 * Clear verified state (e.g. after failed health check).
 *
 * @since 4.0.0
 */
function simcal_clear_connect_google_api_key_verified()
{
	delete_option('simple_calendar_connect_core_api_key_verified_hash');
}

/**
 * Whether the saved API key matches the last verified fingerprint.
 *
 * @since 4.0.0
 *
 * @param string $api_key Current saved key (as in settings).
 * @return bool
 */
function simcal_is_connect_google_api_key_verified($api_key)
{
	$k = trim((string) $api_key);
	if ($k === '') {
		return false;
	}
	$h = get_option('simple_calendar_connect_core_api_key_verified_hash', '');
	if (!is_string($h) || $h === '') {
		return false;
	}
	return hash_equals($h, wp_hash($k, SIMCAL_CONNECT_GOOGLE_API_KEY_VERIFY_SCHEME));
}

/**
 * Whether Simple Calendar Google Calendar Pro add-on is active.
 *
 * Note: Some Connect screens also render in a "pro" onboarding context even when the add-on
 * isn't installed yet. Pass the onboarding context to treat that UI path as Pro.
 *
 * @since 4.0.0
 *
 * @param string $connect_flow_context Optional. 'pro' or 'core' (Connect onboarding context).
 * @return bool
 */
function simcal_is_google_calendar_pro_active($connect_flow_context = '')
{
	$connect_flow_context = (string) $connect_flow_context;

	$is_pro_active = false;

	// Runtime signals (add-on loaded).
	if (defined('SIMPLE_CALENDAR_GOOGLE_PRO_VERSION')) {
		$is_pro_active = true;
	} elseif (class_exists('Google_Pro')) {
		$is_pro_active = true;
	} elseif (class_exists('\SimpleCalendar\Feeds\Google_Pro')) {
		$is_pro_active = true;
	} elseif ('pro' === $connect_flow_context) {
		// Connect onboarding can be forced into a Pro context via saved choice/query args.
		$is_pro_active = true;
	}

	// If we still don't know, fall back to plugin activation checks (works when add-on files exist but aren't loaded yet).
	if (!$is_pro_active) {
		if (!function_exists('is_plugin_active') && defined('ABSPATH')) {
			$plugin_file = trailingslashit(ABSPATH) . 'wp-admin/includes/plugin.php';
			if (is_readable($plugin_file)) {
				// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
				require_once $plugin_file;
			}
		}

		if (function_exists('is_plugin_active')) {
			$is_pro_active = is_plugin_active('simple-calendar-google-calendar-pro/simple-calendar-google-calendar-pro.php');
		} else {
			$active_plugins = (array) get_option('active_plugins', []);
			$active_plugins = array_map('strval', $active_plugins);
			foreach ($active_plugins as $p) {
				$p_lower = strtolower($p);
				if (
					strpos($p_lower, 'google-calendar-pro') !== false ||
					strpos($p_lower, 'simple-calendar-google-calendar-pro') !== false
				) {
					$is_pro_active = true;
					break;
				}
			}

			// Multisite: network-activated plugins live in active_sitewide_plugins (keys are plugin filenames).
			if (!$is_pro_active) {
				$sitewide = (array) get_option('active_sitewide_plugins', []);
				$sitewide_files = array_map('strval', array_keys($sitewide));
				foreach ($sitewide_files as $p) {
					$p_lower = strtolower($p);
					if (
						strpos($p_lower, 'google-calendar-pro') !== false ||
						strpos($p_lower, 'simple-calendar-google-calendar-pro') !== false
					) {
						$is_pro_active = true;
						break;
					}
				}
			}
		}
	}

	return (bool) apply_filters('simcal_is_google_calendar_pro_active', $is_pro_active);
}

/**
 * Whether the Simple Calendar FullCalendar add-on is active.
 *
 * Mirrors {@see simcal_is_google_calendar_pro_active()} so the Add-ons page and other UI
 * can detect the add-on even when the plugin directory name differs from the default.
 *
 * @since 4.0.0
 *
 * @return bool
 */
function simcal_is_fullcalendar_addon_active()
{
	$is_active = false;

	if (defined('SIMPLE_CALENDAR_FULLCALENDAR_VERSION')) {
		$is_active = true;
	} elseif (class_exists('\SimpleCalendar\Add_On_FullCalendar')) {
		$is_active = true;
	}

	if (!$is_active) {
		if (!function_exists('is_plugin_active') && defined('ABSPATH')) {
			$plugin_file = trailingslashit(ABSPATH) . 'wp-admin/includes/plugin.php';
			if (is_readable($plugin_file)) {
				// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
				require_once $plugin_file;
			}
		}

		if (function_exists('is_plugin_active')) {
			$is_active = is_plugin_active('simple-calendar-fullcalendar/simple-calendar-fullcalendar.php');
		} else {
			$active_plugins = (array) get_option('active_plugins', []);
			$active_plugins = array_map('strval', $active_plugins);
			foreach ($active_plugins as $p) {
				$p_lower = strtolower($p);
				if (
					strpos($p_lower, 'simple-calendar-fullcalendar') !== false ||
					(strpos($p_lower, 'fullcalendar') !== false && strpos($p_lower, 'simple-calendar') !== false)
				) {
					$is_active = true;
					break;
				}
			}

			if (!$is_active) {
				$sitewide = (array) get_option('active_sitewide_plugins', []);
				$sitewide_files = array_map('strval', array_keys($sitewide));
				foreach ($sitewide_files as $p) {
					$p_lower = strtolower($p);
					if (
						strpos($p_lower, 'simple-calendar-fullcalendar') !== false ||
						(strpos($p_lower, 'fullcalendar') !== false && strpos($p_lower, 'simple-calendar') !== false)
					) {
						$is_active = true;
						break;
					}
				}
			}
		}
	}

	return (bool) apply_filters('simcal_is_fullcalendar_addon_active', $is_active);
}

/**
 * Whether the Simple Calendar Book an Appointment add-on is active.
 *
 * Mirrors the other add-on detection helpers so Connect can keep the Appointment
 * onboarding context even when Google Calendar Pro is also active.
 *
 * @since 4.0.0
 *
 * @return bool
 */
function simcal_is_appointment_addon_active()
{
	$is_active = false;

	if (defined('SIMPLE_CALENDAR_APPOINTMENT_VERSION')) {
		$is_active = true;
	} elseif (class_exists('\SimpleCalendar\Simple_Calendar_Appointment')) {
		$is_active = true;
	}

	if (!$is_active) {
		if (!function_exists('is_plugin_active') && defined('ABSPATH')) {
			$plugin_file = trailingslashit(ABSPATH) . 'wp-admin/includes/plugin.php';
			if (is_readable($plugin_file)) {
				// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
				require_once $plugin_file;
			}
		}

		if (function_exists('is_plugin_active')) {
			$is_active = is_plugin_active('simple-calendar-appointment/simple-calendar-appointment.php');
		} else {
			$active_plugins = (array) get_option('active_plugins', []);
			$active_plugins = array_map('strval', $active_plugins);
			foreach ($active_plugins as $p) {
				$p_lower = strtolower($p);
				if (
					strpos($p_lower, 'simple-calendar-appointment') !== false ||
					(strpos($p_lower, 'appointment') !== false && strpos($p_lower, 'simple-calendar') !== false)
				) {
					$is_active = true;
					break;
				}
			}

			if (!$is_active) {
				$sitewide = (array) get_option('active_sitewide_plugins', []);
				$sitewide_files = array_map('strval', array_keys($sitewide));
				foreach ($sitewide_files as $p) {
					$p_lower = strtolower($p);
					if (
						strpos($p_lower, 'simple-calendar-appointment') !== false ||
						(strpos($p_lower, 'appointment') !== false && strpos($p_lower, 'simple-calendar') !== false)
					) {
						$is_active = true;
						break;
					}
				}
			}
		}
	}

	return (bool) apply_filters('simcal_is_appointment_addon_active', $is_active);
}

/**
 * Build variables for Connect sidebar (progress / rating / Pro CTA) and Connect step logic.
 *
 * Mirrors {@see SIMPLE_CALENDAR_PATH}/includes/admin/pages/connect-controller.php onboarding
 * detection so Misc Settings and Connect show the same core vs Pro progress rules.
 *
 * @since 4.0.0
 *
 * @return array{
 *   welcome_context: string,
 *   is_pro_active: bool,
 *   is_pro_flow: bool,
 *   api_key: string,
 *   has_api_key: bool,
 *   has_core_api_key_verified: bool,
 *   has_oauth_connection: bool,
 *   has_client_credentials: bool,
 *   has_published_pro_calendar: bool,
 *   has_published_calendar: bool,
 *   should_hide_progress: bool,
 *   assets_base: string
 * }
 */
function simcal_prepare_connect_sidebar_scope()
{
	static $cached_scope = null;
	if (null !== $cached_scope) {
		return $cached_scope;
	}

	$welcome_context = (string) get_option('simple_calendar_connect_welcome_context', '');
	$welcome_context = $welcome_context ? $welcome_context : 'core';

	$is_appointment_active =
		defined('SIMPLE_CALENDAR_APPOINTMENT_VERSION') ||
		class_exists('\SimpleCalendar\Simple_Calendar_Appointment') ||
		(function_exists('simcal_is_appointment_addon_active') && simcal_is_appointment_addon_active());
	$is_google_pro_active = simcal_is_google_calendar_pro_active('');
	$is_pro_active = $is_google_pro_active || $is_appointment_active;
	if ('appointment' === $welcome_context && !$is_appointment_active) {
		$welcome_context = $is_google_pro_active ? 'pro' : 'core';
		update_option('simple_calendar_connect_welcome_context', $welcome_context, false);
	} elseif ('pro' === $welcome_context && !$is_google_pro_active && $is_appointment_active) {
		$welcome_context = 'appointment';
		update_option('simple_calendar_connect_welcome_context', $welcome_context, false);
	} elseif ('pro' === $welcome_context && !$is_google_pro_active && !$is_appointment_active) {
		$welcome_context = 'core';
		delete_option('simple_calendar_connect_welcome_context');
	}

	// phpcs:disable WordPress.Security.NonceVerification.Recommended -- OAuth return URL; state verified below.
	if (!empty($_GET['auth_token'])) {
		$auth_token = sanitize_text_field((string) wp_unslash($_GET['auth_token']));

		$helper_origin_ok = false;
		$helper_domain = defined('SIMPLE_CALENDAR_OAUTH_HELPER_AUTH_DOMAIN')
			? (string) SIMPLE_CALENDAR_OAUTH_HELPER_AUTH_DOMAIN
			: '';
		$helper_host = $helper_domain ? wp_parse_url($helper_domain, PHP_URL_HOST) : '';

		if ($auth_token && current_user_can('manage_options')) {
			update_option('simple_calendar_auth_site_token', $auth_token, true);
			if ($is_pro_active) {
				update_option('simple_calendar_connect_pro_connection_type', 'via_sc', false);
			}
		}
	}
	// phpcs:enable WordPress.Security.NonceVerification.Recommended

	$feeds_options = get_option('simple-calendar_settings_feeds', []);
	$api_key = isset($feeds_options['google']['api_key']) ? $feeds_options['google']['api_key'] : '';
	$has_api_key = !empty(trim((string) $api_key));
	$has_core_api_key_verified = function_exists('simcal_is_connect_google_api_key_verified')
		? simcal_is_connect_google_api_key_verified((string) $api_key)
		: false;
	$auth_site_token = (string) get_option('simple_calendar_auth_site_token', '');
	$has_oauth_connection = !empty(trim($auth_site_token));
	$google_pro =
		isset($feeds_options['google-pro']) && is_array($feeds_options['google-pro']) ? $feeds_options['google-pro'] : [];
	$has_client_credentials =
		!empty(trim((string) ($google_pro['client_id'] ?? ''))) &&
		!empty(trim((string) ($google_pro['client_secret'] ?? '')));

	$has_published_pro_calendar = false;

	$pro_query_base = [
		'post_type' => 'calendar',
		'post_status' => 'publish',
		'posts_per_page' => 1,
		'fields' => 'ids',
	];

	if (taxonomy_exists('calendar_feed')) {
		$pro_calendar_query = new \WP_Query(
			array_merge($pro_query_base, [
				'tax_query' => [
					[
						'taxonomy' => 'calendar_feed',
						'field' => 'slug',
						'terms' => ['google-pro', 'google_pro'],
					],
				],
			]),
		);
		$has_published_pro_calendar = $pro_calendar_query->have_posts();
		wp_reset_postdata();
	}

	if (!$has_published_pro_calendar) {
		$pro_calendar_query = new \WP_Query(
			array_merge($pro_query_base, [
				'meta_query' => [
					'relation' => 'OR',
					[
						'key' => '_feed_type',
						'value' => 'google-pro',
						'compare' => '=',
					],
					[
						'key' => '_feed_type',
						'value' => 'google_pro',
						'compare' => '=',
					],
				],
			]),
		);
		$has_published_pro_calendar = $pro_calendar_query->have_posts();
		wp_reset_postdata();
	}

	$calendar_query = new \WP_Query([
		'post_type' => 'calendar',
		'post_status' => 'publish',
		'posts_per_page' => 1,
		'fields' => 'ids',
	]);
	$has_published_calendar = $calendar_query->have_posts();
	wp_reset_postdata();

	$completed_timestamp = (int) get_option('simple-calendar_connect_setup_completed_at', 0);
	$core_setup_complete = !$is_pro_active && $has_core_api_key_verified && $has_published_calendar;
	if ($core_setup_complete && $completed_timestamp <= 0) {
		$completed_timestamp = time();
		update_option('simple-calendar_connect_setup_completed_at', $completed_timestamp);
	}
	if (!$is_pro_active && !$core_setup_complete && $completed_timestamp > 0) {
		delete_option('simple-calendar_connect_setup_completed_at');
		$completed_timestamp = 0;
	}
	$hide_progress_after = DAY_IN_SECONDS;
	$should_hide_progress =
		$core_setup_complete && $completed_timestamp > 0 && time() - $completed_timestamp >= $hide_progress_after;

	$is_pro_flow = $is_pro_active;

	if ($is_pro_flow) {
		$pro_onboarding_complete = (bool) $has_published_pro_calendar;

		$pro_completed_timestamp = (int) get_option('simple-calendar_connect_pro_setup_completed_at', 0);
		if ($pro_onboarding_complete && $pro_completed_timestamp <= 0) {
			$pro_completed_timestamp = time();
			update_option('simple-calendar_connect_pro_setup_completed_at', $pro_completed_timestamp, false);
		}

		if (
			$pro_onboarding_complete &&
			$pro_completed_timestamp > 0 &&
			time() - $pro_completed_timestamp >= $hide_progress_after
		) {
			$should_hide_progress = true;
		} else {
			$should_hide_progress = false;
		}
	}

	$cached_scope = [
		'welcome_context' => $welcome_context,
		'is_pro_active' => $is_pro_active,
		'is_pro_flow' => $is_pro_flow,
		'api_key' => $api_key,
		'has_api_key' => $has_api_key,
		'has_core_api_key_verified' => $has_core_api_key_verified,
		'has_oauth_connection' => $has_oauth_connection,
		'has_client_credentials' => $has_client_credentials,
		'has_published_pro_calendar' => $has_published_pro_calendar,
		'has_published_calendar' => $has_published_calendar,
		'should_hide_progress' => $should_hide_progress,
		'assets_base' => SIMPLE_CALENDAR_ASSETS . 'images/admin/',
	];

	return $cached_scope;
}

/**
 * Whether Core Connect already has credentials configured.
 *
 * @since 4.0.0
 *
 * @return bool
 */
function simcal_has_existing_core_connect_configuration()
{
	if ((int) get_option('simple-calendar_connect_setup_completed_at', 0) > 0) {
		return true;
	}

	$feeds = get_option('simple-calendar_settings_feeds', []);
	$api_key = '';
	if (is_array($feeds) && isset($feeds['google']) && is_array($feeds['google'])) {
		$api_key = trim((string) ($feeds['google']['api_key'] ?? ''));
	}

	if ('' !== $api_key) {
		return true;
	}

	return false;
}

/**
 * Whether Pro Connect already has credentials or OAuth via Simple Calendar configured.
 *
 * @since 4.0.0
 *
 * @return bool
 */
function simcal_has_existing_pro_connect_configuration()
{
	if ('1' === (string) get_option('simple_calendar_connect_pro_oauth_health_ok', '')) {
		return true;
	}

	if ('1' === (string) get_option('simple_calendar_connect_pro_own_oauth_health_ok', '')) {
		return true;
	}

	if ('' !== trim((string) get_option('simple_calendar_auth_site_token', ''))) {
		return true;
	}

	if ('' !== trim((string) get_option('simple-calendar_google-pro-token', ''))) {
		return true;
	}

	if ((int) get_option('simple-calendar_connect_pro_setup_completed_at', 0) > 0) {
		return true;
	}

	$feeds = get_option('simple-calendar_settings_feeds', []);
	$google_pro =
		is_array($feeds) && isset($feeds['google-pro']) && is_array($feeds['google-pro']) ? $feeds['google-pro'] : [];
	$client_id = trim((string) ($google_pro['client_id'] ?? ''));
	$client_secret = trim((string) ($google_pro['client_secret'] ?? ''));
	$client_auth = trim((string) ($google_pro['client_auth'] ?? ''));

	return '' !== $client_id || '' !== $client_secret || '' !== $client_auth;
}

/**
 * Dismiss the Connect welcome step when credentials/OAuth are already saved.
 *
 * @since 4.0.0
 *
 * @return void
 */
function simcal_maybe_dismiss_connect_welcome_if_already_configured()
{
	if (simcal_has_existing_core_connect_configuration()) {
		update_option('simple-calendar_connect_welcome_dismissed', 1, false);
	}

	if (simcal_is_google_calendar_pro_active('') && simcal_has_existing_pro_connect_configuration()) {
		update_option('simple-calendar_connect_welcome_dismissed_pro', 1, false);
	}

	if (
		function_exists('simcal_is_appointment_addon_active') &&
		simcal_is_appointment_addon_active() &&
		simcal_has_existing_pro_connect_configuration()
	) {
		update_option('simple-calendar_connect_welcome_dismissed_appointment', 1, false);
	}
}

/**
 * Default Pro Connect to "own credentials" when client ID/secret exist but Via SC is not verified.
 *
 * @since 4.0.0
 *
 * @return void
 */
function simcal_maybe_set_pro_own_credentials_connection_type()
{
	$pro_or_appointment_active =
		simcal_is_google_calendar_pro_active('') ||
		(function_exists('simcal_is_appointment_addon_active') && simcal_is_appointment_addon_active());

	if (!$pro_or_appointment_active) {
		return;
	}

	if ('1' === (string) get_option('simple_calendar_connect_pro_oauth_health_ok', '')) {
		update_option('simple_calendar_connect_pro_connection_type', 'via_sc', false);
		return;
	}

	if ('' !== trim((string) get_option('simple_calendar_auth_site_token', ''))) {
		update_option('simple_calendar_connect_pro_connection_type', 'via_sc', false);
		return;
	}

	if ('' !== trim((string) get_option('simple-calendar_google-pro-token', ''))) {
		update_option('simple_calendar_connect_pro_connection_type', 'own', false);
		return;
	}

	$feeds = get_option('simple-calendar_settings_feeds', []);
	$google_pro = isset($feeds['google-pro']) && is_array($feeds['google-pro']) ? $feeds['google-pro'] : [];
	$client_id = isset($google_pro['client_id']) ? trim((string) $google_pro['client_id']) : '';
	$client_secret = isset($google_pro['client_secret']) ? trim((string) $google_pro['client_secret']) : '';

	if ('' !== $client_id && '' !== $client_secret) {
		update_option('simple_calendar_connect_pro_connection_type', 'own', false);
	}
}

/**
 * Apply Connect defaults after core or an add-on is updated via the WordPress upgrader.
 *
 * Plugin updates do not fire `activated_plugin`. When core is updated alongside an active
 * Pro or Appointment add-on, or when either add-on is updated in place, persist Connect options.
 *
 * @since 4.0.0
 *
 * @param \WP_Upgrader $upgrader Upgrader instance.
 * @param array        $options  Upgrade context.
 *
 * @return void
 */
function simcal_apply_connect_defaults_on_plugin_update($upgrader, $options)
{
	unset($upgrader);

	if (
		!is_array($options) ||
		!isset($options['action'], $options['type']) ||
		'update' !== $options['action'] ||
		'plugin' !== $options['type'] ||
		empty($options['plugins']) ||
		!is_array($options['plugins'])
	) {
		return;
	}

	$core_basename = plugin_basename(SIMPLE_CALENDAR_MAIN_FILE);
	$pro_basename = 'simple-calendar-google-calendar-pro/simple-calendar-google-calendar-pro.php';
	$appointment_basename = 'simple-calendar-appointment/simple-calendar-appointment.php';
	$updated = array_map('strval', $options['plugins']);

	$core_updated = in_array($core_basename, $updated, true);
	$pro_updated = in_array($pro_basename, $updated, true);
	$appointment_updated = in_array($appointment_basename, $updated, true);

	if (!$core_updated && !$pro_updated && !$appointment_updated) {
		return;
	}

	$pro_active = simcal_is_google_calendar_pro_active('');
	$appointment_active = function_exists('simcal_is_appointment_addon_active') && simcal_is_appointment_addon_active();

	$should_apply = $core_updated || $pro_updated || $appointment_updated;

	if (!$should_apply) {
		return;
	}

	simcal_apply_connect_defaults_on_plugin_event();
}

/**
 * Apply Connect UI defaults after plugin activation or upgrade.
 *
 * @since 4.0.0
 *
 * @return void
 */
function simcal_apply_connect_defaults_on_plugin_event()
{
	simcal_maybe_dismiss_connect_welcome_if_already_configured();
	simcal_maybe_set_pro_own_credentials_connection_type();
}

/**
 * Get admin notices.
 *
 * @since  3.0.0
 *
 * @return array
 */
function simcal_get_admin_notices()
{
	$notices = new \SimpleCalendar\Admin\Notices();
	return $notices->get_notices();
}

/**
 * Delete admin notices.
 *
 * @since 3.0.0
 */
function simcal_delete_admin_notices()
{
	delete_option('simple-calendar_admin_notices');
}

/**
 * Print a shortcode tip.
 *
 * @since  3.0.0
 *
 * @param  int $post_id
 *
 * @return void
 */
function simcal_print_shortcode_tip($post_id)
{
	$browser = new \SimpleCalendar\Browser();
	if ($browser::PLATFORM_APPLE == $browser->getPlatform()) {
		$cmd = '&#8984;&#43;C';
	} else {
		$cmd = 'Ctrl&#43;C';
	}

	$shortcut = sprintf(__('Press %s to copy.', 'google-calendar-events'), $cmd);
	$shortcode = sprintf('[calendar id="%s"]', $post_id);

	echo "<input readonly='readonly' " .
		"class='simcal-shortcode simcal-calendar-shortcode simcal-shortcode-tip' " .
		"title='" .
		$shortcut .
		"' " .
		"onclick='this.select();' value='" .
		$shortcode .
		"' />";
}

/**
 * Google Analytics campaign URL.
 *
 * @since   3.0.0
 *
 * @param   string  $base_url   Plain URL to navigate to
 * @param   string  $campaign   GA "campaign" tracking value
 * @param   string  $content    GA "content" tracking value
 * @param   bool    $raw        Use esc_url_raw instead (default = false)
 *
 * @return  string  $url        Full Google Analytics campaign URL
 */
function simcal_ga_campaign_url($base_url, $campaign, $content, $raw = false)
{
	$campaign = sanitize_text_field($campaign);
	$content = sanitize_text_field($content);
	$url = esc_url(
		add_query_arg(
			[
				'utm_source' => 'inside-plugin',
				'utm_medium' => 'link',
				'utm_campaign' => $campaign, // i.e. 'core-plugin', 'gcal-pro'
				'utm_content' => $content, // i.e. 'sidebar-link', 'settings-link'
			],
			$base_url,
		),
	);

	if ($raw) {
		return esc_url_raw($url);
	}

	return esc_url($url);
}

/**
 * Newsletter signup form.
 *
 * @since  3.0.0
 *
 * @return void
 */
function simcal_newsletter_signup()
{
	if ($screen = simcal_is_admin_screen()) {

		global $current_user;
		wp_get_current_user();

		$name = $current_user->user_firstname ? $current_user->user_firstname : '';
		?>
		<div id="simcal-drip" class="<?php echo $screen; ?>">
			<div class="signup">
				<p>
					<?php _e(
     	"Enter your name and email and we'll send you a coupon code for <strong>20% off</strong> all Pro Add-on purchases.",
     	'google-calendar-events',
     ); ?>
				</p>

				<p>
					<label for="simcal-drip-field-email"><?php _e('Your Email', 'google-calendar-events'); ?></label><br />
					<input type="email"
					       id="simcal-drip-field-email"
					       name="fields[email]"
					       value="<?php echo $current_user->user_email; ?>" />
				</p>

				<p>
					<label for="simcal-drip-field-first_name"><?php _e('First Name', 'google-calendar-events'); ?></label><br />
					<input type="text"
					       id="simcal-drip-field-first_name"
					       name="fields[first_name]"
					       value="<?php echo $name; ?>" />
				</p>
				<p class="textright">
					<a href="#"
					   id="simcal-drip-signup"
					   class="button button-primary"><?php _e('Send me the coupon', 'google-calendar-events'); ?></a>
				</p>
				<div class="textright">
					<em><?php _e('No spam. Unsubscribe anytime.', 'google-calendar-events'); ?></em>
					<br/>
					<a href="<?php echo simcal_ga_campaign_url(simcal_get_url('addons'), 'core-plugin', 'sidebar-link'); ?>"
					   target="_blank"><?php _e('Just take me the add-ons', 'google-calendar-events'); ?></a>
				</div>
			</div>
			<div class="thank-you" style="display: none;">
				<?php _e('Thank you!', 'google-calendar-events'); ?>
			</div>
			<div class="clear">
			</div>
		</div>
		<?php
	}
}

/**
 * Upgrade to Premium Add-ons HTML.
 *
 * @since  3.1.6
 *
 * @return void
 */
function simcal_upgrade_to_premium()
{
	if ($screen = simcal_is_admin_screen()) { ?>
		<div class="main">
			<p class="heading centered">
				<?php _e('Some of the features included with our premium add-ons', 'google-calendar-events'); ?>
			</p>

			<ul>
				<li><div class="dashicons dashicons-yes"></div> <?php _e(
    	'Display color coded events',
    	'google-calendar-events',
    ); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e('Show week & day views', 'google-calendar-events'); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e('Fast view switching', 'google-calendar-events'); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e(
    	'Event titles & start times in grid',
    	'google-calendar-events',
    ); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e('Limit event display times', 'google-calendar-events'); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e(
    	'Display private calendar events',
    	'google-calendar-events',
    ); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e(
    	'Show attendees & RSVP status',
    	'google-calendar-events',
    ); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e('Display attachments', 'google-calendar-events'); ?></li>
				<li><div class="dashicons dashicons-yes"></div> <?php _e('Priority email support', 'google-calendar-events'); ?></li>
			</ul>

			<div class="centered">
				<a href="<?php echo simcal_ga_campaign_url(simcal_get_url('addons'), 'core-plugin', 'sidebar-link'); ?>"
				   class="button-primary button-large" target="_blank">
					<?php _e('Upgrade to Premium Now', 'google-calendar-events'); ?></a>
			</div>
		</div>
		<?php }
}
/**
 * Rating
 *
 * @since  3.1.42
 *
 *
 */
function sc_rating()
{
	?>
		<div class='simcal-flex simcal-flex-row simcal-justify-center simcal-gap-3'>
			<?php for ($i = 0; $i < 5; $i++) {
   	svgfillstar();
   } ?>
		</div>
	<?php
}

/**
 * Notice to uprade the PHP version if version is less then 8.1.
 * This function can be remove after update the minimum PHP version to 8.1.
 * @since  3.5.1
 *
 * @return void
 */
function simcal_notice_to_update_php_version()
{
	$notices = get_option('simple-calendar_admin_notices', []);

	$notice_id = 'simcal_check_site_php_version';
	$requirements = 8.0;

	if (version_compare(PHP_VERSION, $requirements, '<')) {
		/*
		 * Notice for not providing support for PHP7
		 */
		$update_pro_notice = new Notice([
			'id' => [
				$notice_id => 'discontinuing_support_for_php7',
			],
			'type' => 'error',
			'dismissable' => true,
			'content' =>
				'<p>' .
				'<i class="simcal-icon-calendar-logo"></i> ' .
				__(
					'<strong>Attention!</strong><br /> On <strong>November 15, 2025</strong>, we will be updating our plugin to the latest Google libraries and discontinuing support for PHP 7.x.
					To ensure your calendar plugin continues to work without interruption, please upgrade your PHP version to 8.0 or higher. If you\'ve already upgraded, you\'re all set!',
					'google-calendar-events',
				) .
				'</p>',
		]);

		$update_pro_notice->add();
	} elseif (is_array($notices)) {
		unset($notices[$notice_id]);
		update_option('simple-calendar_admin_notices', $notices);
	}
}
add_action('admin_init', 'simcal_notice_to_update_php_version');
