<?php
/**
 * Single Livestream view (CPT: livestream) — mirrors brentwood.ca's
 * /livestreams/{id} page: a featured "stream" header with the banner image,
 * a click-to-play inline YouTube player, the start date, and a
 * recording-availability note.
 *
 * Rendered into the_content (like the page/post hero in brentwood-hero.php) so
 * it flows inside .entry-content. Kadence's own entry title is suppressed (see
 * the kadence_post_layout filter below) and re-rendered inside the card beneath
 * the player — the title/date/note sit BELOW the video, matching the live site.
 * The event LISTS (Upcoming/Completed/OnGoing) are a separate concern handled
 * by the bw/youtube-list block on the /live page.
 *
 * Reuses the youtube-list helpers (date formatting, icons) and the global
 * bw_youtube_id() normaliser from brentwood-hero.php. No plugin changes, no
 * DB writes.
 *
 * @package Kadence-Child
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Load the bw_yt_* helpers (date/icon) on demand — they normally only load
 * inside the youtube-list block's render.php.
 */
function bw_ls_load_helpers() {
	if ( ! function_exists( 'bw_yt_icon' ) ) {
		$helpers = get_stylesheet_directory() . '/blocks/youtube-list/helpers.php';
		if ( file_exists( $helpers ) ) {
			require_once $helpers;
		}
	}
}

/**
 * Build the featured livestream view markup for a single livestream post.
 *
 * @param WP_Post $post Livestream post.
 * @return string HTML (all values escaped).
 */
function bw_render_livestream( $post ) {
	bw_ls_load_helpers();

	$yt    = function_exists( 'bw_youtube_id' )
		? bw_youtube_id( (string) get_post_meta( $post->ID, 'ls_youtube_id', true ) )
		: trim( (string) get_post_meta( $post->ID, 'ls_youtube_id', true ) );
	$thumb = get_the_post_thumbnail_url( $post, 'full' );
	$start = get_post_meta( $post->ID, 'ls_start', true );
	$date  = function_exists( 'bw_yt_format_date' ) ? bw_yt_format_date( $start ) : '';
	$iso   = function_exists( 'bw_yt_utc_iso' ) ? bw_yt_utc_iso( $start ) : '';
	$title = wptexturize( get_the_title( $post ) );

	$has_icon = function_exists( 'bw_yt_icon' );
	$yt_icon  = $has_icon ? bw_yt_icon( 'youtube' ) : '';
	$cal_icon = $has_icon ? bw_yt_icon( 'calendar' ) : '';

	// Recording-availability note — same copy/logic as the list rows
	// (bw_yt_render_row): ls_no_recording = "live broadcast only".
	$norec = (string) get_post_meta( $post->ID, 'ls_no_recording', true );
	$note  = '1' === $norec
		? __( 'This is a live broadcast only; no post-event recording will be made available.', 'kadence-child' )
		: __( 'The recording of this event will be posted after the event has concluded and has been processed for upload.', 'kadence-child' );

	$img = $thumb
		? '<img class="bw-ls__poster-img" src="' . esc_url( $thumb ) . '" alt="" />'
		: '<span class="bw-ls__noimg" aria-hidden="true"></span>';

	$play = '<span class="bw-ls__play" aria-hidden="true">'
		. '<span class="bw-ls__play-bg"></span>'
		. '<span class="bw-ls__play-icon">' . $yt_icon . '</span>'
		. '</span>';

	$out = '<section class="bw-ls">';

	// Media: click-to-play poster when a recording/video id exists; otherwise a
	// static banner (e.g. an upcoming stream that hasn't been published yet).
	$out .= '<div class="bw-ls__player">';
	if ( '' !== $yt ) {
		$out .= '<button type="button" class="bw-ls__poster" data-yt="' . esc_attr( $yt ) . '" '
			. 'aria-label="' . esc_attr( sprintf( __( 'Play: %s', 'kadence-child' ), get_the_title( $post ) ) ) . '">'
			. $img . $play
			. '</button>';
	} else {
		$out .= '<div class="bw-ls__poster bw-ls__poster--noplay">' . $img . '</div>';
	}
	$out .= '</div>'; // .bw-ls__player

	// Title card (below the player) — mirrors the live site: a bordered box with
	// the event thumbnail (left, red accent line) and the title + date +
	// recording note (right). The page title lives here, not above the video.
	$card_img = $thumb
		? '<img class="bw-ls__card-img" src="' . esc_url( $thumb ) . '" alt="" loading="lazy" />'
		: '<span class="bw-ls__card-noimg" aria-hidden="true"></span>';

	$out .= '<div class="bw-ls__card">';
	$out .= '<div class="bw-ls__card-inner">';
	$out .= '<div class="bw-ls__card-media">' . $card_img . '</div>';
	$out .= '<div class="bw-ls__card-body">';
	$out .= '<h1 class="bw-ls__title">' . esc_html( $title ) . '</h1>';
	if ( '' !== $date ) {
		$out .= '<div class="bw-ls__date">'
			. '<span class="bw-ls__date-icon" aria-hidden="true">' . $cal_icon . '</span>'
			. '<span class="bw-ls__date-text"' . ( '' !== $iso ? ' data-utc="' . esc_attr( $iso ) . '"' : '' ) . '>'
			. esc_html( $date ) . '</span>'
			. '</div>';
	}
	$out .= '<div class="bw-ls__note">' . esc_html( $note ) . '</div>';
	$out .= '</div>'; // .bw-ls__card-body
	$out .= '</div>'; // .bw-ls__card-inner
	$out .= '</div>'; // .bw-ls__card

	// Event lists — integrated here so the single template alone reproduces the
	// live page (no separate Kadence Element needed). Reuses the bw/youtube-list
	// block: an Upcoming list and a Completed (recordings) list, each excluding
	// the stream you're currently watching (mirrors Laravel's exclude_id).
	$out .= bw_render_livestream_lists( $post );

	$out .= '</section>';

	return $out;
}

