<?php

namespace BwWinner;

class Product_Shortcodes {

	public function __construct () {
		add_action( 'wp_enqueue_scripts', array( $this, 'register_assets' ) );

		add_shortcode( 'bw-product-superheading', array( $this, 'product_superheading_shortcode' ) );
		add_shortcode( 'bw-product-heading', array( $this, 'product_heading_shortcode' ) );
		add_shortcode( 'bw-product-links', array( $this, 'product_links_shortcode' ) );
		add_shortcode( 'bw-product-subheading', array( $this, 'product_subheading_shortcode' ) );
		add_shortcode( 'bw-product-description', array( $this, 'product_description_shortcode' ) );
		add_shortcode( 'bw-product-miscellaneous', array( $this, 'product_miscellaneous_shortcode' ) );
		add_shortcode( 'bw-product-video', array( $this, 'product_video_shortcode' ) );
		add_shortcode( 'bw-product-individual-awards', array( $this, 'product_individual_awards_shortcode' ) );
		add_shortcode( 'award', array( $this, 'award_badge_shortcode' ) );
	}

	/**
	 * Renders the tiered award badge anywhere via a shortcode, e.g. [award=96].
	 *
	 * Identical to the badges in the Winners tables (icons/Award.jsx): a gold disc
	 * with the score for Gold, two overlapping gold discs for Double Gold, and
	 * silver-/bronze-coloured discs for those tiers. The score is mapped to a tier
	 * using the per-site "Display Score As" thresholds
	 * (bw_winners_options.displayScoreAs). Scores below the Bronze threshold render
	 * nothing, exactly like the tables.
	 *
	 * WordPress parses `[award=96]` with the leading "=96" landing in the first
	 * positional attribute (atts[0] === '=96'), so we strip a leading "=" as well
	 * as supporting the `score`/positional forms.
	 *
	 * Accepts:
	 *   [award=96]          (the requested syntax)
	 *   [award score=96]    (explicit attribute)
	 *   [award 96]          (positional)
	 *   [award=96 size=64]  (disc height in px; default 2em, matching the tables)
	 */
	public function award_badge_shortcode ( $atts ) {
		$atts = (array) $atts;

		$score = '';
		if ( isset( $atts['score'] ) ) {
			$score = $atts['score'];
		} elseif ( isset( $atts['value'] ) ) {
			$score = $atts['value'];
		} elseif ( isset( $atts[0] ) ) {
			// Handles [award=96] (atts[0] === '=96') and [award 96] (atts[0] === '96').
			$score = ltrim( (string) $atts[0], '= ' );
		}

		$score = (int) $score;
		if ( $score <= 0 ) {
			return '';
		}

		// Disc height: explicit px via size=, else 2em to match the Winners tables.
		$height = isset( $atts['size'] ) ? max( 16, (int) $atts['size'] ) . 'px' : '2em';

		// Per-site score thresholds (Winners Settings -> Display Score As), with the
		// historical hardcoded fallbacks used elsewhere in the template.
		$opts = get_option( 'bw_winners_options', array() );
		$sa   = isset( $opts['displayScoreAs'] ) && is_array( $opts['displayScoreAs'] ) ? $opts['displayScoreAs'] : array();
		$dg   = isset( $sa['doubleGold'] ) ? (int) $sa['doubleGold'] : 95;
		$g    = isset( $sa['gold'] )       ? (int) $sa['gold']       : 90;
		$s    = isset( $sa['silver'] )     ? (int) $sa['silver']     : 85;
		$b    = isset( $sa['bronze'] )     ? (int) $sa['bronze']     : 80;

		// Tier colours match icons/Award.jsx: [stroke/text, fill, shadow].
		$gold   = array( '#f7e259', '#eda140', '#c26a34' );
		$silver = array( '#ccc', '#999', '#666' );
		$bronze = array( '#b74', '#842', '#542' );

		$wrap = 'display:inline-flex;justify-content:space-around;vertical-align:middle;line-height:0;';

		if ( $score >= $dg ) {
			$label = sprintf( 'Double Gold award, score %d', $score );
			$discs = $this->award_disc_svg( '', $gold, $height, 'transform:translate(85%,0);' )
			       . $this->award_disc_svg( $score, $gold, $height, 'transform:translate(-85%,0);' );
			return '<span class="apn-award-badge apn-award-badge--double-gold" role="img" aria-label="' . esc_attr( $label ) . '" style="' . esc_attr( $wrap ) . '">' . $discs . '</span>';
		} elseif ( $score >= $g ) {
			$colors = $gold;   $tier = 'Gold';
		} elseif ( $score >= $s ) {
			$colors = $silver; $tier = 'Silver';
		} elseif ( $score >= $b ) {
			$colors = $bronze; $tier = 'Bronze';
		} else {
			return ''; // below Bronze -> no badge, same as the Winners tables
		}

		$label = sprintf( '%s award, score %d', $tier, $score );
		return '<span class="apn-award-badge apn-award-badge--' . strtolower( $tier ) . '" role="img" aria-label="' . esc_attr( $label ) . '" style="' . esc_attr( $wrap ) . '">'
			. $this->award_disc_svg( $score, $colors, $height )
			. '</span>';
	}

