<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
	wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), 103 );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles' );

/**
 * APN Hero Layers — Inject CSS custom properties for product/flare images.
 * Uses competition data from the main site CPT via the sync layer.
 */
add_action( 'wp_head', function() {
	if ( is_main_site() || ! class_exists( 'APN_Competition_Sync' ) ) {
		return;
	}

	$competition_id = APN_Competition_Sync::get_instance()->get_competition_for_current_site();
	if ( ! $competition_id ) {
		return;
	}

	switch_to_blog( 1 );

	$product_id    = get_post_meta( $competition_id, 'product_image', true );
	$flare_id      = get_post_meta( $competition_id, 'flare_image', true );
	$primary_color = get_post_meta( $competition_id, 'primary_color', true );

	$product_url = $product_id ? wp_get_attachment_image_url( $product_id, 'large' ) : '';
	$flare_url   = $flare_id ? wp_get_attachment_url( $flare_id ) : '';

	restore_current_blog();

	if ( ! $product_url && ! $flare_url && ! $primary_color ) {
		return;
	}

	echo "<style id=\"apn-hero-layers\">\n:root {\n";
	if ( $product_url ) {
		echo "  --apn-product-image: url('" . esc_url( $product_url ) . "');\n";
	}
	if ( $flare_url ) {
		echo "  --apn-flare-image: url('" . esc_url( $flare_url ) . "');\n";
	}
	if ( $primary_color ) {
		echo "  --apn-brand-color: " . esc_attr( $primary_color ) . ";\n";
	}
	echo "}\n</style>\n";
}, 5 );

/**
 * APN Hero Layers — Enqueue CSS and JS for .product-image and .flare classes.
 */
add_action( 'wp_enqueue_scripts', function() {
	if ( is_main_site() ) {
		return;
	}

	// CSS for layers
	wp_register_style( 'apn-hero-layers', false, [], '1.0.0' );
	wp_enqueue_style( 'apn-hero-layers' );
	wp_add_inline_style( 'apn-hero-layers', '
/* =============================================
   APN Layers - Shared
   ============================================= */
[class*="product-image-"] { position: relative; }
[class*="flare"] { position: relative; }

/* Content and dividers stay above layers */
[class*="product-image-"] > .kt-row-column-wrap,
[class*="flare"] > .kt-row-column-wrap {
  position: relative;
  z-index: 3;
}
[class*="product-image-"] > .kt-row-layout-bottom-sep,
[class*="product-image-"] > .kt-row-layout-top-sep,
[class*="flare"] > .kt-row-layout-bottom-sep,
[class*="flare"] > .kt-row-layout-top-sep {
  z-index: 4;
}

/* =============================================
   APN Layers - Product Image
   ============================================= */
.product-image-bottom::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 500px;
  height: 50%;
  background-image: var(--apn-product-image, none);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center calc(100% + 30px);
  pointer-events: none;
  z-index: 2;
}

/* Slide-up animation */
.product-image-slide-up::after {
  transform: translateX(-50%) translateY(20%);
  opacity: 0;
  transition: transform 0.8s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.6s ease;
}
.product-image-slide-up.apn-visible::after {
  transform: translateX(-50%) translateY(0);
  opacity: 1;
}

/* =============================================
   APN Layers - Flare (injected via JS)
   ============================================= */
.apn-flare {
  position: absolute;
  width: 20%;
  height: 60%;
  background-color: var(--apn-brand-color, currentColor);
  -webkit-mask-image: var(--apn-flare-image, none);
  mask-image: var(--apn-flare-image, none);
  -webkit-mask-size: contain;
  mask-size: contain;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-position: center bottom;
  mask-position: center bottom;
  pointer-events: none;
  z-index: 1;
  opacity: 0.8;
}

/* Flare positions */
.apn-flare--center        { bottom: 0; left: 50%; transform: translateX(-50%); width: 30%; height: 70%; }
.apn-flare--bottom-left   { bottom: 5%; left: 5%; }
.apn-flare--bottom-right  { bottom: 5%; right: 5%; transform: scaleX(-1); }
.apn-flare--mid-left      { bottom: 5%; left: 13%; }
.apn-flare--mid-right     { bottom: 5%; right: 13%; transform: scaleX(-1); }

/* Float animation - each position gets offset timing */
.flare-float .apn-flare--center       { animation: apn-float-a 8s ease-in-out infinite; }
.flare-float .apn-flare--bottom-left  { animation: apn-float-a 7s ease-in-out infinite; }
.flare-float .apn-flare--mid-left     { animation: apn-float-a 7s ease-in-out infinite; }
.flare-float .apn-flare--bottom-right { animation: apn-float-b 9s ease-in-out infinite; }
.flare-float .apn-flare--mid-right    { animation: apn-float-b 9s ease-in-out infinite; }

@keyframes apn-float-a {
  0%, 100% { transform: translateY(0); }
  40% { transform: translateY(-12px); }
  70% { transform: translateY(5px); }
}
@keyframes apn-float-b {
  0%, 100% { transform: scaleX(-1) translateY(0); }
  30% { transform: scaleX(-1) translateY(6px); }
  65% { transform: scaleX(-1) translateY(-10px); }
}
	' );

	// JS for intersection observer + flare injection
	wp_register_script( 'apn-hero-layers', '', [], '1.0.0', true );
	wp_enqueue_script( 'apn-hero-layers' );
	wp_add_inline_script( 'apn-hero-layers', '
(function() {
  /* Slide-up: IntersectionObserver trigger */
  var slideTargets = document.querySelectorAll(".product-image-slide-up");
  if (slideTargets.length) {
    if ("IntersectionObserver" in window) {
      var observer = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
          if (entry.isIntersecting) {
            entry.target.classList.add("apn-visible");
            observer.unobserve(entry.target);
          }
        });
      }, { threshold: 0.15 });
      slideTargets.forEach(function(el) { observer.observe(el); });
    } else {
      slideTargets.forEach(function(el) { el.classList.add("apn-visible"); });
    }
  }

  /* Flare: inject elements based on classes */
  var flareMap = {
    "flare":                  "center",
    "flare-bottom-left":      "bottom-left",
    "flare-bottom-right":     "bottom-right",
    "flare-bottom-mid-left":  "mid-left",
    "flare-bottom-mid-right": "mid-right"
  };

  var allFlare = document.querySelectorAll("[class*=flare]");
  allFlare.forEach(function(el) {
    Object.keys(flareMap).forEach(function(cls) {
      if (el.classList.contains(cls) && !el.querySelector(".apn-flare--" + flareMap[cls])) {
        var div = document.createElement("div");
        div.className = "apn-flare apn-flare--" + flareMap[cls];
        el.appendChild(div);
      }
    });
  });
})();
	' );
}, 20 );

