<?php
	get_template_part( 'panel/constants' );

	load_theme_textdomain( 'ci_theme', get_template_directory() . '/lang' );

	// This is the main options array. Can be accessed as a global in order to reduce function calls.
	$ci = get_option(THEME_OPTIONS);
	$ci_defaults = array();

	// The $content_width needs to be before the inclusion of the rest of the files, as it is used inside of some of them.
	if ( ! isset( $content_width ) ) $content_width = 750;

	//
	// Let's bootstrap the theme.
	//
	get_template_part( 'panel/bootstrap' );

	get_template_part( 'functions/woocommerce' );

	//
	// Let WordPress manage the title.
	//
	add_theme_support( 'title-tag' );


	//
	// Define our various image sizes.
	//
	add_theme_support( 'post-thumbnails' );
	set_post_thumbnail_size( 750, 500, true );
	add_image_size( 'ci_blog_thumb', 750, 370, true );
	add_image_size( 'ci_thumb_sm', 350, 235, true );
	add_image_size( 'ci_blog_full', 1140, 380, true );
	add_image_size( 'ci_site_header', 1920, 160, true );
	add_image_size( 'ci_slider', 1920, 850, true );
	add_image_size( 'ci_square', 750, 750, true );
	add_image_size( 'ci_masonry', 750 );


	// Enable HTML5 support
	add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );

	// Let WooCommerce know that we support it.
	add_theme_support( 'woocommerce', array(
		'thumbnail_image_width'         => 750,
		'single_image_width'            => 750,
		'gallery_thumbnail_image_width' => 300,
	) );

	// Let the user choose a color scheme on each post individually.
	add_ci_theme_support( 'post-color-scheme', array( 'page', 'post', 'product', 'cpt_gallery', 'cpt_service', 'cpt_team', 'cpt_video' ) );

	// Set up the WordPress core custom background feature.
	add_theme_support( 'custom-background', apply_filters( 'ci_theme_custom_background_args', array() ) );

	// Enable the automatic video thumbnails.
	add_filter( 'ci_automatic_video_thumbnail_field', 'ci_theme_add_auto_thumb_video_field' );
	if ( ! function_exists( 'ci_theme_add_auto_thumb_video_field' ) ):
	function ci_theme_add_auto_thumb_video_field( $field ) {
		return 'ci_cpt_video_url';
	}
	endif;

	add_filter( 'the_content', 'ci_prettyPhoto_rel', 12 );
	add_filter( 'get_comment_text', 'ci_prettyPhoto_rel' );
	add_filter( 'wp_get_attachment_link', 'ci_prettyPhoto_rel' );
	if ( ! function_exists( 'ci_prettyPhoto_rel' ) ):
	function ci_prettyPhoto_rel( $content ) {
		global $post;
		$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>(.*?)<\/a>/i";

		$replacement = '<a$1href=$2$3.$4$5 data-rel="prettyPhoto[' . $post->ID . ']"$6>$7</a>';

		$content = preg_replace( $pattern, $replacement, $content );
		return $content;
	}
	endif;

	if ( ! function_exists( 'ci_get_remaining_time_array' ) ):
	function ci_get_remaining_time_array( $date, $time ) {
		$now  = current_time( 'timestamp' );
		$tmp  = strtotime( trim( $date ) . ' ' . trim( $time ), $now );
		$diff = $tmp - $now;
		if ( $diff <= 1 ) {
			return false;
		}
		$days    = floor( $diff / ( 60 * 60 * 24 ) );
		$diff    = $diff % ( 60 * 60 * 24 );
		$hours   = floor( $diff / ( 60 * 60 ) );
		$diff    = $diff % ( 60 * 60 );
		$minutes = round( $diff / 60 );
		$array   = array(
			'days'    => $days,
			'hours'   => $hours,
			'minutes' => $minutes,
		);

		return $array;
	}
	endif;

	if ( ! function_exists( 'ci_is_repeating_button' ) ):
	function ci_is_repeating_button( $txt ) {
		$pattern = '/^<(a|span).*class="btn".*\1>$/';
		preg_match( $pattern, $txt, $matches );

		return ! empty( $matches );
	}
	endif;

	if ( ! function_exists( 'ci_get_layout_classes' ) ):
	function ci_get_layout_classes( $context, $part ) {
		$sidebar_cols   = '';
		$content_cols   = '';
		$meta_placement = '';
		$glob_placement = ci_setting( 'layout_site' );

		if ( is_singular() ) {
			$meta_placement = get_post_meta( get_the_ID(), 'meta_placement', true );
		}

		if ( 'cpt' == $context ) {
			if ( 'alt' != $glob_placement ) {
				$sidebar_cols = 'col-md-push-8 col-sm-push-7';
				$content_cols = 'col-md-pull-4 col-sm-pull-5';
			}
			if ( 'right' == $meta_placement ) {
				$sidebar_cols = 'col-md-push-8 col-sm-push-7';
				$content_cols = 'col-md-pull-4 col-sm-pull-5';
			} elseif ( 'left' == $meta_placement ) {
				$sidebar_cols = '';
				$content_cols = '';
			}
		} elseif ( 'blog' == $context ) {
			if ( 'alt' == $glob_placement ) {
				$sidebar_cols = 'col-md-pull-8 col-sm-pull-7';
				$content_cols = 'col-md-push-4 col-sm-push-5';
			}
			if ( 'right' == $meta_placement ) {
				$sidebar_cols = '';
				$content_cols = '';
			} elseif ( 'left' == $meta_placement ) {
				$sidebar_cols = 'col-md-pull-8 col-sm-pull-7';
				$content_cols = 'col-md-push-4 col-sm-push-5';
			}
		}

		if ( 'content' == $part ) {
			return $content_cols;
		} elseif ( 'sidebar' == $part ) {
			return $sidebar_cols;
		}

	}
	endif;

	if ( ! function_exists( 'ci_get_read_more_text' ) ):
	function ci_get_read_more_text( $post_type ) {
		$wording = ci_setting( 'read_more_text' );

		if ( ! in_array( $post_type, array( 'post', 'page', 'attachment' ) ) ) {
			$tmp = ci_setting( 'read_more_text_' . $post_type );
			if ( ! empty( $tmp ) ) {
				$wording = $tmp;
			}
		}

		return $wording;
	}
	endif;

	if ( ! function_exists( 'ci_theme_get_slides' ) ):
	function ci_theme_get_slides( $base_category = false, $post_id = false, $return_ids = false ) {

		if ( $base_category === false && $post_id === false && get_option( 'show_on_front' ) == 'page' ) {
			$front = get_option( 'page_on_front' );
			if ( ! empty( $front ) ) {
				$base = get_post_meta( $front, 'base_slider_category', true );
				if ( ! empty( $base ) ) {
					$base_category = $base;
				}
			}
		} elseif ( $base_category === false && $post_id !== false ) {
			$base = get_post_meta( $post_id, 'base_slider_category', true );
			if ( ! empty( $base ) ) {
				$base_category = $base;
			}
		}

		$args = array(
			'post_type'      => 'cpt_slider',
			'posts_per_page' => - 1,
		);

		if ( ! empty( $base_category ) && $base_category > 0 ) {
			$args = array_merge( $args, array(
				'tax_query' => array(
					array(
						'taxonomy' => 'slider-category',
						'terms'    => intval( $base_category ),
					)
				)
			) );
		}

		if ( $return_ids === true ) {
			$args['fields'] = 'ids';
		}

		return new WP_Query( $args );
	}
	endif;


	if ( ! function_exists( 'ci_theme_get_columns_classes' ) ):
	function ci_theme_get_columns_classes( $columns ) {
		switch ( $columns ) {
			case 1:
				$classes = 'col-md-12 col-sm-6 col-xs-12';
				break;
			case 2:
				$classes = 'col-md-6 col-sm-6 col-xs-12';
				break;
			case 4:
				$classes = 'col-md-3 col-sm-6 col-xs-12';
				break;
			case 3:
			default:
				$classes = 'col-md-4 col-sm-6 col-xs-12';
				break;
		}

		return $classes;
	}
	endif;

	/**
	 * Theme Elements
	 */
	if ( defined( 'ELEMENTOR_VERSION' ) && version_compare( PHP_VERSION, '5.4', '>=' ) ) {
		require_once( 'functions/elements.php' );
	}

	function ci_theme_post_types() {
		$post_types_available = get_post_types( array( 'public' => true ), 'objects' );
		unset( $post_types_available['attachment'] );
		if ( post_type_exists( 'elementor_library' ) ) {
			unset( $post_types_available['elementor_library'] );
		}

		$ci_theme_pt[] = '';

		foreach ( $post_types_available as $key => $pt ) {
			$ci_theme_pt[ $key ] = $pt->label;
		}

		return $ci_theme_pt;
	}

	add_action( 'wp_ajax_ci_theme_get_posts', 'ajax_ci_theme_posts' );
	function ajax_ci_theme_posts() {

		// Verify nonce
		if ( ! isset( $_POST['ci_theme_post_nonce'] ) || ! wp_verify_nonce( $_POST['ci_theme_post_nonce'], 'ci_theme_post_nonce' ) ) {
			die( 'Permission denied' );
		}

		$post_type = $_POST['post_type'];

		$q = new WP_Query( array(
			'post_type' => $post_type,
			'posts_per_page' => -1,
		) );
		?>

		<option><?php esc_html_e( 'Select an item', 'ci_theme' ); ?></option>

		<?php while ( $q->have_posts() ) : $q->the_post(); ?>
			<option value="<?php echo esc_attr( get_the_ID() ); ?>"><?php the_title(); ?></option>
			<?php
		endwhile;
		wp_reset_postdata();
		wp_die();
	}


	if ( ! defined( 'CI_THEME_WHITELABEL' ) || false === (bool) CI_THEME_WHITELABEL ) {
		add_filter( 'pt-ocdi/import_files', 'ci_theme_ocdi_import_files' );
		add_action( 'pt-ocdi/after_import', 'ci_theme_ocdi_after_import_setup' );
	}

	add_filter( 'pt-ocdi/timeout_for_downloading_import_file', 'ci_theme_ocdi_download_timeout' );
	function ci_theme_ocdi_download_timeout( $timeout ) {
		return 60;
	}

	function ci_theme_ocdi_import_files( $files ) {
		if ( ! defined( 'CI_THEME_NAME' ) ) {
			define( 'CI_THEME_NAME', 'salon' );
		}

		$demo_dir_url = untrailingslashit( apply_filters( 'ci_theme_ocdi_demo_dir_url', 'https://www.cssigniter.com/sample_content/' . CI_THEME_NAME ) );

		// When having more that one predefined imports, set a preview image, preview URL, and categories for isotope-style filtering.
		$new_files = array(
			array(
				'import_file_name'           => esc_html__( 'Demo Import', 'ci_theme' ),
				'import_file_url'            => $demo_dir_url . '/content.xml',
				'import_widget_file_url'     => $demo_dir_url . '/widgets.wie',
				'import_customizer_file_url' => $demo_dir_url . '/customizer.dat',
			),
		);

		return array_merge( $files, $new_files );
	}

	function ci_theme_ocdi_after_import_setup() {
		// Set up nav menus.
		$main_menu      = get_term_by( 'name', 'Main', 'nav_menu' );
		$secondary_menu = get_term_by( 'name', 'Shop', 'nav_menu' );

		set_theme_mod( 'nav_menu_locations', array(
			'ci_main_menu'      => $main_menu->term_id,
			'ci_secondary_menu' => $secondary_menu->term_id,
		) );

		// Set up home and blog pages.
		$front_page_id = get_page_by_title( 'Home' );
		$blog_page_id  = get_page_by_title( 'Blog' );

		update_option( 'show_on_front', 'page' );
		update_option( 'page_on_front', $front_page_id->ID );
		update_option( 'page_for_posts', $blog_page_id->ID );

		// Try to force a term recount.
		// wp_defer_term_counting( false ) doesn't work properly as there are post imported from different AJAX requests.
		$taxonomies = get_taxonomies( array(), 'names' );
		foreach ( $taxonomies as $taxonomy ) {
			$terms             = get_terms( $taxonomy, array( 'hide_empty' => false ) );
			$term_taxonomy_ids = wp_list_pluck( $terms, 'term_taxonomy_id' );

			wp_update_term_count( $term_taxonomy_ids, $taxonomy );
		}
	}

	if ( ! function_exists( 'ci_theme_color_luminance' ) ) :
		/**
		 * Lightens/darkens a given colour (hex format), returning the altered colour in hex format.
		 *
		 * @see https://gist.github.com/stephenharris/5532899
		 *
		 * @param string $color Hexadecimal color value. May be 3 or 6 digits, with an optional leading # sign.
		 * @param float $percent Decimal (0.2 = lighten by 20%, -0.4 = darken by 40%)
		 *
		 * @return string Lightened/Darkened colour as hexadecimal (with hash)
		 */
		function ci_theme_color_luminance( $color, $percent ) {
			// Remove # if provided
			if ( '#' === $color[0] ) {
				$color = substr( $color, 1 );
			}

			// Validate hex string.
			$hex     = preg_replace( '/[^0-9a-f]/i', '', $color );
			$new_hex = '#';

			$percent = floatval( $percent );

			if ( strlen( $hex ) < 6 ) {
				$hex = $hex[0] + $hex[0] + $hex[1] + $hex[1] + $hex[2] + $hex[2];
			}

			// Convert to decimal and change luminosity.
			for ( $i = 0; $i < 3; $i ++ ) {
				$dec = hexdec( substr( $hex, $i * 2, 2 ) );
				$dec = min( max( 0, $dec + $dec * $percent ), 255 );
				$new_hex .= str_pad( dechex( $dec ), 2, 0, STR_PAD_LEFT );
			}

			return $new_hex;
		}
	endif;

		/**
	 * Sanitizes integer input while differentiating zero from empty string.
	 *
	 * @param int|string $input Input value to sanitize.
	 * @return int|string Integer value, 0, or an empty string otherwise.
	 */
	function ci_theme_sanitize_intval_or_empty( $input ) {
		if ( false === $input || '' === $input || is_null( $input ) ) {
			return '';
		}

		if ( 0 === intval( $input ) ) {
			return 0;
		}

		return intval( $input );
	}

	/**
	 * Sanitizes float input while differentiating zero from empty string.
	 *
	 * @param int|string $input Input value to sanitize.
	 * @return int|string Integer value, 0, or an empty string otherwise.
	 */
	function ci_theme_sanitize_floatval_or_empty( $input ) {
		if ( false === $input || '' === $input || is_null( $input ) ) {
			return '';
		}

		if ( 0 === floatval( $input ) ) {
			return 0;
		}

		return floatval( $input );
	}

	function ci_theme_customizer_defaults( $setting = false ) {
		$theme = wp_get_theme();

		// phpcs:disable WordPress.Arrays.MultipleStatementAlignment.DoubleArrowNotAligned
		$defaults = apply_filters(
			'ci_theme_customizer_defaults',
			array(
				'global_typo_is_google_active' => 1,
				'global_typo_body' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Lato',
							'variant'    => '400',
							'size'       => 16,
							'lineHeight' => 1.5,
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h1' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 24,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h2' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 20,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h3' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 18,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h4' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 16,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h5' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 14,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_h6' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 12,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_form_labels' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Lato',
							'variant'    => '400',
							'size'       => '',
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_form_text' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Lato',
							'variant'    => '400',
							'size'       => 14,
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_buttons' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Lato',
							'variant'    => '700',
							'size'       => 12,
							'lineHeight' => '',
							'transform'  => 'uppercase',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_widget_titles' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Montserrat',
							'variant'    => '400',
							'size'       => 13,
							'lineHeight' => '',
							'transform'  => 'uppercase',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
				'global_typo_widget_text' => ci_theme_typography_control_defaults_empty_breakpoints(
					array(
						'desktop' => array(
							'family'     => 'Lato',
							'variant'    => '400',
							'size'       => '',
							'lineHeight' => '',
							'transform'  => 'none',
							'spacing'    => '',
							'is_gfont'   => true,
						),
					)
				),
			)
		);
		// phpcs:enable

		if ( ! empty( $setting ) && array_key_exists( $setting, $defaults ) ) {
			return apply_filters( 'ci_theme_customizer_default', $defaults[ $setting ], $setting );
		}

		return $defaults;
	}

	/**
	 * Outputs a preconnect link that helps performance of Google Fonts.
	 * Hooked conditionally on 'wp_head'.
	 */
	function ci_theme_head_preconnect_google_fonts() {
		?><link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin><?php
	}


	/**
	 * Fonts list.
	 */
	require_once get_theme_file_path( '/functions/class-fonts-list.php' );

	/**
	 * Common theme features.
	 */
	require_once get_theme_file_path( '/common/common.php' );


	/**
	 * Customizer additions.
	 */
	require_once get_template_directory() . '/functions/customizer.php';

	/**
	 * Customizer styles.
	 */
	require_once get_theme_file_path( '/functions/customizer-styles.php' );
