<?php
/**
 * aniro-hotel-light functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package aniro-hotel-light
 */

if (!function_exists('anirohotellight_setup')):
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function anirohotellight_setup() {
	/*
	 * Make theme available for translation.
	 * Translations can be filed in the /languages/ directory.
	 * If you're building a theme based on anirohotellight, use a find and replace
	 * to change 'aniro-hotel-light' to the name of your theme in all the template files.
	 */
	load_theme_textdomain('aniro-hotel-light', get_template_directory().'/languages');
	// This theme styles the visual editor to resemble the theme style.
	//add_editor_style( array( 'inc/editor-style.css', anirohotellight_fonts_url() ) );
	// Add default posts and comments RSS feed links to head.
	add_theme_support('automatic-feed-links');

	/*
	 * Let WordPress manage the document title.
	 * By adding theme support, we declare that this theme does not use a
	 * hard-coded <title> tag in the document head, and expect WordPress to
	 * provide it for us.
	 */
	add_theme_support('title-tag');

	/*
	 * Enable support for Post Thumbnails on posts and pages.
	 *
	 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
	 */
	add_theme_support('post-thumbnails');
	add_image_size('anirohotellight-mainslider-thumb', 600, 450, true);
	add_image_size('anirohotellight-thumb', 440, 440, true);

	// Add other useful image sizes for use through Add Media modal
	add_image_size('customlarge', 1040, 600, true);

	// Register the three useful image sizes for use in Add Media modal
	add_filter('image_size_names_choose', 'anirohotellight_wpshout_custom_sizes');
	function anirohotellight_wpshout_custom_sizes($sizes) {
		return array_merge($sizes, array(
				'customlarge' => esc_html__('Custom Large 1040x600', 'aniro-hotel-light'),
			));
	}

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus(array(
			'menu-1' => esc_html__('Primary', 'aniro-hotel-light'),
		));

	/*
	 * Switch default core markup for search form, comment form, and comments
	 * to output valid HTML5.
	 */
	add_theme_support('html5', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		));

	// Add theme support for selective refresh for widgets.
	add_theme_support('customize-selective-refresh-widgets');

	// Add support for Block Styles.
	add_theme_support('wp-block-styles');

	// Add support for full and wide align images.
	add_theme_support('align-wide');

	// Add support for editor styles.
	add_theme_support('editor-styles');

	// Enqueue editor styles.
	add_editor_style('inc/editor-style.css');

	// Add custom editor font sizes.
	add_theme_support(
		'editor-font-sizes',
		array(
			array(
				'name'      => __('Small', 'aniro-hotel-light'),
				'shortName' => __('S', 'aniro-hotel-light'),
				'size'      => 12,
				'slug'      => 'small',
			),
			array(
				'name'      => __('Normal', 'aniro-hotel-light'),
				'shortName' => __('N', 'aniro-hotel-light'),
				'size'      => 16,
				'slug'      => 'normal',
			),
			array(
				'name'      => __('Large', 'aniro-hotel-light'),
				'shortName' => __('L', 'aniro-hotel-light'),
				'size'      => 32,
				'slug'      => 'large',
			),
			array(
				'name'      => __('Huge', 'aniro-hotel-light'),
				'shortName' => __('XL', 'aniro-hotel-light'),
				'size'      => 48,
				'slug'      => 'huge',
			),
		)
	);

	// Editor color palette.
	add_theme_support('editor-color-palette', array(
			array(
				'name'  => __('Main color', 'aniro-hotel-light'),
				'slug'  => 'main-color',
				'color' => ' #d2691e ',
			),
			array(
				'name'  => __('White color', 'aniro-hotel-light'),
				'slug'  => 'white-color',
				'color' => ' #fff ',
			),
		));
	// Disables custom colors in block color palette.
	add_theme_support('disable-custom-colors');
	// Add support for responsive embedded content.
	add_theme_support('responsive-embeds');

}
endif;
add_action('after_setup_theme', 'anirohotellight_setup');

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function anirohotellight_content_width() {
	$GLOBALS['content_width'] = apply_filters('anirohotellight_content_width', 640);
}
add_action('after_setup_theme', 'anirohotellight_content_width', 0);

/**
 *anirohotellight default options
 */