	/**
	 * One award disc SVG, ported from icons/Award.jsx in the winners-table block so
	 * the shortcode badge is pixel-identical to the Winners tables.
	 *
	 * @param int|string $score       Score to show; '' renders an empty disc (Double Gold back disc).
	 * @param array      $colors      [stroke/text colour, fill colour, shadow colour].
	 * @param string     $height      CSS height for the <svg> (e.g. '2em' or '64px').
	 * @param string     $extra_style Extra inline CSS (e.g. a transform).
	 */
	private function award_disc_svg ( $score, $colors, $height = '2em', $extra_style = '' ) {
		static $seq = 0;
		$seq++;
		$id1 = 'bwaw' . $seq . 'a';
		$id2 = 'bwaw' . $seq . 'b';
		$id3 = 'bwaw' . $seq . 'c';

		list( $c1, $c2, $c3 ) = $colors; // stroke/text, fill, shadow
		$num   = ( $score === '' ) ? '' : (string) (int) $score;
		$style = 'height:' . $height . ';' . $extra_style;

		return sprintf(
			'<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="%s">'
				. '<circle cx="50" cy="50" r="38" filter="url(#%s)" fill="%s"/>'
				. '<circle cx="50" cy="50" r="44" filter="url(#%s)" fill="none" stroke="%s" stroke-width="12"/>'
				. '<text x="50" y="53" text-anchor="middle" dominant-baseline="middle" filter="url(#%s)" fill="%s" style="font:700 40px sans-serif;">%s</text>'
				. '<filter id="%s">'
					. '<feOffset/>'
					. '<feGaussianBlur stdDeviation="1" result="offset-blur"/>'
					. '<feComposite operator="out" in="SourceGraphic" in2="offset-blur" result="inverse"/>'
					. '<feFlood flood-color="%s" flood-opacity="0.95" result="color"/>'
					. '<feComposite operator="in" in="color" in2="inverse" result="shadow"/>'
					. '<feComposite in="shadow" in2="SourceGraphic"/>'
				. '</filter>'
				. '<filter id="%s" color-interpolation-filters="sRGB">'
					. '<feGaussianBlur stdDeviation="0.85"/>'
					. '<feOffset dx="0.5" dy="0.5" result="shadow"/>'
					. '<feFlood flood-color="%s" flood-opacity="0.95" result="color"/>'
					. '<feComposite operator="in" in="color" in2="shadow" result="shadow2"/>'
					. '<feComposite in="SourceGraphic" in2="shadow2"/>'
				. '</filter>'
				. '<filter id="%s" x="-25%%" y="-25%%" width="150%%" height="150%%">'
					. '<feOffset in="SourceAlpha" dx="0.16666666666666666" dy="0.8333333333333334" result="o1"/>'
					. '<feGaussianBlur stdDeviation="0.5" in="o1" result="b1"/>'
					. '<feSpecularLighting specularConstant="0.9" specularExponent="15" in="b1" result="s1"><fePointLight x="-1000" y="-5000" z="300"/></feSpecularLighting>'
					. '<feComposite in="s1" in2="SourceAlpha" operator="in" result="cc1"/>'
					. '<feOffset in="SourceAlpha" dx="-0.16666666666666666" dy="-0.8333333333333334" result="o2"/>'
					. '<feGaussianBlur stdDeviation="0.5" in="o2" result="b2"/>'
					. '<feSpecularLighting specularConstant="1.8" specularExponent="8" in="b2" result="s2"><fePointLight x="100" y="5000" z="300"/></feSpecularLighting>'
					. '<feComposite in="s2" in2="SourceAlpha" operator="in" result="cc2"/>'
					. '<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .85 0" in="cc2" result="m1"/>'
					. '<feComposite k2="0.8" k3="0.5" in="cc1" in2="m1" operator="arithmetic" result="cc3"/>'
					. '<feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="cc3"/></feMerge>'
				. '</filter>'
			. '</svg>',
			esc_attr( $style ),
			$id1, esc_attr( $c2 ),
			$id3, esc_attr( $c1 ),
			$id2, esc_attr( $c1 ), esc_html( $num ),
			$id1, esc_attr( $c3 ),
			$id2, esc_attr( $c3 ),
			$id3
		);
	}

