<?php
/**
 * General purpose helpers
 *
 * @copyright 2019-present Creative Themes
 * @license   http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @package Blocksy
 */

function blocksy_assert_args($args, $fields = []) {
	foreach ($fields as $single_field) {
		if (
			! isset($args[$single_field])
			||
			!$args[$single_field]
		) {
			throw new Error($single_field . ' missing in args!');
		}
	}
}

function blocksy_sync_whole_page($args = []) {
	$args = wp_parse_args(
		$args,
		[
			'prefix_custom' => ''
		]
	);

	$selector = 'main#main';

	return array_merge(
		[
			'selector' => $selector,
			'container_inclusive' => true,
			'render' => function () {
				echo blocksy_replace_current_template();
			}
		],
		$args
	);
}

function blocksy_get_with_percentage( $id, $value ) {
	$val = blocksy_get_theme_mod($id, $value);

	if (strpos($value, '%') !== false && is_numeric($val)) {
		$val .= '%';
	}

	return str_replace('%%', '%', $val);
}

/**
 * Link to menus editor for every empty menu.
 *
 * @param array  $args Menu args.
 */
if (! function_exists('blocksy_link_to_menu_editor')) {
	function blocksy_link_to_menu_editor($args) {
		if (! current_user_can('manage_options')) {
			return;
		}

		// see wp-includes/nav-menu-template.php for available arguments
		// phpcs:ignore WordPress.PHP.DontExtract.extract_extract
		extract($args);

		$output = '<a class="ct-create-menu" href="' . admin_url('nav-menus.php') . '" target="_blank">' . $before . __('You don\'t have a menu yet, please create one here &rarr;', 'blocksy') . $after . '</a>';

		if (! empty($container)) {
			$output = "<$container>$output</$container>";
		}

		if ($echo) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo wp_kses_post($output);
		}

		return $output;
	}
}

/**
 * Extract variable from a file.
 *
 * @param string $file_path path to file.
 * @param array  $_extract_variables variables to return.
 * @param array  $_set_variables variables to pass into the file.
 */
function blocksy_get_variables_from_file(
	$file_path,
	array $_extract_variables,
	array $_set_variables = array()
) {
	// phpcs:ignore WordPress.PHP.DontExtract.extract_extract
	extract($_set_variables, EXTR_REFS);
	unset($_set_variables);

	if (is_file($file_path)) {
		require $file_path;
	}

	foreach ($_extract_variables as $variable_name => $default_value) {
		if (isset($$variable_name) ) {
			$_extract_variables[$variable_name] = $$variable_name;
		}
	}

	return $_extract_variables;
}

/**
 * Extract a key from an array with defaults.
 *
 * @param string       $keys 'a/b/c' path.
 * @param array|object $array_or_object array to extract from.
 * @param null|mixed   $default_value defualt value.
 *
 * Keep function_exists() check for some time because Blocksy Companion 1.9
 * framework/helpers/blocksy-integration.php declares it again.
 */
if (! function_exists('blocksy_default_akg')) {
	function blocksy_default_akg($keys, $array_or_object, $default_value) {
		return blocksy_akg($keys, $array_or_object, $default_value);
	}
}

/**
 * Recursively find a key's value in array
 *
 * @param string       $keys 'a/b/c' path.
 * @param array|object $array_or_object array to extract from.
 * @param null|mixed   $default_value defualt value.
 *
 * @return null|mixed
 */
if (! function_exists('blocksy_akg')) {
	function blocksy_akg($keys, $array_or_object, $default_value = null) {
		if (! is_array($keys)) {
			$keys = explode('/', (string) $keys);
		}

		$array_or_object = $array_or_object;
		$key_or_property = array_shift($keys);

		if (is_null($key_or_property)) {
			return $default_value;
		}

		$is_object = is_object($array_or_object);

		if ($is_object) {
			if (! property_exists($array_or_object, $key_or_property)) {
				return $default_value;
			}
		} else {
			if (! is_array($array_or_object) || ! array_key_exists($key_or_property, $array_or_object)) {
				return $default_value;
			}
		}

		if (isset($keys[0])) { // not used count() for performance reasons.
			if ($is_object) {
				return blocksy_akg($keys, $array_or_object->{$key_or_property}, $default_value);
			} else {
				return blocksy_akg($keys, $array_or_object[$key_or_property], $default_value);
			}
		} else {
			if ($is_object) {
				return $array_or_object->{$key_or_property};
			} else {
				return $array_or_object[ $key_or_property ];
			}
		}
	}
}

function blocksy_akg_or_customizer($key, $source, $default = null) {
	$source = wp_parse_args(
		$source,
		[
			'prefix' => '',

			// customizer | array
			'strategy' => 'customizer',
		]
	);

	if ($source['strategy'] !== 'customizer' && !is_array($source['strategy'])) {
		throw new Error(
			'strategy wrong value provided. Array or customizer is required.'
		);
	}

	if (! empty($source['prefix'])) {
		$source['prefix'] .= '_';
	}

	if ($source['strategy'] === 'customizer') {
		return blocksy_get_theme_mod($source['prefix'] . $key, $default);
	}

	return blocksy_akg($source['prefix'] . $key, $source['strategy'], $default);
}

