<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class YVPD_Auto_Replace {
    public function __construct() {
        if ( get_option('yvpd_auto_enable', 0) ) {
            add_action( 'init', array( $this, 'register_hooks' ) );
        }
    }
    public function register_hooks() {
        if ( is_admin() ) return;
        $run = false;
        $slugs_raw = get_option('yvpd_auto_slugs', '');
        if ( !empty($slugs_raw) ) {
            $current_slug = get_post_field( 'post_name', get_post() );
            $slugs = array_map('trim', explode(',', $slugs_raw));
            if ( in_array($current_slug, $slugs) ) $run = true;
        }
        if ( ! $run ) {
            if ( is_single() && get_option('yvpd_auto_posts', 0) ) $run = true;
            if ( is_page() && get_option('yvpd_auto_pages', 0) ) $run = true;
        }
        if ( $run ) {
            add_filter( 'render_block', array( $this, 'intercept_any_block' ), 20, 2 );
            add_filter( 'wp_video_shortcode_override', array( $this, 'replace_shortcode' ), 20, 4 );
        }
    }
    public function intercept_any_block( $block_content, $block ) {
        if ( $block['blockName'] !== 'core/video' ) {
            return $block_content;
        }
        $src = '';
        $poster = '';
        if ( !empty($block['attrs']['id']) ) {
            $src = wp_get_attachment_url( $block['attrs']['id'] );
        }
        if ( empty($src) && !empty($block['attrs']['src']) ) {
            $src = $block['attrs']['src'];
        }
        if ( empty($src) && preg_match( '/src\s*=\s*["\']([^"\']+)["\']/i', $block_content, $match ) ) {
            $src = $match[1];
        }
        if ( !empty($src) ) {
            if ( !empty($block['attrs']['poster']) ) {
                $poster = $block['attrs']['poster'];
            }
            return YVPD_Shortcode::generate_player_html( array(
                'url'    => $src,
                'poster' => $poster
            ) );
        }
        return $block_content;
    }
    public function replace_shortcode( $output, $atts, $content, $instance ) {
        $src = '';
        if ( !empty($atts['src']) ) $src = $atts['src'];
        elseif ( !empty($atts['mp4']) ) $src = $atts['mp4'];
        if ( !empty($src) ) {
            $poster = !empty($atts['poster']) ? $atts['poster'] : '';
            return YVPD_Shortcode::generate_player_html( array('url'=>$src, 'poster'=>$poster) );
        }
        return $output;
    }
}
new YVPD_Auto_Replace();