	public function register_assets () {
		wp_register_style( 'product_shortcode_styles', PLUGIN_URL . 'assets/css/product-shortcode-styles.css', array(), '0.0.5' );
	}

	public function product_superheading_shortcode ($atts) {

		global $bw_winners;

		$product_id = get_the_ID();

		$logo_id = get_field( 'brand_logo' );

		$brand_link = get_field( 'brand_link' );
		$brand_link = false;
		$company_link = get_field( 'company_link' );
		$company_link = false;

		$product = $bw_winners->entities->get_product( $product_id );
		if ( ! $product ) return '';
		wp_enqueue_style( 'product_shortcode_styles' );


		$brand = $bw_winners->entities->get_brand( $product['brand_id'] );
		$company = $bw_winners->entities->get_company( $product['company_id'] );


		$brand_name = $brand['name'];
		$company_name = $company['name'];


		ob_start();
		?>
			<div class="bw-winners-superheading_shortcode">
				<?php if ( $logo_id && $logo = wp_get_attachment_image( $logo_id, 'medium' ) ) : ?>
					<div class="bw-winners-brand-logo">
						<?php echo $logo; ?>
					</div>
				<?php endif; ?>
				<h2 class="bw-winners-brand-heading">
					<?php if ( $brand_link ) : ?><a href="<?php echo $brand_link; ?>" rel="nofollow" target="_blank"><?php endif; ?>
						<?php echo $brand_name; ?>
					<?php if ( $brand_link ) : ?></a><?php endif; ?>
					<span class="bw-dash">&nbsp;&nbsp;&horbar;&nbsp;&nbsp;</span>
					<?php if ( $company_link ) : ?><a href="<?php echo $company_link; ?>" rel="nofollow" target="_blank"><?php endif; ?>
						<?php echo $company_name; ?>
					<?php if ( $company_link ) : ?></a><?php endif; ?>
				</h2>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_heading_shortcode ($atts) {

		global $bw_winners;

		$product_id = get_the_ID();

		$product_link = get_field( 'product_link' );
		$product_link = false;

		$product = $bw_winners->entities->get_product( $product_id );
		if ( ! $product ) return '';
		wp_enqueue_style( 'product_shortcode_styles' );

		$product_name = $product['name'];

		ob_start();
		?>
			<div class="bw-winners-product_heading_shortcode">
				<h1 class="bw-winners-brand-heading">
					<?php if ( $product_link ) : ?><a href="<?php echo $product_link; ?>" rel="nofollow" target="_blank"><?php endif; ?>
						<?php echo $product_name; ?>
					<?php if ( $product_link ) : ?></a><?php endif; ?>
				</h1>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_links_shortcode ($atts) {

		global $bw_winners;


		$atts = shortcode_atts( array(
			'company_link_text' => 'Company'
		), $atts, 'bartag' );


		$product_id = get_the_ID();

		$product = $bw_winners->entities->get_product( $product_id );
		if ( ! $product ) return '';

		$brand = $bw_winners->entities->get_brand( $product['brand_id'] );

		$brand_name = $brand['name'];

		$company_link = get_field( 'company_link' );
		$brand_link = get_field( 'brand_link' );
		$product_link = get_field( 'product_link' );

		$has_link = $brand_link || $company_link || $product_link;

		if ( ! $has_link ) return '';
		wp_enqueue_style( 'product_shortcode_styles' );

		ob_start();
		?>
			<div class="bw-winners-product_links_shortcode">
				<?php if ( $company_link ) : ?>
					<span>
						<a href="<?php echo $company_link; ?>" rel="nofollow" target="_blank">
							<?php echo $atts['company_link_text']; ?>			
						</a>
					</span>
				<?php endif; ?>
				<?php if ( $brand_link ) : ?>
					<span>
						<a href="<?php echo $brand_link; ?>" rel="nofollow" target="_blank">
							<i>
								<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="currentColor" version="1.1" id="Capa_1" width="800px" height="800px" viewBox="0 0 466.337 466.337" xml:space="preserve" style="height: 1em;width: 1em;">
									<g>
										<path d="M233.168,0C104.604,0,0,104.604,0,233.168c0,128.565,104.604,233.169,233.168,233.169   c128.565,0,233.169-104.604,233.169-233.169C466.337,104.604,361.733,0,233.168,0z M223.984,441.874   c-22.321,0-46.405-41.384-59.045-107.815h118.067C270.371,400.49,246.316,441.874,223.984,441.874z M161.114,310.144   c-2.738-19.991-4.437-41.781-4.881-65.018H291.74c-0.443,23.237-2.148,45.027-4.869,65.018H161.114z M24.521,245.126h107.704   c0.443,21.883,2.09,43.859,4.887,65.018H38.768C30.693,289.826,25.818,267.966,24.521,245.126z M223.984,24.464   c21.982,0,45.687,40.14,58.484,104.877h-116.97C178.286,64.604,201.996,24.464,223.984,24.464z M286.463,153.245   c2.978,20.785,4.811,43.596,5.277,67.966H156.222c0.467-24.37,2.295-47.169,5.272-67.966H286.463z M132.226,221.211H24.521   c1.354-23.926,6.568-46.836,15.332-67.966h97.656C134.462,175.32,132.681,198.312,132.226,221.211z M315.749,245.126h126.065   c-1.296,22.84-6.188,44.7-14.246,65.018H310.855C313.646,288.985,315.305,267.009,315.749,245.126z M315.749,221.211   c-0.468-22.898-2.254-45.891-5.29-67.966h116.023c8.77,21.13,13.978,44.04,15.332,67.966H315.749z M414.596,129.33H306.617   c-7.894-42.067-20.727-78.844-38.195-102.222C330.952,37.799,384.06,76.205,414.596,129.33z M176.073,32.036   c-15.7,23.459-27.348,58.1-34.699,97.305H51.741C78.657,82.505,123.064,47.1,176.073,32.036z M49.96,334.058h90.895   c7.311,40.403,19.133,76.205,35.219,100.26C121.944,418.904,76.672,382.378,49.96,334.058z M268.41,439.222   c17.865-23.938,30.874-61.889,38.697-105.164h109.274C386.15,388.743,332.12,428.339,268.41,439.222z"/>
									</g>
								</svg>
							</i>
							Visit the <?php echo $brand_name; ?> Website			
						</a>
					</span>
				<?php endif; ?>
				<?php if ( $product_link ) : ?>
					<span>
						<a href="<?php echo $product_link; ?>" rel="nofollow" target="_blank">
							Visit the Product Page			
						</a>
					</span>
				<?php endif; ?>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_subheading_shortcode ($atts) {
		$atts = shortcode_atts( array(
			'local' => 'en_US',
			'currency' => 'USD'
		), $atts, 'bartag' );

		$fmt = new \NumberFormatter( $atts['local'], \NumberFormatter::CURRENCY );


		$retail_price = get_field( 'retail_price' );
		$purchase_link = get_field( 'purchase_link' );

		if ( empty( $purchase_link ) && empty( $retail_price ) ) {
			return '';
		}
		wp_enqueue_style( 'product_shortcode_styles' );

		ob_start();
		?>
			<div class="bw-winners-product_subheading_shortcode">
				<?php if ( $retail_price ) : ?>
					<div>
						<?php echo $fmt->formatCurrency( $retail_price, $atts['currency'] ); ?>
					</div>
				<?php endif; ?>
				<?php if ( $purchase_link ) : ?>
					<div>
						<a class="button button-size-small" href="<?php echo $purchase_link; ?>" rel="nofollow" target="_blank">
							Purchase Online
						</a>
					</div>
				<?php endif; ?>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_description_shortcode ($atts) {

		if ( ! is_singular( 'bw-product' ) ) return '';

		wp_enqueue_style( 'product_shortcode_styles' );

		ob_start();
		?>
			<div class="bw-winners-product_description_shortcode">
				<div class="bw-winners-tasting-notes">
					<?php the_content(); ?>
				</div>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_miscellaneous_shortcode ($atts) {

		$elements = array();

		// APV
		$alcohol_by_volume = get_field( 'alcohol_by_volume' );
		if ( $alcohol_by_volume != false ) {
			$elements[] = "<div>{$alcohol_by_volume}% Alcohol By Volume</div>";
		}

		if ( empty( $elements ) ) {
			return '';
		}
		wp_enqueue_style( 'product_shortcode_styles' );

		ob_start();
		?>
			<div class="bw-winners-product_miscellaneous_shortcode">
				<?php echo implode( '', $elements ); ?>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_video_shortcode ($atts) {
		$video_link = get_field( 'video_link' );

		if ( empty( $video_link ) ) {
			return '';
		}
		wp_enqueue_style( 'product_shortcode_styles' );

		ob_start();
		?>
			<div class="bw-winners-product_video_shortcode">
				<?php echo wp_video_shortcode( array(
					'src' => $video_link,
					'height' => 720,
					'width' => 1280
				) ); ?>
			</div>
		<?php

		return ob_get_clean();
	}

	public function product_individual_awards_shortcode ($atts) {

		$individual_awards = get_field( 'individual_awards' );
		if ( ! $individual_awards ) return '';

		ob_start();
		?>
			<div class="bw-winners-product_individual_awards_shortcode">
				<?php echo $individual_awards; ?>
			</div>
		<?php

		return ob_get_clean();
	}
}
