<?php
namespace TotalTheme\Header;

use TotalTheme\Header\Core as Header;
use TotalTheme\Header\Overlay as Overlay_Header;
use TotalTheme\Header\Sticky as Sticky_Header;

defined( 'ABSPATH' ) || exit;

/**
 * Header Logo.
 *
 * @package TotalTheme
 * @subpackage Header
 * @version 5.5
 */
class Logo {

	/**
	 * Stores the header logo image id.
	 */
	protected static $image_id;

	/**
	 * Stores the header logo retina image id.
	 */
	protected static $retina_image_id;

	/**
	 * Stores the header logo image src.
	 */
	protected static $image_src;

	/**
	 * Stores whether the header logo is an svg or not.
	 */
	protected static $is_image_svg;

	/**
	 * Stores the header logo icon.
	 */
	protected static $icon;

	/**
	 * Checks if the logo should scroll up on click.
	 */
	public static function has_scroll_top_link() {
		$check = false;

		/**
		 * Filter for the header logo scroll to top check.
		 *
		 * @param boolean $check
		 */
		$check = (bool) apply_filters( 'wpex_header_logo_scroll_top', $check );

		if ( $post_id = wpex_get_current_post_id() ) {
			$meta = get_post_meta( $post_id, 'wpex_logo_scroll_top', true );
			if ( 'enable' === $meta ) {
				$check = true;
			} elseif ( 'disable' === $meta ) {
				$check = false;
			}
		}

		return (bool) $check;
	}

	/**
	 * Returns header logo link url.
	 */
	public static function get_link_url() {
		$url = null;

		if ( self::has_scroll_top_link() ) {
			$url = '#';
		} else {
			if ( get_theme_mod( 'logo_has_link', true ) ) {
				if ( wpex_vc_is_inline() ) {
					$url = get_permalink();
				}
				$url = $url ?: home_url( '/' );
			}
		}

		/**
		 * Filters the header logo url.
		 *
		 * @param string $url
		 */
		$url = (string) apply_filters( 'wpex_header_logo_url', $url );
		$url = apply_filters( 'wpex_logo_url', $url ); // old filter

		return $url;
	}

	/**
	 * Returns header logo image ID.
	 */
	public static function get_image_id() {
		if ( ! is_null( self::$image_id ) ) {
			return self::$image_id;
		}

		$image_id = wpex_get_translated_theme_mod( 'custom_logo' );

		/**
		 * Filters the header logo image url.
		 *
		 * @param string $img
		 *
		 * @todo this technically returns an attachment ID not a URL so we should move the filter
		 * 		 over to the get_image_url method.
		 */
		self::$image_id = apply_filters( 'wpex_header_logo_img_url', $image_id );

		// @todo - move overlay header logo checks here.

		// return self::get_image( $parse_logo ); // @todo use recursive function?

		return self::$image_id;
	}

	/**
	 * Returns header logo image url.
	 */
	public static function get_image_url() {
		$image_id = self::get_image_id();
		if ( $image_id ) {
			return self::parse_image( $image_id );
		}
	}

	/**
	 * Returns header logo retina image.
	 */
	public static function get_retina_image_id() {
		if ( ! is_null( self::$retina_image_id ) ) {
			return self::$retina_image_id;
		}

		if ( Overlay_Header::is_enabled() && Overlay_Header::logo_img() ) {
			$image_id = Overlay_Header::logo_img_retina();
		} else {
			$image_id = wpex_get_translated_theme_mod( 'retina_logo' );
		}

		/**
		 * Filters the header logo retina image url.
		 *
		 * @todo deprecate.
		 */
		$image_id = apply_filters( 'wpex_retina_logo_url', $image_id );

		/**
		 * Filters the header logo retina image url.
		 *
		 * @param string $image_id url.
		 *
		 * @todo this technically returns an attachment ID not a URL so we should move the filter
		 * 		 over to the get_retina_image_url method.
		 */
		self::$retina_image_id = apply_filters( 'wpex_header_logo_img_retina_url', $image_id );

		return self::$retina_image_id;
	}

	/**
	 * Returns header logo retina image.
	 */
	public static function get_retina_image_url() {
		$image_id = self::get_retina_image_id();
		if ( $image_id ) {
			return self::parse_image( $image_id );
		}
	}

