<?php
/**
 * Template View: Video Embed
 *
 * Embeds a YouTube or Vimeo video.
 *
 * @package    BoostBot
 * @subpackage Templates/Views
 * @since      1.6.0
 *
 * @var string $url       Video URL (YouTube or Vimeo).
 * @var string $title     Optional video title.
 * @var string $thumbnail Optional thumbnail URL.
 */

// phpcs:ignoreFile WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-scope variables set by the includer, not true globals.

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Validate required data
if ( empty( $url ) ) {
    return;
}

// Parse video URL to get embed URL
$embed_url = '';
$video_id  = '';

// YouTube
if ( preg_match( '/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]+)/', $url, $matches ) ) {
    $video_id  = $matches[1];
    $embed_url = 'https://www.youtube.com/embed/' . $video_id;
    if ( empty( $thumbnail ) ) {
        $thumbnail = 'https://img.youtube.com/vi/' . $video_id . '/hqdefault.jpg';
    }
}
// Vimeo
elseif ( preg_match( '/vimeo\.com\/(?:video\/)?(\d+)/', $url, $matches ) ) {
    $video_id  = $matches[1];
    $embed_url = 'https://player.vimeo.com/video/' . $video_id;
}

if ( empty( $embed_url ) ) {
    return;
}

$title = $title ?? '';
?>

<div class="bb-video-embed">
    <?php if ( ! empty( $title ) ) : ?>
        <div class="bb-video-title"><?php echo esc_html( $title ); ?></div>
    <?php endif; ?>
    
    <div class="bb-video-container">
        <iframe 
            src="<?php echo esc_url( $embed_url ); ?>" 
            title="<?php echo esc_attr( $title ?: 'Video' ); ?>"
            frameborder="0" 
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
            allowfullscreen>
        </iframe>
    </div>
</div>