function custom_theme_sidebars() {

	// Register the About sidebar
	register_sidebar(
		array(
			'name' => __( 'About', 'custom-theme' ),
			'id' => 'sidebar-about',
			'description' => __( 'The sidebar for the About page.', 'custom-theme' ),
			'before_widget' => '<div class="widget">',
			'after_widget' => '</div>',
			'before_title' => '<h2 class="widget-title">',
			'after_title' => '</h2>'
		)
	);

	// Register the Services sidebar
	register_sidebar(
		array(
			'name' => __( 'Services', 'custom-theme' ),
			'id' => 'sidebar-where-we-work',
			'description' => __( 'The sidebar for the Services page.', 'custom-theme' ),
			'before_widget' => '<div class="widget">',
			'after_widget' => '</div>',
			'before_title' => '<h2 class="widget-title">',
			'after_title' => '</h2>'
		)
	);

	// Register the Support sidebar
	register_sidebar(
		array(
			'name' => __( 'Support', 'custom-theme' ),
			'id' => 'sidebar-support',
			'description' => __( 'The sidebar for the Support page.', 'custom-theme' ),
			'before_widget' => '<div class="widget">',
			'after_widget' => '</div>',
			'before_title' => '<h2 class="widget-title">',
			'after_title' => '</h2>'
		)
	);

		// Register the Blog sidebar
	register_sidebar(
		array(
			'name' => __( 'Blog', 'custom-theme' ),
			'id' => 'sidebar-blog',
			'description' => __( 'The sidebar for the blog index and single blog.', 'custom-theme' ),
			'before_widget' => '<div class="widget">',
			'after_widget' => '</div>',
			'before_title' => '<h2 class="widget-title">',
			'after_title' => '</h2>'
		)
	);
}
add_action( 'widgets_init', 'custom_theme_sidebars' );

function custom_enter_title_here( $title ) {
	$screen = get_current_screen();

	// Check if the current post type is 'winner'
	if ( 'winner' == $screen->post_type ) {
		$title = 'Add product name';
	}

	return $title;
}
add_filter( 'enter_title_here', 'custom_enter_title_here' );

