<?php

function create_block_audio_player_register_plyr()
{
	// Register Plyr CSS
	wp_register_style(
		'plyr',
		plugins_url('assets/plyr/plyr.css', __FILE__),
		array(),
		'3.8.3'
	);

	// Register Plyr JS
	wp_register_script(
		'plyr',
		plugins_url('assets/plyr/plyr.min.js', __FILE__),
		array(),
		'3.8.3',
		true
	);
}
add_action('init', 'create_block_audio_player_register_plyr');

/**
 * Enqueue Plyr in the block editor
 */
function create_block_audio_player_enqueue_editor_assets()
{
	wp_enqueue_style('plyr');
	wp_enqueue_script('plyr');
}
add_action('enqueue_block_editor_assets', 'create_block_audio_player_enqueue_editor_assets');

/**
 * Enqueue Plyr assets when the block is used
 */
function create_block_audio_player_enqueue_assets($block_content, $block)
{
	if ('carhop-blocks/audio-player' === $block['blockName']) {
		wp_enqueue_style('plyr');
		wp_enqueue_script('plyr');
	}
	return $block_content;
}
add_filter('render_block', 'create_block_audio_player_enqueue_assets', 10, 2);



/* ############## DISALLOW BLOCKS ############## */

/**
 * Désactive le bloc audio natif pour les utilisateurs non administrateurs pour éviter toute confusio
 *
 */
function carhop_blocks_disallow_block_types($allowed_block_types, $block_editor_context)
{



	$disallowed_blocks = array(
		'core/audio',
	);

	// Get all registered blocks if $allowed_block_types is not already set.
	if (! is_array($allowed_block_types) || empty($allowed_block_types)) {
		$registered_blocks   = WP_Block_Type_Registry::get_instance()->get_all_registered();
		$allowed_block_types = array_keys($registered_blocks);
	}

	// Create a new array for the allowed blocks.
	$filtered_blocks = array();

	// Loop through each block in the allowed blocks list.
	foreach ($allowed_block_types as $block) {

		// Check if the block is not in the disallowed blocks list.
		if (! in_array($block, $disallowed_blocks, true)) {

			// If it's not disallowed, add it to the filtered list.
			$filtered_blocks[] = $block;
		}
	}


	// Return the filtered list of allowed blocks
	return $filtered_blocks;
}
add_filter('allowed_block_types_all', 'carhop_blocks_disallow_block_types', 10, 2);
