<?php
/**
 * Plugin Name: BW YouTube Embed
 * Description: Gutenberg block that displays a YouTube video from an ACF field with proper 16:9 aspect ratio.
 * Version:     1.1.0
 * Author:      Bowden Works
 * Author URI:  https://bowdenworks.com
 * License:     GPL-2.0-or-later
 * Text Domain: bw-youtube-embed
 */

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

/* ----------------------------------------------------------------
 * Settings
 * -------------------------------------------------------------- */

/**
 * Return the ACF field name configured in settings (default: youtube_link).
 */
function bw_youtube_get_field_name() {
	$options = get_option( 'bw_youtube_embed_settings', array() );
	$field   = isset( $options['acf_field'] ) ? sanitize_text_field( $options['acf_field'] ) : '';
	return $field !== '' ? $field : 'youtube_link';
}

/**
 * Register the settings page under Settings → BW YouTube Embed.
 */
function bw_youtube_embed_add_settings_page() {
	add_options_page(
		'BW YouTube Embed Config',   // page title
		'BW YouTube Embed',          // menu title
		'manage_options',            // capability
		'bw-youtube-embed',          // slug
		'bw_youtube_embed_render_settings_page'
	);
}
add_action( 'admin_menu', 'bw_youtube_embed_add_settings_page' );

/**
 * Register settings, section, and fields.
 */
function bw_youtube_embed_register_settings() {
	register_setting(
		'bw_youtube_embed_settings_group',
		'bw_youtube_embed_settings',
		array(
			'type'              => 'array',
			'sanitize_callback' => 'bw_youtube_embed_sanitize_settings',
			'default'           => array( 'acf_field' => 'youtube_link' ),
		)
	);

	add_settings_section(
		'bw_youtube_embed_main_section',
		'',
		'__return_false',
		'bw-youtube-embed'
	);

	add_settings_field(
		'bw_youtube_acf_field',
		'ACF Field Name',
		'bw_youtube_embed_render_acf_field',
		'bw-youtube-embed',
		'bw_youtube_embed_main_section'
	);
}
add_action( 'admin_init', 'bw_youtube_embed_register_settings' );

/**
 * Sanitize callback.
 */
function bw_youtube_embed_sanitize_settings( $input ) {
	$output = array();
	$output['acf_field'] = isset( $input['acf_field'] ) ? sanitize_text_field( $input['acf_field'] ) : 'youtube_link';
	return $output;
}

/**
 * Render the ACF field name input.
 */
function bw_youtube_embed_render_acf_field() {
	$options = get_option( 'bw_youtube_embed_settings', array() );
	$value   = isset( $options['acf_field'] ) ? esc_attr( $options['acf_field'] ) : 'youtube_link';
	?>
	<input
		type="text"
		name="bw_youtube_embed_settings[acf_field]"
		value="<?php echo $value; ?>"
		class="regular-text"
	/>
	<p class="description">
		Enter the ACF field name that contains the YouTube URL. Default: <code>youtube_link</code>
	</p>
	<?php
}

/**
 * Render the settings page.
 */