/* Only shortcode to write comment on blockeditor using shortcode */
function wpb_editor_only_comment_shortcode( $atts, $content = null ) {
	// If the current user can edit posts, show the comment
	if ( current_user_can( 'edit_posts' ) ) {
		return '<div class="editor-comment" style="display: none;">' . $content . '</div>';
	}
	// Return nothing for public
	return '';
}

add_shortcode( 'comment', 'wpb_editor_only_comment_shortcode' );



/* Retrieve posts from RSS */

function bw_fetch_rss_feed($atts) {
	// Default attributes
	$atts = shortcode_atts(
		array(
			'source' => '',    // Default source
			'number' => 4,     // Default number of items to show
			'columns' => 2,    // Default number of columns
		), 
		$atts
	);

	// Fetch the RSS feed
	$rss = fetch_feed($atts['source']);

	// Check for errors
	if (is_wp_error($rss)) {
		return '<p>Unable to fetch RSS feed.</p>';
	}

	// Get the specified number of items
	$maxitems = $rss->get_item_quantity($atts['number']);
	$rss_items = $rss->get_items(0, $maxitems);

	// Start the grid container
	ob_start();
	?>
	<style>
		.bw-rss-grid {
			display: grid;
			grid-template-columns: repeat(<?php echo intval($atts['columns']); ?>, 1fr);
			gap: 20px;
		}
		.bw-rss-item {
			background-color: #f0f0f0; /* Light grey background */
			/* border: 1px solid #ddd;  Grey border */
			padding: 25px;
			box-shadow: 0 2px 5px rgba(0,0,0,0.1); /* Optional: Adds a subtle shadow to each item */
			overflow: hidden; /* Ensure the overflow from children elements is hidden */
		}
		.bw-rss-image {
			width: 100%; /* Full width of the container */
			padding-top: 56.25%; /* 16:9 aspect ratio */
			position: relative; /* For absolute positioning of the image */
			background-color: #333; /* Fallback color */
			overflow: hidden; /* Hide overflow to maintain aspect ratio */
		}
		.bw-rss-image img {
			position: absolute;
			top: 50%;
			left: 50%;
			width: 100%;
			height: auto;
			transform: translate(-50%, -50%);
			object-fit: cover; /* Cover the area, cropping as needed */
		}
		.bw-rss-button {
			display: inline-block;
			margin-top: 10px;
			padding: 10px 20px;
			background-color: #333; /* Dark background for the button */
			color: #fff; /* White text color */
			text-decoration: none;
			border-radius: 5px;
			font-weight: 500;
			padding: 10px 30px 10px 30px;
		}
		.bw-rss-button:hover {
			background-color: #910439; /* Dark background for the button */
			color: #fff; /* White text color */
		}
	</style>
	<div class="bw-rss-grid">
		<?php
		if ($maxitems == 0) {
			echo '<p>No items to display.</p>';
		} else {
			foreach ($rss_items as $item) {
				// Try to find the image URL in the feed
				$image_url = '';
				if ($enclosure = $item->get_enclosure()) {
					// Get the image URL from the enclosure
					$image_url = $enclosure->get_link();
				}
				?>
				<div class="bw-rss-item">
					<?php if ($image_url) : ?>
						<a target="_blank" href="<?php echo esc_url($item->get_permalink()); ?>">
							<div class="bw-rss-image">
								<img src="<?php echo esc_url($image_url); ?>" alt="Featured Image">
							</div>
						</a>
					<?php endif; ?>
					<a target="_blank" href="<?php echo esc_url($item->get_permalink()); ?>">
						<h3 class="bw-rss-title"><?php echo esc_html($item->get_title()); ?></h3>
					</a>
					<div class="bw-rss-excerpt">
						<?php echo wp_kses_post($item->get_description()); ?>
					</div>
					<a class="bw-rss-button" target="_blank" href="<?php echo esc_url($item->get_permalink()); ?>">Read More</a>
				</div>
				<?php
			}
		}
		?>
	</div>
	<?php
	
	// Return the content to be displayed by the shortcode
	return ob_get_clean();
}

// Register the shortcode with WordPress
add_shortcode('bw_rss_feed', 'bw_fetch_rss_feed');

$asset_settings = include plugin_dir_path( __FILE__ ) . 'build/blocks/rrs-feed-grid/index.asset.php';
register_block_type(
	plugin_dir_path( __FILE__ ) . 'build/blocks/rrs-feed-grid',
	array(
		'render_callback' => 'bw_fetch_rss_feed_block',
	)
);

