<?php

namespace Tech360;

defined( 'ABSPATH' ) or die;

class Utils {

	/**
	 * Remove all extra spaces
	 * @param string
	 * @return string
	 */
	static function trim_all( $input ) {
		return trim( preg_replace( '/\s\s+/', ' ', str_replace( "\n", " ", $input ) ) );
	}

	/**
	 * Replace spaces and underscored with dashes
	 * @param string
	 * @return string
	 */
	static function sluggify( $input ) {
		return str_replace( [ " ", "_" ], "-", self::trim_all( $input ) );
	}

	/**
	 * Remove all spaces, dashes and underscores
	 * @param string
	 * @return string
	 */
	static function make_phone( $input ) {
		return str_replace( [ " ", "-", "_" ], "", self::trim_all( $input ) );
	}

	/**
	 * Render email or phone link
	 * @param string		$href
	 * @param string		$type		'mailto' or 'tel'
	 * @param bool			$echo		Default true
	 * @return mixed
	 */
	static function render_link( $href, $type, $echo = true ) {

		if( empty( $href ) || empty( $type ) )
			return;

		if( ! is_string( $href ) )
			return;

		if( 'mailto' != $type && 'tel' != $type )
			return;

		$label = self::trim_all( $href );

		if( 'tel' == $type ) {
			$href = self::make_phone( $href );
			$title = sprintf( 'Call us at %s', $label );
		} else {
			$title = sprintf( 'Email us at %s', $label );
		}

		$output = sprintf( '<a href="%s:%s" title="%s">%s</a>', $type, $href, $title, $label );

		if( $echo ) {
			echo $output;
		} else {
			return $output;
		}

	}

	/**
	 * Get image attachment by image ID
	 * @param integer		$attachment_id
	 * @param boolean		$src_only		Default true
	 * @param string		$size			Default 'full'
	 * @return mixed
	 */
	static function get_image_by_id( $attachment_id, $src_only = true, $size = 'full' ) {

		$image = [];

		$img = wp_get_attachment_image_src( $attachment_id, $size );
		$image[ 'src' ] = $img[ 0 ];
		$image[ 'width' ] = $img[ 1 ];
		$image[ 'height' ] = $img[ 2 ];
		$image[ 'resized' ] = $img[ 3 ];
		$image[ 'alt' ] = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
		$image[ 'title' ] = get_post( $attachment_id )->post_title;
		$image[ 'caption' ] = wp_get_attachment_caption( $attachment_id );
		$image[ 'description' ] = get_post( $attachment_id )->post_content;

		if( $src_only )
			return $image[ 'src' ];
		else
			return $image;

	}

	/**
	 * Render the logo tag
	 * @param array			$atts			Link title and image alt attributes
	 * @param string		$link_class		Class to be applied to the <a> tag
	 * @param string		$img_class		Class to be applied to the <img> tag
	 */
	static function render_logo_link( $link_class = '', $img_class = '' ) {

		$src = self::get_image_by_id( get_theme_mod( 'custom_logo', false ) );

		$href = esc_url( home_url( '/' ) );
		$title = get_bloginfo( 'name' );
		$alt = get_bloginfo( 'name' );

		$l_class = [];
		$i_class = [];

		if( $link_class ) {
			$l_class = explode( ' ', self::trim_all( $link_class ) );
		}
		$l_class[] = 'd-inline-block';

		if( $img_class ) {
			$i_class = explode( ' ', self::trim_all( $img_class ) );
		}
		$i_class[] = 'img-fluid';

		$output = sprintf( '<a href="%s" title="%s" class="%s"><img src="%s" alt="%s" class="%s"></a>', $href, $title, implode( ' ', $l_class ), $src, $alt, implode( ' ', $i_class ) );

		echo $output;

	}

	/**
	 * Just a wrapper for get_option
	 */
	static function option( $option_name, $default = false ) {
		return get_option( $option_name, $default );
	}

	static function render_custom_styles() {

		$primary_color = self::option( 'primary_color' );
		$secondary_color = self::option( 'secondary_color' );
		$headings_color = self::option( 'headings_color' );
		$text_color = self::option( 'text_color' );

		if( $primary_color || $secondary_color || $headings_color || $text_color ) {
		?>
			<style type="text/css">
		<?php
			if( $primary_color ) {
		?>
				.btn-primary {
					background-color: <?php echo $primary_color ?>;
				}
		<?php
			}
		?>
			</style>
		<?php
		}

	}