function bw_youtube_embed_render_settings_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	?>
	<div class="wrap">
		<h1>BW YouTube Embed Config</h1>

		<div style="background:#fff;border:1px solid #c3c4c7;border-left:4px solid #2271b1;padding:16px 20px;margin:20px 0;max-width:720px;">
			<h2 style="margin-top:0;">About This Plugin</h2>
			<p>
				<strong>BW YouTube Embed</strong> provides a Gutenberg block that automatically displays a YouTube video
				stored in an <a href="https://www.advancedcustomfields.com/" target="_blank">ACF (Advanced Custom Fields)</a> field.
				The video is rendered with a responsive <strong>16:9 aspect ratio</strong> so it looks correct at any screen size.
			</p>

			<hr style="border:none;border-top:1px solid #dcdcde;margin:16px 0;">

			<h3 style="margin-top:0;">How to Use</h3>
			<ol>
				<li>
					<strong>Create an ACF field</strong> (type: URL or Text) on the post type where you want YouTube videos.
					By default the plugin looks for a field named <code>youtube_link</code>. You can change this in the setting below.
				</li>
				<li>
					<strong>Add the YouTube URL</strong> to that field on any post/page.
					Supported formats:
					<code>https://www.youtube.com/watch?v=XXXXX</code>,
					<code>https://youtu.be/XXXXX</code>,
					<code>https://www.youtube.com/embed/XXXXX</code>,
					<code>https://www.youtube.com/shorts/XXXXX</code>
				</li>
				<li>
					<strong>Insert the block</strong> in the Gutenberg editor &mdash; search for
					<strong>&ldquo;BW YouTube Embed&rdquo;</strong> in the block inserter.
					The block will automatically pull the video from the ACF field and display it on the front end.
				</li>
			</ol>

			<hr style="border:none;border-top:1px solid #dcdcde;margin:16px 0;">

			<h3 style="margin-top:0;">Using in a Kadence Query Loop</h3>
			<p>
				To display videos in a grid (e.g. a Videos archive page), add the <strong>BW YouTube Embed</strong> block
				inside a <strong>Kadence Query Loop</strong> card template. The block reads the ACF field from each post
				in the loop automatically &mdash; no shortcode or custom code needed.
			</p>

			<hr style="border:none;border-top:1px solid #dcdcde;margin:16px 0;">

			<h3 style="margin-top:0;">Shortcode</h3>
			<p>
				This plugin also registers the <code>[bw_youtube]</code> shortcode for use in classic editor pages,
				widgets, or anywhere shortcodes are supported. It uses the same ACF field setting and renders
				with the same responsive 16:9 aspect ratio as the Gutenberg block.
			</p>
			<p>
				Simply place <code>[bw_youtube]</code> in your content &mdash; no attributes needed.
				It automatically reads the ACF field from the current post.
			</p>
			<p>
				<strong>Note:</strong> If the child theme also has a <code>[bw_youtube]</code> shortcode registered,
				remove it from the child theme&rsquo;s <code>functions.php</code> to avoid conflicts.
			</p>
		</div>

		<h2>Settings</h2>
		<form method="post" action="options.php">
			<?php
			settings_fields( 'bw_youtube_embed_settings_group' );
			do_settings_sections( 'bw-youtube-embed' );
			submit_button();
			?>
		</form>
	</div>
	<?php
}

/* ----------------------------------------------------------------
 * Shortcode: [bw_youtube]
 * -------------------------------------------------------------- */

/**
 * Render a responsive 16:9 YouTube embed via shortcode.
 * Uses the same ACF field and settings as the Gutenberg block.
 */
function bw_youtube_shortcode_handler( $atts ) {
	$post_id     = get_the_ID();
	$field_name  = bw_youtube_get_field_name();
	$youtube_url = function_exists( 'get_field' ) ? get_field( $field_name, $post_id ) : '';

	$video_id = '';
	if ( ! empty( $youtube_url ) && preg_match( '/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([^\?&"\'>]+)/', $youtube_url, $matches ) ) {
		$video_id = $matches[1];
	}

	if ( $video_id ) {
		$embed_url = 'https://www.youtube.com/embed/' . rawurlencode( $video_id );
		return '<div class="bw-youtube-block">
			<div class="bw-youtube-block__inner">
				<iframe src="' . esc_url( $embed_url ) . '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen loading="lazy"></iframe>
			</div>
		</div>';
	}

	// No video — fall back to featured image.
	if ( has_post_thumbnail( $post_id ) ) {
		return '<div class="bw-youtube-block bw-youtube-block--fallback-image">
			<div class="bw-youtube-block__inner">'
				. get_the_post_thumbnail( $post_id, 'large', array( 'class' => 'bw-youtube-block__featured-img' ) )
			. '</div>
		</div>';
	}

	return '';
}
add_shortcode( 'bw_youtube', 'bw_youtube_shortcode_handler' );

/**
 * Enqueue the block front-end styles on pages that use the shortcode too.
 */
function bw_youtube_shortcode_styles() {
	global $post;
	if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'bw_youtube' ) ) {
		wp_enqueue_style(
			'bw-youtube-block-style',
			plugin_dir_url( __FILE__ ) . 'blocks/bw-youtube/style.css',
			array(),
			'1.1.0'
		);
	}
}
add_action( 'wp_enqueue_scripts', 'bw_youtube_shortcode_styles' );

/* ----------------------------------------------------------------
 * Block registration
 * -------------------------------------------------------------- */

function bw_youtube_embed_register_block() {
	register_block_type( plugin_dir_path( __FILE__ ) . 'blocks/bw-youtube' );
}
add_action( 'init', 'bw_youtube_embed_register_block' );