/**
 * Generate a random ID.
 *
 * Keep function_exists() check for some time because Blocksy Companion 1.9
 * framework/helpers/blocksy-integration.php declares it again.
 */
if (! function_exists('blocksy_rand_md5')) {
	function blocksy_rand_md5() {
		return md5(time() . '-' . uniqid(wp_rand(), true) . '-' . wp_rand());
	}
}

/**
 * Safe render a view and return html
 * In view will be accessible only passed variables
 * Use this function to not include files directly and to not give access to current context variables (like $this)
 *
 * @param string $file_path File path.
 * @param array  $view_variables Variables to pass into the view.
 *
 * @return string HTML.
 */
if (! function_exists('blocksy_render_view')) {
	function blocksy_render_view(
		$file_path,
		$view_variables = [],
		$default_value = ''
	) {
		if (! is_file($file_path)) {
			return $default_value;
		}

		// phpcs:ignore WordPress.PHP.DontExtract.extract_extract
		extract($view_variables, EXTR_REFS);
		unset($view_variables);

		ob_start();
		require $file_path;

		return ob_get_clean();
	}
}

function blocksy_get_wp_theme() {
	return apply_filters('blocksy_get_wp_theme', wp_get_theme());
}

if (! function_exists('blocksy_get_wp_parent_theme')) {
	function blocksy_get_wp_parent_theme() {
		return apply_filters('blocksy_get_wp_theme', wp_get_theme(get_template()));
	}
}

function blocksy_current_url() {
	static $url = null;

	if ($url === null) {
		if (is_multisite() && !(defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL)) {
			switch_to_blog(1);
			$url = home_url();
			restore_current_blog();
		} else {
			$url = home_url();
		}

		//Remove the "//" before the domain name
		$url = ltrim(preg_replace('/^[^:]+:\/\//', '//', $url), '/');

		//Remove the ulr subdirectory in case it has one
		$split = explode('/', $url);

		//Remove end slash
		$url = rtrim($split[0], '/');

		$url .= '/' . ltrim(blocksy_akg('REQUEST_URI', $_SERVER, ''), '/');
		$url = set_url_scheme('//' . $url); // https fix
	}

	return $url;
}

if (! function_exists('blocksy_get_all_image_sizes')) {
	function blocksy_get_all_image_sizes() {
		$titles = [
			'thumbnail' => __('Thumbnail', 'blocksy'),
			'medium' => __('Medium', 'blocksy'),
			'medium_large' => __('Medium Large', 'blocksy'),
			'large' => __('Large', 'blocksy'),
			'full' => __('Full Size', 'blocksy'),
			'woocommerce_thumbnail' => __('WooCommerce Thumbnail', 'blocksy'),
			'woocommerce_single' => __('WooCommerce Single', 'blocksy'),
			'woocommerce_gallery_thumbnail' => __(
				'WooCommerce Gallery Thumbnail',
				'blocksy'
			),
			'woocommerce_archive_thumbnail' => __(
				'WooCommerce Archive Thumbnail',
				'blocksy'
			)
		];

		$all_sizes = get_intermediate_image_sizes();

		$result = [
			'full' => __('Full Size', 'blocksy')
		];

		foreach ($all_sizes as $single_size) {
			if (isset($titles[$single_size])) {
				$result[$single_size] = $titles[$single_size];
			} else {
				$result[$single_size] = $single_size;
			}
		}

		return $result;
	}
}

if (! function_exists('blocksy_debug')) {
	function blocksy_debug_log($message, $object = null) {
		if (
			! defined('WP_DEBUG')
			||
			! WP_DEBUG
		) {
			return;
		}

		if (is_null($object)) {
			error_log($message);
		} else {
			error_log($message . ': ' . print_r($object, true));
		}
	}
}

// Deprecated.
//
// This function is no longer needed. Use StringHelpers class instead.
// Keeping it for few more releases to avoid updates crashes.
//
// Ref: https://php.watch/versions/8.2/utf8_encode-utf8_decode-deprecated
//
// To be removed in March 2024.
function blocksy_utf8_decode($s) {
	$len = \strlen($s);

	for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
		switch ($s[$i] & "\xF0") {
		case "\xC0":
		case "\xD0":
			$c = (\ord($s[$i] & "\x1F") << 6) | \ord($s[++$i] & "\x3F");
			$s[$j] = $c < 256 ? \chr($c) : '?';
			break;

		case "\xF0":
			++$i;
			// no break

		case "\xE0":
			$s[$j] = '?';
			$i += 2;
			break;

		default:
			$s[$j] = $s[$i];
		}
	}

	return substr($s, 0, $j);
}

function blocksy_output_html_safely($html) {
	$html = do_shortcode($html);

	if (current_user_can('unfiltered_html')) {
		return $html;
	}

	// Just drop scripts from the html content, if user doesnt have
	// unfiltered_html capability.
	return preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

	// Dont use wp_filter_post_kses() as it is very unstable as far as slashes go.
	// Just call wp_kses() directly.
	//
	// Context:
	//
	// https://github.com/WP-API/WP-API/issues/2848
	// https://github.com/WP-API/WP-API/issues/2788
	// https://core.trac.wordpress.org/ticket/38609
	// return wp_kses($html, 'post');
}