	/**
	 * Returns header logo image src.
	 */
	public static function get_image_src() {
		if ( ! is_null( self::$image_src ) ) {
			return self::$image_src;
		}

		self::$image_src = '';

		if ( Overlay_Header::is_enabled() ) {
			$overlay_logo = Overlay_Header::logo_img( false );
			if ( $overlay_logo && is_numeric( $overlay_logo ) ) {
				self::$image_src = wp_get_attachment_image_src( $overlay_logo, 'full', false );
			}
		} else {
			$logo_id = self::get_image_id();
			if ( $logo_id && is_numeric( $logo_id ) ) {
				self::$image_src = wp_get_attachment_image_src( $logo_id, 'full', false );
			}
		}

		return self::$image_src;
	}

	/**
	 * Return logo image width.
	 */
	public static function get_image_width() {
		$width = get_theme_mod( 'logo_width' );

		/**
		 * Filters the header logo image width.
		 *
		 * @param int $width
		 * @todo need to prefix the filter.
		 */
		$width = (int) apply_filters( 'logo_width', $width );

		// Calculate width from src.
		if ( ! $width && ! self::is_image_svg() ) {
			$logo_src = self::get_image_src();
			if ( ! empty( $logo_src[1] ) ) {
				$width = absint( $logo_src[1] );
			}
		}

		if ( $width ) {
			return absint( $width );
		}
	}

	/**
	 * Return logo image height.
	 */
	public static function get_image_height() {
		$height = get_theme_mod( 'logo_height' );

		/**
		 * Filters the header logo image height.
		 *
		 * @param int $height
		 * @todo need to prefix the filter.
		 */
		$height = (int) apply_filters( 'logo_height', $height );

		if ( ! $height && ! self::is_image_svg() ) {
			$logo_src = self::get_image_src();
			if ( ! empty( $logo_src[2] ) ) {
				$height = absint( $logo_src[2] );
			}
		}

		if ( $height ) {
			return absint( $height );
		}
	}

	/**
	 * Checks if the header logo image is an svg or not.
	 */
	public static function is_image_svg() {
		if ( ! is_null( self::$is_image_svg ) ) {
			return self::$is_image_svg;
		}

		$check = false;

		$logo = self::get_image_id();

		if ( $logo ) {
			if ( is_numeric( $logo ) ) {
				$mime_type = get_post_mime_type( $logo );
				if ( 'image/svg+xml' === $mime_type ) {
					$check = true;
				}
			} elseif ( is_string( $logo ) ) {
				$check = strpos( $logo, '.svg' );
			}
		}

		/**
		* Checks whether the header logo image is an SVG or not.
		*
		* @since 4.0
		*/
		self::$is_image_svg = (bool) apply_filters( 'wpex_header_logo_is_svg', $check );

		return self::$is_image_svg;
	}

	/**
	 * Returns header logo icon.
	 */
	public static function get_icon() {
		if ( ! is_null( self::$icon ) ) {
			if ( ! self::$icon ) {
				return '';
			}
			return self::$icon;
		}

		$html = '';

		$custom_icon = (int) wpex_get_translated_theme_mod( 'logo_icon_img' );

		// Custom image based icon.
		if ( $custom_icon ) {
			$custom_icon_image_url = wp_get_attachment_image_url( $custom_icon, 'full' );
			if ( $custom_icon_image_url ) {
				$dims = (string) get_theme_mod( 'logo_icon_img_dims' );
				$dims_escaped = esc_attr( absint( $dims ) );
				$img_attrs = array(
					'src'    => esc_url( $custom_icon_image_url ),
					'width'  => $dims_escaped ?: null,
					'height' => $dims_escaped ?: null, // it will use auto anyway
					'alt'    => wpex_get_attachment_data( $custom_icon, 'alt' ),
				);
				$html = '<span id="site-logo-icon" class="wpex-inline-flex wpex-items-center wpex-flex-shrink-0 wpex-max-h-100 wpex-mr-10" aria-hidden="true"><img ' . trim( wpex_parse_attrs( $img_attrs ) ) . '></span>';
			}
		}

		// Theme icon based icon.
		else {

			/**
			 * Filters the header logo icon.
			 *
			 * @param string $icon
			 */
			$icon = (string) apply_filters( 'wpex_header_logo_icon', get_theme_mod( 'logo_icon' ) );

			if ( $icon && 'none' !== $icon ) {
				$html = wpex_get_theme_icon_html( $icon, [
					'id'    => 'site-logo-fa-icon',
					'class' => 'site-logo-text__icon wpex-mr-10',
				] );
			}
		}

		/**
		 * Filters the header logo icon html
		 *
		 * @param string $html
		 */
		self::$icon = apply_filters( 'wpex_header_logo_icon_html', $html );

		return self::$icon;
	}