	/**
	 * Build main content class
	 * @param integer		$the_id
	 * @param boolean		$echo		Default true
	 * @return string
	 */
	static function _main_class( $the_id, $echo = true ) {

		$output = [];

		$output[] = get_field( 'main_content_layout', $the_id );

		if( 'none' != get_field( 'main_content_top_padding', $the_id ) ) {
			$output[] = get_field( 'main_content_top_padding', $the_id );
		}

		if( 'none' != get_field( 'main_content_bottom_padding', $the_id ) ) {
			$output[] = get_field( 'main_content_bottom_padding', $the_id );
		}

		if( 'none' != get_field( 'main_content_top_margin', $the_id ) ) {
			$output[] = get_field( 'main_content_top_margin', $the_id );
		}

		if( 'none' != get_field( 'main_content_bottom_margin', $the_id ) ) {
			$output[] = get_field( 'main_content_bottom_margin', $the_id );
		}

		if( $echo ) {
			echo implode( ' ', $output );
		} else {
			return implode( ' ', $output );
		}

	}

	/**
	 * Build main content style
	 * @param integer		$the_id
	 * @param boolean		$echo		Default true
	 * @return string
	 */
	static function _main_style( $the_id, $echo = true ) {

		$output = [];

		if( 'container' == get_field( 'main_content_layout', $the_id ) && 'none' != get_field( 'main_content_width', $the_id ) ) {
			$output[] = 'max-width: ' . get_field( 'main_content_width', $the_id );
		}

		if( $echo ) {
			echo implode( '; ', $output );
		} else {
			return implode( '; ', $output );
		}

	}

	/**
	 * Build main content header style
	 * @param integer		$the_id
	 * @param boolean		$echo		Default true
	 * @return string
	 */
	static function _header_style( $the_id, $echo = true ) {

		$output = '';

		if( get_field( 'header_image', $the_id ) ) {
			$output = sprintf( 'background-image: url(%s)', self::get_image_by_id( get_field( 'header_image', $the_id ) ) );
		}

		if( $echo ) {
			echo $output;
		} else {
			return $output;
		}

	}

	/**
	 * Return contact info as a list
	 * @param array			$info
	 * @param boolean		$echo		Default true
	 * @return string
	 */
	static function render_contact_info_list_tags( $info, $echo = true ) {

		if( empty( $info ) || ! is_array( $info ) ) {
			return;
		}

		$output = [];

		foreach( $info as $mod ) {
			if( get_option( $mod ) ) {
				$data = CONTACT_INFO[ $mod ];
				$icon = array_key_exists( 'icon', $data ) ? $data[ 'icon' ] : '';
				if( array_key_exists( 'link_type', $data ) ) {
					$output[] = sprintf( '<li>%s%s</li>', $icon, self::render_link( get_option( $mod ), $data[ 'link_type' ], false ) );
				} else {
					$output[] = sprintf( '<li>%s%s</li>', $icon, nl2br( get_option( $mod ) ) );
				}
			}
		}

		if( $echo ) {
			echo implode( '', $output );
		} else {
			return implode( '', $output );
		}

	}

	/**
	 * Return social links as a list
	 * @param boolean		$echo		Default true
	 * @return string
	 */
	static function the_social_links( $echo = true ) {

		/**
		 * Social links array is defined in /theme-code/constants.php
		 */
		$social_links = SOCIAL_LINKS;

		foreach( array_keys( $social_links ) as $social_link ) {
			if( ! get_option( $social_link ) ) {
				unset( $social_links[ $social_link ] );
			}
		}

		if( empty( $social_links ) ) {
			return;
		}

		$output = [];

		$output[] = '<ul class="social-links">';

		foreach( $social_links as $social_link => $social_link_args ) {
			if( get_option( $social_link, false ) ) {
				$output[] = sprintf( '<li><a href="%s" target="_blank" title="%s">%s</a></li>', get_option( $social_link ), $social_link_args[ 'label' ], $social_link_args[ 'icon' ] );
			}
		}

		$output[] = '</ul>';

		if( $echo ) {
			echo implode( '', $output );
		} else {
			return implode( '', $output );
		}

	}

	/**
	 * Check if we have contact info to display
	 * @param mixed		$info			String or array of options to check against
	 * @return boolean
	 */
	static function has_contact_info( $info = null ) {

		if( ! $info ) {
			$info = 'phone_number toll_free_number email office_address';
		}

		if( is_string( $info ) ) {
			$info = explode( ' ', self::trim_all( $info ) );
		}

		if( ! is_array( $info ) ) {
			return false;
		}

		$contact_info = false;

		foreach( $info as $mod ) {
			if( get_option( $mod ) ) {
				$contact_info = true;
				break;
			}
		}

		return $contact_info;

	}

	/**
	 * Check if we have social networks defined
	 * @return boolean
	 */
	static function has_social_networks() {

		$social = false;

		foreach( SOCIAL_LINKS as $mod => $data ) {
			if( get_option( $mod ) ) {
				$social = true;
				break;
			}
		}

		return $social;

	}

