<?php

/**
 * Init
 *
 * @package Dotspice
 * @version 1.3.0
 */


/**
 * Autoload files in the directory
 *
 * @param string $path
 */
function dotspice_autoload_files($path, $pattern = false)
{
	global $wp_filesystem;

	if (empty($wp_filesystem)) {
		load_template(ABSPATH . '/wp-admin/includes/file.php', true);
		WP_Filesystem();
	}

	if ($wp_filesystem->is_dir($path)) {
		$dirlist = $wp_filesystem->dirlist($path);
	} else {
		return false;
	}

	// loop folders
	foreach ($dirlist as $list_item) {
		$file = $list_item['name'];
		$path_file = $path . "/" . basename($file);

		if ($pattern && !preg_match("/$pattern/", basename($file))) {
			continue;
		}

		if (file_exists($path_file) && $file != "index.php") {

			if ($wp_filesystem->is_dir($path_file) && file_exists($path_file . "/$file.php")) {
				load_template($path_file . "/$file.php", true);
			} else if ($wp_filesystem->is_file($path_file) && preg_match("/\.php$/i", $path_file)) {
				load_template($path_file, true);
			}
		}
	}
}

dotspice_autoload_files(get_template_directory() . '/includes/core');
dotspice_autoload_files(get_template_directory() . '/includes/functions');
dotspice_autoload_files(get_template_directory() . '/includes/libraries');
dotspice_autoload_files(get_template_directory() . '/includes/modules');
dotspice_autoload_files(get_template_directory() . '/includes/settings');
dotspice_autoload_files(get_template_directory() . '/includes/widgets');
load_template(get_template_directory() . '/includes/shortcodes.php', true);


/**
 * Is value exists
 *
 * @param  mixed $value
 * @return boolean
 */
function dotspice_value_exists($value = '')
{

	if (!isset($value)) {
		return false;
	}

	if ((is_array($value)) && empty($value)) {
		return false;
	}

	if ((is_string($value) && !is_numeric($value)) && empty($value)) {
		return false;
	}

	return true;
}


/**
 * SSL | Compatibility
 *
 * @param  boolean $value
 * @return string
 */
function dotspice_theme_ssl($echo = false)
{
	$ssl = '';

	if (is_ssl()) {
		$ssl = 's';
	}
	if ($echo) {
		echo esc_attr($ssl);
	}

	return $ssl;
}


/**
 * HTML Minifier
 *
 * @param  string $input
 * @return string
 */