	/**
	 * Returns header logo text.
	 */
	public static function get_text() {
		$text = get_theme_mod( 'logo_text' );

		if ( empty( $text ) || ! is_string( $text ) ) {
			$text = get_bloginfo( 'name' );
		}

		/**
		 * Filters the header logo text.
		 *
		 * @param string $text
		 */
		$text = (string) apply_filters( 'wpex_header_logo_text', $text );

		/**
		 * Filters the header logo title.
		 *
		 * @param string $title
		 * @todo deprecate
		 */
		$text = (string) apply_filters( 'wpex_logo_title', $text );

		return $text;
	}

	/**
	 * Return logo image class.
	 */
	public static function get_image_class() {
		$class = array(
			'logo-img',
			// Keep as abstract class for now.
			//	'wpex-inline',
			//	'wpex-align-middle',
			//	'wpex-w-auto',
			//	'wpex-h-auto',
			//	'wpex-max-h-100',
			//	'wpex-max-w-100',
		);

		/**
		 * Filters the header logo image class.
		 *
		 * @param array $classes
		 */
		$class = (array) apply_filters( 'wpex_header_logo_img_class', $class );

		$class_escaped = array_map( 'esc_attr', $class );
		return implode( ' ', $class_escaped );
	}

	/**
	 * Return logo text classes.
	 */
	public static function get_text_class() {
		$class = array(
			'site-logo-text',
		//	'wpex-font-bold',
		);

		if ( self::get_icon() ) {
			$class[] = 'wpex-inline-flex';
			$class[] = 'wpex-items-center';
		}

		/**
		 * Filters the header logo text class
		 *
		 * @param array $class
		 */
		$class = (array) apply_filters( 'wpex_header_logo_txt_class', $class );

		// Sanitize classes.
		$class_escaped = array_map( 'esc_attr', $class );

		return implode( ' ', $class_escaped );
	}

	/**
	 * Renders the header logo.
	 */
	public static function render() {
		$html         = '';
		$inner_html   = '';
		$logo_img_url = self::get_image_url();
		$logo_title   = self::get_text();

		if ( Sticky_Header::is_enabled() ) {
			$sticky_logo = Sticky_Header::get_logo_image_url();
		}

		// Get overlay/transparent header logo when enabled.
		if ( Overlay_Header::is_enabled() ) {
			$overlay_logo = Overlay_Header::logo_img();
		}

		// Define logo link attributes.
		$logo_link_attrs = [];

		$link = self::get_link_url();

		if ( $link ) {
			$logo_link_attrs['id'] = 'site-logo-link';
			$logo_link_attrs['href'] = self::get_link_url();
			$logo_link_attrs['rel']  = 'home';
		} else {
			$logo_link_attrs['id'] = 'site-logo-span';
		}

		// Display image logo.
		if ( ! empty( $logo_img_url ) || ! empty( $overlay_logo ) ) {

			// Define logo image attributes.
			$img_attrs = array(
				'src'            => esc_url( $logo_img_url ),
				'alt'            => $logo_title,
				'class'          => self::get_image_class(),
				'width'          => self::get_image_width(),
				'height'         => self::get_image_height(),
				'data-no-retina' => '',
				'data-skip-lazy' => '',
			);

			/**
			 * Change src to overlay logo if defined.
			 */
			if ( ! empty( $overlay_logo ) ) {
				$img_attrs['src'] = esc_url( $overlay_logo );
			}

			// Add retina logo if set.
			$retina_logo = self::get_retina_image_url();

			if ( $retina_logo ) {
				$img_attrs['srcset'] = $img_attrs['src'] . ' 1x,' . esc_url( $retina_logo ) . ' 2x';
			}

			if ( ! empty( $sticky_logo ) ) {
				$img_attrs['data-nonsticky-logo'] = '';
			}

			/**
			 * Filters the header logo image attributes.
			 *
			 * @param array $img_attrs
			 */
			$img_attrs = (array) apply_filters( 'wpex_header_logo_img_attrs', $img_attrs );

			// Standard logo html.
			$img_html = '<img ' . wpex_parse_attrs( $img_attrs ) . '>';

			// Sticky logo html.
			if ( ! empty( $sticky_logo ) ) {

				$sticky_img_attrs = array(
					'src'              => esc_url( $sticky_logo ),
					'alt'              => $img_attrs['alt'],
					'class'            => $img_attrs['class'],
					'width'            => Sticky_Header::get_logo_image_width(),
					'height'           => Sticky_Header::get_logo_image_height(),
					'data-no-retina'   => '',
					'data-skip-lazy'   => '',
					'data-sticky-logo' => '',
				);

				if ( $sticky_logo_retina = Sticky_Header::get_retina_logo_image_url() ) {
					$sticky_img_attrs['srcset'] = $sticky_img_attrs['src'] . ' 1x,' . esc_url( $sticky_logo_retina ) . ' 2x';
				}

				$img_html .= '<img ' . wpex_parse_attrs( $sticky_img_attrs ) . '>';
			}

			/**
			 * Custom header-overlay logo.
			 *
			 * @todo update to have new wpex_header_logo_link_class() so we don't have to write dup html here.
			 */
			if ( ! empty( $overlay_logo ) ) {
				$logo_link_attrs['class'] = 'overlay-header-logo';
			}

			// Standard site-wide image logo.
			elseif ( ! empty( $logo_img_url ) ) {
				$logo_link_attrs['class'] = 'main-logo';
			}

			/**
			 * Filters the header logo img html.
			 *
			 * @param string $html.
			 */
			$img_html = apply_filters( 'wpex_header_logo_img_html', $img_html );

			// Add image to inner html.
			$inner_html = $img_html;

		}

		// Display text logo.
		else {

			// Add logo link class for text based logo.
			$logo_link_attrs['class'] = self::get_text_class();

			// Add logo icon to inner html.
			$inner_html .= self::get_icon();

			// Add logo text to inner html.
			$inner_html .= do_shortcode( wp_strip_all_tags( $logo_title ) );

		}

		/**
		 * Filters the header logo link attributes.
		 *
		 * @param array $attributes.
		 */
		$logo_link_attrs = (array) apply_filters( 'wpex_header_logo_link_attrs', $logo_link_attrs );

		// Final html output.
		$html_tag = $link ? 'a' : 'span';
		$html = wpex_parse_html( $html_tag, $logo_link_attrs, $inner_html );

		/**
		 * Filters the header logo output.
		 *
		 * @param string $html
		 */
		echo (string) apply_filters( 'wpex_header_logo_output', $html );
	}