	/**
	 * Check if we have top bar
	 * @param mixed			$options		String or array of options to check against. Default null
	 * @return boolean
	 */
	function has_top_bar( $options = null ) {

		if( ! $options ) {
			$options = 'top_bar_phone top_bar_toll_free_phone top_bar_email top_bar_quote_button top_bar_book_button';
		}

		if( is_string( $options ) ) {
			$options = explode( ' ', self::trim_all( $options ) );
		}

		if( ! is_array( $options ) ) {
			return false;
		}

		$output = false;

		foreach( $options as $option ) {
			switch( $option ) {
				case 'top_bar_quote_button':
					if( get_option( $option ) && get_option( 'top_bar_quote_page' ) ) {
						$output = true;
						break 2;
					}
					break;
				case 'top_bar_book_button':
					if( get_option( $option ) && get_option( 'top_bar_book_page' ) ) {
						$output = true;
						break 2;
					}
					break;
				default:
					if( get_option( $option ) ) {
						$output = true;
						break 2;
					}
					break;
			}
		}

		return $output;

	}

	/**
	 * Render elements in the top bar
	 * @param mixed			$elements		String or array containing the options.
	 * @param boolean		$echo			Default true
	 * @return string
	 */
	static function render_top_bar_elements( $elements, $echo = true ) {

		if( empty( $elements ) ) {
			return;
		}

		if( is_string( $elements) ) {
			$elements = explode( ' ', self::trim_all( $elements ) );
		}

		if( ! is_array( $elements ) ) {
			return;
		}

		$output = [];

		foreach( $elements as $option ) {
			if( get_option( $option ) ) {
				if( 'top_bar_quote_button' == $option ) {
					if( get_option( 'top_bar_quote_page' ) ) {
						$output[] = sprintf( '<div class="top-bar-element"><a class="%s" href="%s">%s</a></div>', TOP_BAR_OPTIONS[ $option ][ 'btn_class' ], get_permalink( get_option( 'top_bar_quote_page' ) ), get_option( 'top_bar_quote_button_label', 'Get a quote' ) );
					}
				} elseif( 'top_bar_book_button' == $option ) {
					if( get_option( 'top_bar_book_page' ) ) {
						$output[] = sprintf( '<div class="top-bar-element"><a class="%s" href="%s">%s</a></div>', TOP_BAR_OPTIONS[ $option ][ 'btn_class' ], get_permalink( get_option( 'top_bar_book_page' ) ), get_option( 'top_bar_book_button_label', 'Book now' ) );
					}
				} else {
					if( array_key_exists( 'link_type', TOP_BAR_OPTIONS[ $option ] ) ) {
						if( get_option( TOP_BAR_OPTIONS[ $option ][ 'option' ] ) ) {
							$elm = '<div class="top-bar-element">';
							if( array_key_exists( 'icon', TOP_BAR_OPTIONS[ $option ] ) ) {
								$elm .= TOP_BAR_OPTIONS[ $option ][ 'icon' ];
							}
							$elm .= self::render_link( get_option( TOP_BAR_OPTIONS[ $option ][ 'option' ] ), TOP_BAR_OPTIONS[ $option ][ 'link_type' ], false );
							$elm .= '</div>';
							$output[] = $elm;
						}
					}
				}
			}
		}

		if( $echo ) {
			echo implode( '', $output );
		} else {
			return implode( '', $output );
		}

	}

	/**
	 * Render custom post type menu
	 * @param string		$post_type
	 * @param array			$args			Default null
	 * @param boolean		$echo			Default true
	 * @return string
	 */
	static function render_menu( $post_type, $args = null, $echo = true ) {

		if( ! is_string( $post_type ) || empty( $post_type ) ) {
			return;
		}

		$query_args = [
			'post_type' => $post_type,
			'posts_per_page' => -1,
			'orderby' => 'menu_order',
			'order' => 'ASC'
		];

		if( is_array( $args ) && array_key_exists( 'exclude', $args) ) {
			if( is_array( $args[ 'exclude' ] ) ) {
				$query_args[ 'exclude' ] = $args[ 'exclude' ];
			} else {
				$exclude = explode( ' ', self::trim_all( $args[ 'exclude' ] ) );
				$query_args[ 'exclude' ] = $exclude;
			}
		}

		$items = get_posts( $query_args );

		$output = [];
		$output[] = '<ul class="side-menu">';

		foreach( $items as $item ) {

			$active_class = '';
			if( is_array( $args ) && array_key_exists( 'active', $args ) && $args[ 'active' ] ) {
				if( intval( $args[ 'active' ] ) == intval( $item->ID ) ) {
					$active_class = 'active';
				}
			}

			$title = apply_filters( 'the_title', $item->post_title, $item->ID );

			$output[] = sprintf( '<li class="%s"><a href="%s">%s</a></li>', $active_class, get_permalink( $item->ID ), $title );

		}

		$output[] = '</ul>';

		if( $echo ) {
			echo implode( '', $output );
		} else {
			return implode( '', $output );
		}

	}