function dotspice_minify_html($input)
{
	if (trim($input) === "") {
		return $input;
	}
	$input = preg_replace_callback('#<([^\/\s<>!]+)(?:\s+([^<>]*?)\s*|\s*)(\/?)>#s', function ($matches) {
		return '<' . $matches[1] . preg_replace('#([^\s=]+)(\=([\'"]?)(.*?)\3)?(\s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>';
	}, str_replace("\r", "", $input));
	if (strpos($input, ' style=') !== false) {
		$input = preg_replace_callback('#<([^<]+?)\s+style=([\'"])(.*?)\2(?=[\/\s>])#s', function ($matches) {
			return '<' . $matches[1] . ' style=' . $matches[2] . dotspice_minify_css($matches[3]) . $matches[2];
		}, $input);
	}
	return preg_replace(
		array(
			// t = text
			// o = tag open
			// c = tag close
			// Keep important white-space(s) after self-closing HTML tag(s)
			'#<(img|input)(>| .*?>)#s',
			// Remove a line break and two or more white-space(s) between tag(s)
			'#(<!--.*?-->)|(>)(?:\n*|\s{2,})(<)|^\s*|\s*$#s',
			'#(<!--.*?-->)|(?<!\>)\s+(<\/.*?>)|(<[^\/]*?>)\s+(?!\<)#s', // t+c || o+t
			'#(<!--.*?-->)|(<[^\/]*?>)\s+(<[^\/]*?>)|(<\/.*?>)\s+(<\/.*?>)#s', // o+o || c+c
			'#(<!--.*?-->)|(<\/.*?>)\s+(\s)(?!\<)|(?<!\>)\s+(\s)(<[^\/]*?\/?>)|(<[^\/]*?\/?>)\s+(\s)(?!\<)#s', // c+t || t+o || o+t -- separated by long white-space(s)
			'#(<!--.*?-->)|(<[^\/]*?>)\s+(<\/.*?>)#s', // empty tag
			'#<(img|input)(>| .*?>)<\/\1>#s', // reset previous fix
			'#(&nbsp;)&nbsp;(?![<\s])#', // clean up ...
			'#(?<=\>)(&nbsp;)(?=\<)#', // --ibid
			// Remove HTML comment(s) except IE comment(s)
			'#\s*<!--(?!\[if\s).*?-->\s*|(?<!\>)\n+(?=\<[^!])#s'
		),
		array(
			'<$1$2</$1>',
			'$1$2$3',
			'$1$2$3',
			'$1$2$3$4$5',
			'$1$2$3$4$5$6$7',
			'$1$2$3',
			'<$1$2',
			'$1 ',
			'$1',
			""
		),
		$input
	);
}


/**
 * CSS Minifier
 *
 * @param  string $input
 * @return string
 */
function dotspice_minify_css($input)
{
	if (trim($input) === "") {
		return $input;
	}
	return preg_replace(
		array(
			// Remove comment(s)
			'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
			// Remove unused white-space(s)
			'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~+]|\s*+-(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
			// Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
			'#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
			// Replace `:0 0 0 0` with `:0`
			'#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
			// Replace `background-position:0` with `background-position:0 0`
			'#(background-position):0(?=[;\}])#si',
			// Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
			'#(?<=[\s:,\-])0+\.(\d+)#s',
			// Minify string value
			'#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
			'#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
			// Minify HEX color code
			'#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
			// Replace `(border|outline):none` with `(border|outline):0`
			'#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
			// Remove empty selector(s)
			'#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s',
			// Replace calc '-'' to ' - '
			'#(calc\()([^-|^+]*?)([-|\+])(.*?)(\))#',
		),
		array(
			'$1',
			'$1$2$3$4$5$6$7',
			'$1',
			':0',
			'$1:0 0',
			'.$1',
			'$1$3',
			'$1$2$4$5',
			'$1$2$3',
			'$1:0',
			'$1$2',
			'$1$2 $3 $4$5'
		),
		$input
	);
}


/**
 * JavaScript Minifier
 *
 * @param  string $input
 * @return string
 */
function dotspice_minify_js($input)
{
	if (trim($input) === "") {
		return $input;
	}
	return preg_replace(
		array(
			// Remove comment(s)
			'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
			// Remove white-space(s) outside the string and regex
			'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
			// Remove the last semicolon
			'#;+\}#',
			// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
			'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
			// --ibid. From `foo['bar']` to `foo.bar`
			'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
		),
		array(
			'$1',
			'$1$2',
			'}',
			'$1$3',
			'$1.$3'
		),
		$input
	);
}


/**
 * Convert Dashed
 *
 * @param  string $url
 * @param  array  $fields
 * @param  string $method
 * @return bool
 */
function dotspice_convert_dashes($string, $direction = 'up')
{
	if ($direction == 'up') {
		return str_replace('_', '-', (string) $string);
	} else {
		return str_replace('-', '_', (string) $string);
	}
}


/**
 * Prr
 */
function prr($data)
{
	echo "<pre>";
	var_dump($data);
	echo "</pre>";
}


/**
 * PRJ
 */
function prj($data)
{
	ob_start();
	var_dump($data);
	$var_dump = ob_get_contents();

	ob_end_clean();

	wp_add_inline_script('script', '(function($) { console.log(' . json_encode($var_dump) . '); })(jQuery);');
}


/**
 * Unique ID
 */
function dotspice_unique_ID($name = '', $change = true)
{
	switch ($name) {
		case 'accordion':
			static $accordion_key = 0;
			if ($change) {
				return ++$accordion_key;
			} else {
				return $accordion_key;
			}
			break;
		case 'slider':
			static $slider_key = 0;
			return ++$slider_key;
			break;
		default:
			static $theme_key = 0;
			return ++$theme_key;
			break;
	}
}


/**
 * Is Active Sidebar
 */
function dotspice_is_active_sidebar($index)
{
	$index             = (is_int($index)) ? "sidebar-$index" : strtolower(sanitize_title($index));
	$sidebars_widgets  = wp_get_sidebars_widgets();
	$is_active_sidebar = false;

	foreach ($sidebars_widgets as $key => $value) {
		if ($index == strtolower($key)) {
			if (is_array($value) && count($value) > 0) {
				$is_active_sidebar = true;
			}
		}
	}

	return $is_active_sidebar;
}


/**
 * Is Live Sidebar
 */
function dotspice_is_live_sidebar($sidebar_name)
{
	global $wp_registered_sidebars;
	$live = false;

	if (is_array($sidebar_name)) {
		foreach ($sidebar_name as $sidebar) {
			if (array_key_exists($sidebar, $wp_registered_sidebars) && dotspice_is_active_sidebar($sidebar)) {
				$live = true;
			}
		}
	} else {
		if (array_key_exists($sidebar_name, $wp_registered_sidebars) && dotspice_is_active_sidebar($sidebar_name)) {
			$live = true;
		}
	}

	return $live;
}


/**
 * Has Shortcode
 */
function dotspice_has_shortcode($shortcode)
{
	global $post;

	$has_shortcode = false;

	if (isset($post->post_content) && has_shortcode($post->post_content, $shortcode)) {
		$has_shortcode = true;
	}

	return $has_shortcode;
}


/**
 * Enqueue Dynamic Styles
 */
function dotspice_enqueue_dynamic_styles($path_files)
{
	global $wp_filesystem;

	$path_files = array(
		get_template_directory() . '/includes/dynamic-styles.php' => 'style'
	);

	foreach ($path_files as $path_file => $handle) {

		if (!is_string($handle)) {
			continue;
		}

		if ($wp_filesystem->exists($path_file)) {
			ob_start();
			load_template($path_file, true);
			$dynamic_styles = ob_get_clean();

			if (function_exists('dotspice_minify_css')) {
				$dynamic_styles = dotspice_minify_css($dynamic_styles);
			}

			wp_add_inline_style($handle, $dynamic_styles);
		}
	}
}
add_action('wp_enqueue_scripts', 'dotspice_enqueue_dynamic_styles', 1000);


/**
 * Kses Allowed HTML
 */
function dotspice_kses_allowed_html($tags, $context)
{
	$theme_tags = array(
		'a' => array(
			'class'  => array(),
			'href'   => array(),
			'rel'    => array(),
			'title'  => array(),
			'target' => array(),
		),
		'abbr' => array(
			'title' => array(),
		),
		'b' => array(),
		'blockquote' => array(
			'cite'  => array(),
		),
		'cite' => array(
			'title' => array(),
		),
		'code' => array(),
		'del' => array(
			'datetime' => array(),
			'title'    => array(),
		),
		'option' => array(
			'value'    => array(),
			'selected' => array(),
		),
		'dd' => array(),
		'div' => array(
			'class' => array(),
			'title' => array(),
			'style' => array(),
		),
		'dl'  => array(),
		'dt'  => array(),
		'em'  => array(),
		'h1'  => array(),
		'h2'  => array(),
		'h3'  => array(),
		'h4'  => array(),
		'h5'  => array(),
		'h6'  => array(),
		'i'   => array(
			'class' => array()
		),
		'img' => array(
			'alt'         => array(),
			'class'       => array(),
			'height'      => array(),
			'src'         => array(),
			'width'       => array(),
			'data-retina' => array(),
			'data-defaul' => array(),
		),
		'ul' => array(
			'class' => array(),
		),
		'ol' => array(
			'class' => array(),
		),
		'li' => array(
			'class' => array(),
		),
		'p' => array(
			'class' => array(),
		),
		'q' => array(
			'cite'  => array(),
			'title' => array(),
		),
		'span' => array(
			'class' => array(),
			'title' => array(),
			'style' => array(),
		),
		'strike' => array(),
		'strong' => array(),
		'sup'    => array(),
		'br'     => array()
	);

	$svg_tags = array(
		'svg' => array(
			'class'               => array(),
			'width'               => array(),
			'height'              => array(),
			'viewbox'             => array(),
			'preserveaspectratio' => array(),
			'aria-hidden'         => array(),
			'version'             => array(),
			'xmlns'               => array(),
			'fill'                => array(),
			'stroke'              => array(),
			'stroke-width'        => array(),
		),
		'g' => array(
			'fill' => array(),
		),
		'title' => array(
			'title' => array(),
		),
		'path' => array(
			'id'            => array(),
			'd'             => array(),
			'class'         => array(),
			'hover-d'       => array(),
			'fill'          => array(),
			'fill-opacity'  => array(),
			'vector-effect' => array(),
		),
		'clipPath' => array(
			'class'         => array(),
			'id'            => array(),
			'clippathunits' => array(),
		),
		'lineargradient' => array(
			'id' => array(),
			'x2' => array(),
			'y2' => array(),
		),
		'stop' => array(
			'offset' => array(),
		),
		'rect' => array(
			'x'         => array(),
			'y'         => array(),
			'fill'      => array(),
			'width'     => array(),
			'class'     => array(),
			'height'    => array(),
			'transform' => array(),
		),
		'use' => array(
			'x'         => array(),
			'y'         => array(),
			'width'     => array(),
			'height'    => array(),
			'class'     => array(),
			'href'      => array(),
			'transform' => array(),
		),
		'switch' => array(),
		'defs'   => array(),
	);

	switch ($context) {
		case 'dotspice-tags':
			return $theme_tags;
		case 'dotspice-svg':
			return array_merge($theme_tags, $svg_tags);

		default:
			return $tags;
	}
}
add_filter('wp_kses_allowed_html', 'dotspice_kses_allowed_html', 10, 2);


/**
 * Register Custom Post Type
 */
/*
function dotspice_post_types( $post_types ){
	$post_types[] = array(
		'post_type'          => 'tlumacze',
		'menu_name'          => esc_html__( 'Tłumacze', 'dotspice' ),
		'singular_name'      => esc_html__( 'Tłumacz', 'dotspice' ),
		'multiple_name'      => esc_html__( 'Tłumacze', 'dotspice' ),
		'menu_icon'          => 'dashicons-admin-post',
		'menu_position'      => 5,
	);

	return $post_types;
}
add_filter( 'dotspice_cpt', 'dotspice_post_types' );
*/
function dotspice_register_cpt()
{
	$all_post_types = apply_filters('dotspice_cpt', array());

	if (!empty($all_post_types)) {
		foreach ($all_post_types as $args) {
			$default_settings = array(
				'labels'             => array(
					'name'           => _x($args['menu_name'], 'post type general name', 'dotspice'),
					'singular_name'  => _x($args['singular_name'], 'post type singular name', 'dotspice'),
					'menu_name'      => _x($args['menu_name'], 'admin menu', 'dotspice'),
					'name_admin_bar' => _x($args['singular_name'], 'add new on admin bar', 'dotspice'),
					'all_items'      => $args['multiple_name'],
				),
				'public'             => true,
				'publicly_queryable' => true,
				'exclude_from_search' => false,
				'show_ui'            => true,
				'show_in_menu'       => true, // 'theme-settings',
				'query_var'          => true,
				'supports'           => array('title', 'editor', 'thumbnail'),
				'rewrite'            => array(),
				'has_archive'        => true
			);

			$post_type_args = array_merge($default_settings, $args);

			unset($post_type_args['post_type']);

			register_post_type($args['post_type'], $post_type_args);

			if (update_option('dotspice_cpt_' . $args['post_type'], true)) {
				flush_rewrite_rules();
			}
		}
	}
}
add_action('init', 'dotspice_register_cpt');


/**
 * Register Custom Taxonomies
 */
/*
function dotspice_taxonomies( $taxonomies ){
	$taxonomies[] = array(
		'tax_slug'      => 'tlumacze_lang',
		'for_types'     => array( 'tlumacze' ),
		'menu_name'     => esc_html__( 'Języki', 'dotspice' ),
		'singular_name' => esc_html__( 'Język', 'dotspice' ),
		'multiple_name' => esc_html__( 'Języki', 'dotspice' ),
	);

	return $taxonomies;
}
add_filter( 'dotspice_tax', 'dotspice_taxonomies' );
*/
function dotspice_register_taxonomies()
{
	$all_taxonomies = apply_filters('dotspice_tax', array());

	if (!empty($all_taxonomies)) {
		foreach ($all_taxonomies as $args) {
			$default_settings = array(
				'labels'            => array(
					'name'          => _x($args['menu_name'], 'taxonomy general name', 'dotspice'),
					'menu_name'     => __($args['menu_name'], 'dotspice'),
					'singular_name' => _x($args['singular_name'], 'taxonomy singular name', 'dotspice'),
					'all_items'     => $args['multiple_name'],
				),
				'hierarchical'      => true,
				'show_ui'           => true,
				'show_admin_column' => true,
				'query_var'         => true,
				'rewrite'           => array('slug' => $args['tax_slug'])
			);

			$tax_args = array_merge($default_settings, $args);

			register_taxonomy($args['tax_slug'], $args['for_types'], $tax_args);
		}
	}
}
add_action('init', 'dotspice_register_taxonomies');
