<?php

if (! defined('WP_DEBUG')) {
	die( 'Direct access forbidden.' );
}

add_action( 'wp_enqueue_scripts', function () {
	wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
});

// Start output buffering
function start_buffer() {
    ob_start('modify_buffer_for_random_video');
}
add_action('wp_head', 'start_buffer', 1);

// Flush the output buffer
function end_buffer() {
    ob_end_flush();
}
add_action('wp_footer', 'end_buffer', 9999);

// Function to modify the buffer for random video
function modify_buffer_for_random_video($buffer) {
    $videos = array(
        array('src' => 'https://www.youtube.com/watch?v=QGvamZ9pir0', 'poster' => 'https://videomulti.sim.mk/wp-content/uploads/2020/08/ryota-nagasaka-w_5TUm7Xa00-unsplash2.jpg'),
        array('src' => 'https://www.youtube.com/watch?v=OV_fpbiFID8', 'poster' => 'https://videomulti.sim.mk/wp-content/uploads/2020/08/home-hero.jpg'),
        array('src' => 'https://www.youtube.com/watch?v=V-PICz-z0rU', 'poster' => 'https://videomulti.sim.mk/wp-content/uploads/2020/08/nadine-shaabana-DrPcfuaeYFQ-unsplash.jpg'),
        array('src' => 'https://www.youtube.com/watch?v=Pm4NF-V08sc', 'poster' => 'https://videomulti.sim.mk/wp-content/uploads/2020/08/ryota-nagasaka-w_5TUm7Xa00-unsplash-1.jpg'),
        array('src' => 'https://www.youtube.com/watch?v=B1lfaWqmK8s', 'poster' => 'https://videomulti.sim.mk/wp-content/uploads/2020/08/krisztian-tabori-IyaNci0CyRk-unsplash.jpg')
    );

    // Randomly select one video
    $random_video = $videos[array_rand($videos)];

    // Look for the data-settings attribute of the section
    $pattern = '/data-settings="([^"]*)"/';
    $buffer = preg_replace_callback($pattern, function($matches) use ($random_video) {
        $settings = json_decode(htmlspecialchars_decode($matches[1]), true);

        // Update video background and poster settings
        if (isset($settings['background_background']) && $settings['background_background'] === 'video') {
            $settings['background_video_link'] = $random_video['src'];
            $settings['background_video_fallback'] = $random_video['poster'];
        }

        return 'data-settings="' . htmlspecialchars(json_encode($settings), ENT_QUOTES, 'UTF-8', false) . '"';
    }, $buffer);

    return $buffer;
}