function anirohotellight_default_options() {
	$default_options = anirohotellight_default_theme_options();

	foreach ($default_options as $key => $value) {
		if (!esc_html(get_theme_mod($key))) {
			set_theme_mod($key, $value);
		}
	}

}
add_action('after_setup_theme', 'anirohotellight_default_options');

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function anirohotellight_widgets_init() {
	//Sidebar
	register_sidebar(array(
			'name'          => esc_html__('Sidebar', 'aniro-hotel-light'),
			'id'            => 'sidebar-widgets',
			'description'   => esc_html__('Add widgets here.', 'aniro-hotel-light'),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>'
		));

	//Sidedar for place widget 'anirohotellight: Contact info' on contact page
	register_sidebar(array(
			'name'          => esc_html__('Contact Page Widget', 'aniro-hotel-light'),
			'id'            => 'contact-widgets',
			'description'   => esc_html__('Contact Page Widget area appears in the contact page.', 'aniro-hotel-light'),
			'before_widget' => '<aside id="%1$s" class="widget %2$s">',
			'after_widget'  => '</aside>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		));

	//Footer full width widget
	register_sidebar(array(
			'name'          => esc_html__('Footer full width Widgets', 'aniro-hotel-light'),
			'id'            => 'footer-full-widgets',
			'description'   => esc_html__('Footer widgets area for widgets "WP Instagram Widget" and "MailChimp for WordPress".', 'aniro-hotel-light'),
			'before_widget' => '<aside id="%1$s" class="widget %2$s">',
			'after_widget'  => '</aside>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		));
	//Footer sidebar
	register_sidebar(array(
			'name'          => esc_html__('Footer Widgets', 'aniro-hotel-light'),
			'id'            => 'footer-widgets',
			'description'   => esc_html__('Footer widgets area appears in the footer of the site.', 'aniro-hotel-light'),
			'before_widget' => '<aside id="%1$s" class="widget %2$s">',
			'after_widget'  => '</aside>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		));
}
add_action('widgets_init', 'anirohotellight_widgets_init');

/**
 * Create the required Google Fonts for Aniro Hotel.
 */

if (!function_exists('anirohotellight_fonts_url')) {

	function anirohotellight_fonts_url($font) {
		$fonts_url = '';
		/*
		Translators: If there are characters in your language that are not supported
		by chosen font(s), translate this to 'off'. Do not translate into your own language.
		 */
		$google_fonts_array = anirohotellight_google_fonts_array();
		if ('off' !== _x('on', 'Google font: on or off', 'aniro-hotel-light')) {
			foreach ($google_fonts_array as $key => $value) {
				if ($font === $key) {
					$fonts_url = add_query_arg('family', $value, "https://fonts.googleapis.com/css");
				}
			}
		}

		return esc_url_raw($fonts_url);
	}

}// Endif function_exists()

/**
 * Enqueue scripts and styles.
 */
function anirohotellight_scripts() {
	wp_enqueue_style('anirohotellight-style', get_stylesheet_uri());

	//Add style for magnific-popup
	wp_enqueue_style('magnific-popup-style', get_template_directory_uri().'/css/magnific-popup.css', array(), '1.0.0', 'all');

	//Add style for animate css
	wp_enqueue_style('animate-style', get_template_directory_uri().'/css/animate.min.css', array(), '1.0.0', 'all');
	//Add style for slick slider
	wp_enqueue_style('slick-style', get_template_directory_uri().'/css/slick/slick.css', array(), '1.8.0', 'all');

	// Add Google fonts
	$google_fonts_array = anirohotellight_google_fonts_array();

	foreach ($google_fonts_array as $key => $value) {
		if (get_theme_mod('anirohotellight_google_font_setting_body') === $key) {
			wp_enqueue_style('anirohotellight-google-font-body', anirohotellight_fonts_url($key), array(), null);
		}
		if (get_theme_mod('anirohotellight_google_font_setting_header') === $key) {
			wp_enqueue_style('anirohotellight-google-font-header', anirohotellight_fonts_url($key), array(), null);
		}
	}
	// Add FontAwesome
	wp_enqueue_style('fontawesome', get_template_directory_uri().'/fonts/css/all.min.css', array(), '5.9.0', 'all');

	wp_enqueue_script('anirohotellight-navigation', get_template_directory_uri().'/js/navigation.js', array('jquery'), '20160206', true);
	wp_localize_script('anirohotellight-navigation', 'screenReaderText', array(
			'expand'   => '<span class="screen-reader-text">'.__('expand child menu', 'aniro-hotel-light').'</span>',
			'collapse' => '<span class="screen-reader-text">'.__('collapse child menu', 'aniro-hotel-light').'</span>',
		));

	wp_enqueue_script('enquire', get_template_directory_uri().'/js/enquire.min.js', array(), '2.1.2', true);
	//Masonry
	wp_enqueue_script('masonry');
	wp_enqueue_script('masonry-settings', get_template_directory_uri().'/js/masonry-settings.js', array('masonry', 'enquire'), '20170428', true);

	wp_enqueue_script('anirohotellight-skip-link-focus-fix', get_template_directory_uri().'/js/skip-link-focus-fix.js', array(), '20151215', true);
	//Add magnific-popup
	wp_enqueue_script('magnific-popup', get_template_directory_uri().'/js/jquery.magnific-popup.min.js', array(), '1.0.0', true);

	//Add wow js
	wp_enqueue_script('wow', get_template_directory_uri().'/js/wow.min.js', array(), '1.0.0', true);
	//Add blazy
	wp_enqueue_script('blazy', get_template_directory_uri().'/js/blazy.min.js', array('jquery'), '1.0.0', true);
	//Add js for Slick
	wp_enqueue_script('slick', get_template_directory_uri().'/js/slick.min.js', array('jquery'), '2.2.0', true);

	//Retina
	wp_enqueue_script('retina_js', get_template_directory_uri().'/js/retina.min.js', array(), '1.2.0', true);
	wp_enqueue_script('anirohotellight-javascript', get_template_directory_uri().'/js/functions.js', array('jquery'), '20160217', true);

	if (is_singular() && comments_open() && get_option('thread_comments')) {
		wp_enqueue_script('comment-reply');
	}
}
add_action('wp_enqueue_scripts', 'anirohotellight_scripts');

/**
 * Implement the Custom Header feature.
 */
require get_template_directory().'/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory().'/inc/template-tags.php';

/**
 * Custom functions that act independently of the theme templates.
 */
require get_template_directory().'/inc/extras.php';
/**
 * Implement the custom functions for this theme.
 */
require get_template_directory().'/inc/inc-functions.php';

/**
 * Customize theme.
 */
require get_template_directory().'/inc/customize.php';

/**
 * Customizer additions.
 */
require get_template_directory().'/inc/customizer/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
require get_template_directory().'/inc/jetpack.php';

/**
 *  Widget tag cloud - make all letters one size.
 */
add_filter('widget_tag_cloud_args', 'anirohotellight_set_tag_cloud_args');
function anirohotellight_set_tag_cloud_args($args) {
	$args['number']   = 30;
	$args['largest']  = 1;
	$args['smallest'] = 1;
	$args['unit']     = 'em';
	return $args;
}
/**
 *  Widget categories - delete brackets.
 */
function anirohotellight_categories_postcount_filter($variable) {
	$variable = str_replace('(', '<span class="post_count"> ', $variable);
	$variable = str_replace(')', ' </span>', $variable);
	return $variable;
}
add_filter('wp_list_categories', 'anirohotellight_categories_postcount_filter');

/**
 *  Widget archive - delete brackets.
 */
function anirohotellight_archive_postcount_filter($variable) {
	$variable = str_replace('(', ' ', $variable);
	$variable = str_replace(')', ' ', $variable);
	return $variable;
}
add_filter('get_archives_link', 'anirohotellight_archive_postcount_filter');

/**
 * Add WordPress image uploader
 */
function anirohotellight_image_uploader() {

	if (!did_action('wp_enqueue_media')) {
		wp_enqueue_media();
	}
	wp_enqueue_script('anirohotellight_image_uploader_script', get_stylesheet_directory_uri().'/js/anirohotellight-image-uploader.js', array('jquery'), null, false);
	wp_enqueue_style('anirohotellight_image_uploader_style', get_template_directory_uri().'/css/anirohotellight-image-uploader.css');
}
add_action('admin_enqueue_scripts', 'anirohotellight_image_uploader');

/**
 * Add more information about author to user profile
 */
function anirohotellight_wptuts_contact_methods($contactmethods) {

	// Add some useful ones
	$contactmethods['twitter']    = 'Twitter Username';
	$contactmethods['facebook']   = 'Facebook Profile URL';
	$contactmethods['linkedin']   = 'LinkedIn Public Profile URL';
	$contactmethods['googleplus'] = 'Google+ Profile URL';

	return $contactmethods;
}

add_filter('user_contactmethods', 'anirohotellight_wptuts_contact_methods');

/**
 * Include the TGM_Plugin_Activation.
 */
require_once get_template_directory().'/plugins/tgm/tgm.php';

//WooCommerce
add_action('after_setup_theme', 'anirohotellight_woocommerce_support');
function anirohotellight_woocommerce_support() {
	add_theme_support('woocommerce');
}

/**
 * Ability to upload images for the elements of the specified taxonomies: categories, tags.
 *
 * Example of obtaining the ID and URL of the image of the term:
 * $image_id = get_term_meta( $term_id, '_thumbnail_id', 1 );
 * $image_url = wp_get_attachment_image_url( $image_id, 'thumbnail' );
 *
 * @author: Kama (http://wp-kama.ru)
 *
 * @ver: 2.8
 */
if (is_admin() && !class_exists('Anirohotellight_Term_Meta_Image')) {
	// init
	add_action('admin_init', 'Anirohotellight_Term_Meta_Image_init');

	function Anirohotellight_Term_Meta_Image_init() {
		$GLOBALS['Anirohotellight_Term_Meta_Image'] = new Anirohotellight_Term_Meta_Image();
	}

	class Anirohotellight_Term_Meta_Image {

		// for which taxonomies to include the code. By default for all public
		static $taxes = array();
		// example: array('category', 'post_tag');

		// meta key name
		static $meta_key = '_thumbnail_id';

		// URL of the blank image
		static $add_img_url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQMAAABKLAcXAAAABlBMVEUAAAC7u7s37rVJAAAAAXRSTlMAQObYZgAAACJJREFUOMtjGAV0BvL/G0YMr/4/CDwY0rzBFJ704o0CWgMAvyaRh+c6m54AAAAASUVORK5CYII=';

		public function __construct() {
			if (isset($GLOBALS['Anirohotellight_Term_Meta_Image'])) {return $GLOBALS['Anirohotellight_Term_Meta_Image'];
			}
			// once

			$taxes = self::$taxes?self::$taxes:get_taxonomies(array('public' => true), 'names');

			foreach ($taxes as $taxname) {
				add_action("{$taxname}_add_form_fields", array(&$this, 'add_term_image'), 10, 2);
				add_action("{$taxname}_edit_form_fields", array(&$this, 'update_term_image'), 10, 2);
				add_action("created_{$taxname}", array(&$this, 'save_term_image'), 10, 2);
				add_action("edited_{$taxname}", array(&$this, 'updated_term_image'), 10, 2);

				add_filter("manage_edit-{$taxname}_columns", array(&$this, 'add_image_column'));
				add_filter("manage_{$taxname}_custom_column", array(&$this, 'fill_image_column'), 10, 3);
			}
		}

		## fields when creating a term
		public function add_term_image($taxonomy) {
			wp_enqueue_media();// connect media styles if there are none

			add_action('admin_print_footer_scripts', array(&$this, 'add_script'), 99);
			$this->css();
			?>
						<div class="form-field term-group">
							<label><?php esc_html_e('Image', 'aniro-hotel-light');?></label>
							<div class="term__image__wrapper">
								<a class="termeta_img_button" href="#">
									<img src="<?php echo esc_attr(self::$add_img_url);?>" alt="">
								</a>
								<input type="button" class="button button-secondary termeta_img_remove" value="<?php esc_attr_e('Remove', 'aniro-hotel-light');?>" />
							</div>

							<input type="hidden" id="term_imgid" name="term_imgid" value="">
						</div>
			<?php
		}

		## fields when editing the term
		public function update_term_image($term, $taxonomy) {
			wp_enqueue_media();// connect media styles if there are none

			add_action('admin_print_footer_scripts', array(&$this, 'add_script'), 99);

			$image_id  = get_term_meta($term->term_id, self::$meta_key, true);
			$image_url = $image_id?wp_get_attachment_image_url($image_id, 'thumbnail'):self::$add_img_url;
			$this->css();
			?>
						<tr class="form-field term-group-wrap">
							<th scope="row"><?php esc_html_e('Image', 'aniro-hotel-light');?></th>
							<td>
								<div class="term__image__wrapper">
									<a class="termeta_img_button" href="#">
			<?php echo '<img src="'.esc_url($image_url).'" alt="">';?>
									</a>
									<input type="button" class="button button-secondary termeta_img_remove" value="<?php esc_html_e('Remove', 'aniro-hotel-light');?>" />
								</div>

			                                    <input type="hidden" id="term_imgid" name="term_imgid" value="<?php echo esc_attr($image_id);?>">
							</td>
						</tr>
			<?php
		}

		public function css() {
			?>
			<style>
							.termeta_img_button{ display:inline-block; margin-right:1em; }
							.termeta_img_button img{ display:block; float:left; margin:0; padding:0; min-width:100px; max-width:150px; height:auto; background:rgba(0,0,0,.07); }
							.termeta_img_button:hover img{ opacity:.8; }
							.termeta_img_button:after{ content:''; display:table; clear:both; }
						</style>
			<?php
		}

		## Add script
		public function add_script() {

			$title      = __('Featured Image', 'aniro-hotel-light');
			$button_txt = __('Set featured image', 'aniro-hotel-light');
			?>
						<script>
						jQuery(document).ready(function($){
							var frame,
								$imgwrap = $('.term__image__wrapper'),
								$imgid   = $('#term_imgid');

							// addition
							$('.termeta_img_button').click( function(ev){
								ev.preventDefault();

								if( frame ){ frame.open(); return; }

								// set the media frame
								frame = wp.media.frames.questImgAdd = wp.media({
									states: [
										new wp.media.controller.Library({
											title:    '<?php echo esc_html($title)?>',
											library:   wp.media.query({ type: 'image' }),
											multiple: false,
											//date:   false
										})
									],
									button: {
										text: '<?php echo esc_html($button_txt)?>', // Set the text of the button.
									}
								});

								// choice
								frame.on('select', function(){
									var selected = frame.state().get('selection').first().toJSON();
									if( selected ){
										$imgid.val( selected.id );
										$imgwrap.find('img').attr('src', selected.sizes.thumbnail.url );
									}
								} );

								// open
								frame.on('open', function(){
									if( $imgid.val() ) frame.state().get('selection').add( wp.media.attachment( $imgid.val() ) );
								});

								frame.open();
							});

							// deleting
							$('.termeta_img_remove').click(function(){
								$imgid.val('');
								$imgwrap.find('img').attr('src','<?php echo esc_url(self::$add_img_url)?>');
							});
						});
						</script>

			<?php
		}

		## Adds a picture column to the table of terms
		public function add_image_column($columns) {
			// correct the width of the column through css
			add_action('admin_notices', function () {
					echo '<style>.column-image{ width:50px; text-align:center; }</style>';
				});

			$num = 1;// after which column on the account to insert

			$new_columns = array('image' => '');// column without a title ...

			return array_slice($columns, 0, $num)+$new_columns+array_slice($columns, $num);
		}

		public function fill_image_column($string, $column_name, $term_id) {
			// if there is a picture
			if ($image_id = get_term_meta($term_id, self::$meta_key, 1)) {
				$string = '<img src="'.wp_get_attachment_image_url($image_id, 'thumbnail').'" width="50" height="50" alt="" style="border-radius:4px;" />';
			}

			return $string;
		}

		## Save the form field
		public function save_term_image($term_id, $tt_id) {
			if (isset($_POST['term_imgid']) && $image = (int) $_POST['term_imgid']) {
				add_term_meta($term_id, self::$meta_key, $image, true);
			}
		}

		## Update the form field value
		public function updated_term_image($term_id, $tt_id) {
			if (!isset($_POST['term_imgid'])) {return;
			}

			if ($image = (int) $_POST['term_imgid']) {
				update_term_meta($term_id, self::$meta_key, $image);
			} else {

				delete_term_meta($term_id, self::$meta_key);
			}

		}

	}
}

/**
 * acf
 */
add_filter('acf/settings/load_json', 'anirohotellight_acf_json_load_point');

function anirohotellight_acf_json_load_point($paths) {
	// remove original path (optional)
	unset($paths[0]);

	// append path
	$paths[] = get_stylesheet_directory().'/acf-json';

	// return
	return $paths;
}