	/**
	 * Return logo wrapper classes.
	 *
	 * Provides a fallback for the older wpex_header_logo_classes() function.
	 *
	 * @todo deprecate
	 */
	public static function get_wrapper_classes() {
		$header_style    = Header::style();
		$has_flex_header = Header::has_flex_container();

		$classes = array(
			'site-branding',
		);

		// Default class.
		$classes[] = 'header-' . sanitize_html_class( $header_style ) . '-logo';

		// Supports vertical padding.
		if ( ! in_array( $header_style, array( 'seven', 'eight', 'nine', 'ten', 'six' ) ) ) {
			$classes[] = 'logo-padding';
		}

		/* Utility Classes */

		// Flex and none flex classes.
		if ( $has_flex_header ) {
			$classes[] = 'wpex-flex';
			$classes[] = 'wpex-items-center';
			$classes[] = 'wpex-h-100';
		} else {
			$classes[] = 'wpex-table';
		}

		// Custom class added for the overlay header when set via the Theme Settings metabox.
		if ( wpex_has_post_meta( 'wpex_overlay_header' )
			&& Overlay_Header::is_enabled()
			&& Overlay_Header::logo_img()
		) {
			$classes[] = 'has-overlay-logo';
		}

		// Scroll top.
		if ( self::has_scroll_top_link() ) {
			$classes[] = 'wpex-scroll-top';
		}

		/**
		 * Filters the header logo classes.
		 *
		 * @param array $classes
		 */
		$classes = (array) apply_filters( 'wpex_header_logo_classes', $classes );

		$class_escaped = array_map( 'esc_attr', $classes );

		return implode( ' ', $class_escaped );
	}

	/**
	 * Echo logo wrapper class.
	 */
	public static function wrapper_class() {
		$classes = self::get_wrapper_classes();
		if ( $classes ) {
			echo 'class="' . esc_attr( $classes ) . '"';
		}
	}

	/**
	 * Echo logo inner class.
	 */
	public static function inner_class() {
		$has_flex_header = Header::has_flex_container();
		$classes         = array();

		if ( ! $has_flex_header ) {
			$classes[] = 'wpex-table-cell';
			$classes[] = 'wpex-align-middle';
			$classes[] = 'wpex-clr';
		}

		/**
		 * Filters the header logo inner classes.
		 *
		 * @param array $class
		 */
		$classes = (array) apply_filters( 'wpex_header_logo_inner_class', $classes );

		if ( $classes ) {
			echo 'class="' . esc_attr( implode( ' ', $classes ) ) . '"';
		}
	}

	/**
	 * Parses the logo img.
	 */
	private static function parse_image( $image = '' ) {
		return wpex_get_image_url( $image );
	}

}