/**
 * Render the Upcoming + Completed event lists for the single livestream page by
 * reusing the bw/youtube-list block (one source of truth for the row markup,
 * AJAX search and pagination). The current stream is excluded from both lists.
 *
 * @param WP_Post $post Current livestream.
 * @return string HTML, or '' if block rendering is unavailable.
 */
function bw_render_livestream_lists( $post ) {
	if ( ! function_exists( 'render_block' ) ) {
		return '';
	}
	$exclude = array( (int) $post->ID );

	$lists = array(
		array(
			'heading'    => __( 'Upcoming Events', 'kadence-child' ),
			'scope'      => 'upcoming',
			'showSearch' => false,
		),
		array(
			'heading'    => __( 'Completed Events', 'kadence-child' ),
			'scope'      => 'completed',
			'showSearch' => true,
		),
	);

	$out = '<div class="bw-ls__lists">';
	foreach ( $lists as $cfg ) {
		$out .= render_block( array(
			'blockName'    => 'bw/youtube-list',
			'attrs'        => array(
				'heading'        => $cfg['heading'],
				'scope'          => $cfg['scope'],
				'perPage'        => 10,
				'exclude'        => $exclude,
				'showSearch'     => $cfg['showSearch'],
				'showPagination' => true,
			),
			'innerBlocks'  => array(),
			'innerHTML'    => '',
			'innerContent' => array(),
		) );
	}
	$out .= '</div>';

	return $out;
}

/**
 * Prepend the featured livestream view to the content on single livestream
 * pages. Priority 20 = after do_blocks/wpautop, so our markup is never
 * reprocessed (same approach as the hero filter).
 */
add_filter(
	'the_content',
	function ( $content ) {
		if ( is_admin() || ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}
		if ( ! is_singular( 'livestream' ) ) {
			return $content;
		}
		$post = get_post( get_queried_object_id() );
		if ( ! $post instanceof WP_Post ) {
			return $content;
		}
		// Hero is off by default on livestream (acf/load_value forces 'none');
		// when set it renders above the player. '' when unset, so unchanged.
		return bw_render_hero( $post ) . bw_render_livestream( $post ) . $content;
	},
	20
);

/**
 * Kadence empties its own featured-image area on single livestreams — the
 * banner is rendered inside the content (above), so suppress the duplicate.
 */
add_filter(
	'post_thumbnail_html',
	function ( $html, $post_id ) {
		if ( is_admin() || ! is_singular( 'livestream' ) || (int) get_queried_object_id() !== (int) $post_id ) {
			return $html;
		}
		return '';
	},
	10,
	2
);

/**
 * Suppress Kadence's own entry title on single livestreams. We re-render the
 * title inside the card below the video (see bw_render_livestream). Setting the
 * layout 'title' to a value that is neither 'normal' nor 'above' makes both
 * show_in_content_title() and show_hero_title() return false, so Kadence prints
 * no title above the content (single-entry.php gates the entry header on
 * show_in_content_title()).
 */
add_filter(
	'kadence_post_layout',
	function ( $layout ) {
		if ( is_array( $layout ) && is_singular( 'livestream' ) ) {
			$layout['title'] = 'hide';
		}
		return $layout;
	}
);

/**
 * Front-end assets for the single livestream view (style + click-to-play).
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		if ( ! is_singular( 'livestream' ) ) {
			return;
		}
		$dir = get_stylesheet_directory();
		$uri = get_stylesheet_directory_uri();

		if ( file_exists( $dir . '/assets/livestream.css' ) ) {
			wp_enqueue_style(
				'bw-livestream',
				$uri . '/assets/livestream.css',
				array(),
				filemtime( $dir . '/assets/livestream.css' )
			);
		}
		if ( file_exists( $dir . '/assets/livestream.js' ) ) {
			wp_enqueue_script(
				'bw-livestream',
				$uri . '/assets/livestream.js',
				array(),
				filemtime( $dir . '/assets/livestream.js' ),
				true
			);
		}

		// The integrated event lists reuse the bw/youtube-list block. Its style
		// is registered (on init) but only auto-enqueued when the block appears
		// in post content; we render it via render_block(), so enqueue the style
		// here (head, no FOUC) and the AJAX view script (footer) explicitly.
		if ( wp_style_is( 'bw-youtube-list', 'registered' ) ) {
			wp_enqueue_style( 'bw-youtube-list' );
		}
		if ( wp_script_is( 'bw-youtube-list-view', 'registered' ) ) {
			wp_enqueue_script( 'bw-youtube-list-view' );
		}
	}
);