function bw_fetch_rss_feed_block ( $block_attributes, $content ) {
	// Create attributes string
	$attributes = implode(' ', array_map( function ($key, $value) {
		return "{$key}=\"{$value}\"";
	}, array_keys($block_attributes), $block_attributes));
	// Do the shortcode
	return do_shortcode("[bw_rss_feed {$attributes}]");
}

/* BW Author block — dropdown to navigate to an author archive. */
register_block_type(
	plugin_dir_path( __FILE__ ) . 'build/blocks/bw-author',
	array(
		'render_callback' => 'bw_author_block_render',
	)
);

function bw_author_block_render( $attributes ) {
	$args = array(
		'orderby' => 'display_name',
		'order'   => 'ASC',
	);

	if ( ! empty( $attributes['roles'] ) && is_array( $attributes['roles'] ) ) {
		$args['role__in'] = array_map( 'sanitize_key', $attributes['roles'] );
	}

	if ( ! empty( $attributes['includeIds'] ) && is_array( $attributes['includeIds'] ) ) {
		$args['include'] = array_map( 'intval', $attributes['includeIds'] );
	}

	if ( ! empty( $attributes['excludeIds'] ) && is_array( $attributes['excludeIds'] ) ) {
		$args['exclude'] = array_map( 'intval', $attributes['excludeIds'] );
	}

	$only_published = ! isset( $attributes['hasPublishedPosts'] ) || ! empty( $attributes['hasPublishedPosts'] );
	if ( $only_published ) {
		$args['has_published_posts'] = true;
	}

	$authors = get_users( $args );

	if ( empty( $authors ) ) {
		return '<p>No authors found.</p>';
	}

	$placeholder = isset( $attributes['placeholder'] ) && $attributes['placeholder'] !== ''
		? $attributes['placeholder']
		: 'Select an Author';

	$output  = '<div class="wp-block-bw-author">';
	$output .= '<select class="bw-author-dropdown" onchange="if(this.value) window.location.href=this.value;">';
	$output .= '<option value="">' . esc_html( $placeholder ) . '</option>';

	foreach ( $authors as $author ) {
		$url = get_author_posts_url( $author->ID );
		$output .= '<option value="' . esc_url( $url ) . '">' . esc_html( $author->display_name ) . '</option>';
	}

	$output .= '</select></div>';

	return $output;
}

add_action ('wp_head', function() {
	echo "
	<!-- Google Tag Manager -->
	<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
	new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
	j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
	'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
	})(window,document,'script','dataLayer','GTM-PX62VBMZ');</script>
	<!-- End Google Tag Manager -->
	";
});
add_action ('wp_body_open', function() {
	echo '
	<!-- Google Tag Manager (noscript) -->
	<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PX62VBMZ"
	height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
	<!-- End Google Tag Manager (noscript) -->
	';
});
add_shortcode('bw_logo_image', function() {

	$image = get_field('footer_logo');

	ob_start();
	?>
		<div class="wp-block-image">
			<figure class="aligncenter size-full" style="border-radius: 50%;">
				<?php if ($image) : ?>
					<?php echo wp_get_attachment_image($image['ID'], 'full'); ?>
				<?php else : ?>
					<?php
						$logo_id = get_theme_mod('custom_logo');
						if ($logo_id) {
							echo wp_get_attachment_image($logo_id, 'full');
						}
					?>
				<?php endif; ?>
			</figure>
		</div>
	<?php
	return ob_get_clean();
});

/* Merge secondary nav into mobile menu with proper Kadence toggles */
add_filter('wp_nav_menu_items', function($items, $args) {
	if ( ! in_array($args->theme_location, ['mobile', 'primary'], true) ) {
		return $items;
	}
	// Only append when rendering inside the mobile drawer
	if ( ! isset($args->menu_id) || $args->menu_id !== 'mobile-menu' ) {
		return $items;
	}
	if ( ! has_nav_menu('secondary') ) {
		return $items;
	}
	$secondary_html = wp_nav_menu([
		'theme_location' => 'secondary',
		'menu_id'        => 'mobile-menu',
		'container'      => false,
		'items_wrap'     => '%3$s',
		'echo'           => false,
		'show_toggles'   => true,
		'sub_arrows'     => false,
		'depth'          => 0,
	]);
	if ($secondary_html) {
		$items .= $secondary_html;
	}
	return $items;
}, 10, 2);

/* Auto-fill competition name for Gravity Forms hidden fields */
add_filter('gform_field_value_competition_name', function() {
	return get_bloginfo('name');
});