	/**
	 * Check if a specific contact form is defined.
	 * @param mixed			$form		ID or title
	 * @return boolean
	 */
	static function wpcf7_exists( $form ) {

		if( empty( $form ) ) {
			return false;
		}

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

		if( is_numeric( $form ) ) {
			$identifier = 'id';
		} else {
			$identifier = 'title';
		}

		$err_response = '[contact-form-7 404 "Not Found"]';
		$response = do_shortcode( sprintf( '[contact-form-7 %s="%s"]', $identifier, $form ) );

		return ! ( strlen( $response ) == strlen( $err_response ) || $response == $err_response || strpos( $response, 'Not Found' ) !== false );

	}

	/**
	 * Get posts
	 * @param string		$post_type
	 * @param array			$args		Default null
	 * @return array
	 */
	static function get_all( $post_type, $args = null ) {

		if( empty( $post_type ) ) {
			return false;
		}

		$query_args = [
			'post_type' => $post_type,
			'posts_per_page' => -1,
			'orderby' => 'menu_order',
			'order' => 'ASC'
		];

		if( is_array( $args ) ) {
			if( array_key_exists( 'posts_per_page', $args ) ) {
				$query_args[ 'posts_per_page' ] = $args[ 'posts_per_page' ];
			}
			if( array_key_exists( 'orderby', $args ) ) {
				$query_args[ 'orderby' ] = $args[ 'orderby' ];
			}
			if( array_key_exists( 'order', $args ) ) {
				$query_args[ 'order' ] = $args[ 'order' ];
			}
		}

		return get_posts( $query_args );

	}

	/**
	 * Render hero video
	 * @param integer			$page_id
	 * @param boolean			$echo		Default true
	 */
	static function render_video( $page_id, $echo = true ) {

		$extensions = [ 'mp4', 'webm', 'ogv' ];
		$srcset = [];
		$output = [];

		$video_src = get_field( 'hero_video', $page_id )[ 'url' ];
		$video_name = pathinfo( $video_src, PATHINFO_FILENAME );
		$video_extension = pathinfo( $video_src, PATHINFO_EXTENSION );
		$video_dir = pathinfo( $video_src, PATHINFO_DIRNAME );

		$srcset[] = [
			'src' => $video_src,
			'ext' => $video_extension
		];
		foreach( $extensions as $ext ) {
			if( $ext != $video_extension ) {
				$srcset[] = [
					'src' => sprintf( '%s/%s.%s', $video_dir, $video_name, $ext ),
					'ext' => $ext
				];
			}
		}

		$output[] = '<div class="video-background position-relative">';

		if( get_field( 'hero_title', $page_id ) || get_field( 'hero_content', $page_id ) ) {
			$output[] = '<div class="container position-relative z-index-3"><div class="row"><div class="col-md-6">';
		}
		if( get_field( 'hero_title', $page_id ) ) {
			$output[] = sprintf( '<h1 class="hero-title text-light">%s</h1>', get_field( 'hero_title', $page_id ) );
		}
		if( get_field( 'hero_content', $page_id ) ) {
			$output[] = '<div class="hero-content text-light">';
			$output[] = get_field( 'hero_content', $page_id );
			if( get_field( 'hero_button', $page_id ) && get_field( 'hero_button_link', $page_id ) ) {
				$output[] = sprintf( '<a class="btn btn-primary mt-5" href="%s">%s</a>', get_permalink( get_field( 'hero_button_link', $page_id ) ), get_field( 'hero_button_label', $page_id ) );
			}
			$output[] = '</div>';
		}
		if( get_field( 'hero_title', $page_id ) || get_field( 'hero_content', $page_id ) ) {
			$output[] = '</div></div></div>';
		}

		$output[] = '<video class="cover z-index-1" autoplay loop muted>';
		foreach( $srcset as $source ) {
			$output[] = sprintf( '<source src="%s" type="video/%s">', $source[ 'src' ], $source[ 'ext' ] );
		}
		$output[] = '</video>';

		if( 'video' == get_field( 'hero_section', $page_id ) && get_field( 'hero_video', $page_id ) && get_field( 'hero_video_overlay', $page_id ) ) {
			$overlay_color = get_field( 'hero_overlay_color', $page_id ) ? get_field( 'hero_overlay_color', $page_id ) : '#000';
			$overlay_opacity = get_field( 'hero_overlay_opacity', $page_id ) ? intval( get_field( 'hero_overlay_opacity', $page_id ) ) / 100 : .3;
			$output[] = sprintf( '<span class="bg-overlay z-index-2" style="background-color: %s; opacity: %s"></span>', $overlay_color, $overlay_opacity );
		}
		$output[] = '</div>';

		if( $echo ) {
			echo implode( '', $output );
		} else {
			return implode( '', $output );
		}

	}

}
