<?php

/**
 * CUSTOM BLOCKS
 * ------------------
 */
/**
 * Registers the block using the metadata loaded from the `block.json` file.
 * Behind the scenes, it registers also all assets so they can be enqueued
 * through the block editor in the corresponding context.
 *
 * @see https://developer.wordpress.org/reference/functions/register_block_type/
 */
add_action('init', 'dragblock_block_init');
function dragblock_block_init()
{
	// cannot register blocks using block.json path
	global $wp_version;
	if (version_compare($wp_version, '5.8.0') < 0) {
		return;
	}


	$path = DRAGBLOCK_BUILD_PATH . 'blocks/';

	// folder name of the blocks in the src/blocks/ dir
	$blocks = array(
		// Basic,
		'wrapper',
		'link',
		'icon',
		'text',
		'image',
		// 'iframe',

		// form,
		'form',
		'select',
		'option',
		'input',
		'textarea',

		// preset
		'pattern',

		// compact
		'slider',
		'slide',

		'visual-compare',
		'visual-compare-item',
		
	);
	foreach ($blocks as $block) {
		register_block_type($path . $block);
	}

	// Load available translations.	
	wp_set_script_translations('dragblock-editor-script-js', 'dragblock');
}



/**
 * Register a custom block category so all blocks of DragBlockcould stay together
 * @param array $category the array of the current categories
 */
if (version_compare(get_bloginfo('version'), '5.8', '>=')) {
	add_filter('block_categories_all', 'dragblock_register_block_category', 10, 2);
} else {
	add_filter('block_categories', 'dragblock_register_block_category', 10, 2);
}
function dragblock_register_block_category($categories, $block_editor_context)
{
	array_unshift(
		$categories,
		array(
			'slug'  => 'dragblock-compact',
			'title' => __('DragBlock Compact', 'dragBlock-block')
		)
	);

	array_unshift(
		$categories,
		array(
			'slug'  => 'dragblock-form',
			'title' => __('DragBlock Form', 'dragBlock-block')
		)
	);

	array_unshift(
		$categories,
		array(
			'slug'  => 'dragblock-basic',
			'title' => __('DragBlock Basic', 'dragBlock-block')
		)
	);
	
	

	return $categories;
}

/**
 * Fixing: Error Loading Block: Invalid Parameter(s): attributes
 * by adding missing general attributes for the blocks that do not support
 * ex: woocommerce blocks
 * https://github.com/woocommerce/woocommerce-blocks/issues/4690
 */
add_filter('register_block_type_args', 'dragblock_err_loading_block_invalid_param_attrs', 1, 2);
function dragblock_err_loading_block_invalid_param_attrs($args, $block_type)
{
	if (!isset($args['attributes'])) {
		$args['attributes'] = array();
	}

	// for dragblock attributes
	$dragblock_attrs = array(
		'dragBlockClientId' => 'string',
		'dragBlockStyles' => 'array',
		'dragBlockCSS' => 'string',
		'dragBlockAttrs' => 'string',
		'dragBlockQueries' => 'array',
		'dragBlockPHP' => 'string',
		'dragBlockScripts' => 'array',
		'dragBlockJS' => 'string',
		'dragBlockRenderability' => 'string',
	);
	foreach ($dragblock_attrs as $attr => $type) {
		if (isset($args['attributes'][$attr])) {
			continue;
		}

		$args['attributes'][$attr] = array('type' => $type, 'default' => '');
	}

	// for other special attributes
	if (!isset($args['attributes']['anchor'])) {
		$args['attributes']['anchor'] = array(
			'type' => 'string',
			'source' => 'attribute',
			'default' => '',
			'attribute' => 'id',
			'selector' =>  '*', // very important			
		);
	}

	return $args;
}


/* ----------------------------------------------------------------
 * On multisite, only super admin has 'unfiltered_html'
 * while sub-site admins have no that cap, leading to errors
 * when saving blocks with special tags, such as SVG, INPUT, etc.
 * ----------------------------------------------------------------
 */
add_filter( 'map_meta_cap', 'dragblock_multisite_allow_admins_unfiltered_html', 1, 4 );
function dragblock_multisite_allow_admins_unfiltered_html($caps, $cap, $user_id, $args ) {
	if (!is_multisite()) {
		return $caps;
	}
	$user = get_userdata($user_id);
	if (!$user) {
		return $caps; // or handle the error accordingly
	}

	if (is_super_admin($user_id)) {
		return $caps;
	}

	if (!in_array('administrator', (array) $user->roles) ) {
		return $caps;
	}
	$caps = array( 'unfiltered_html' );
	return $caps;
}


// die();

// add_action('init', 'test_wp_insert_post');

// function test_wp_insert_post() {
//     $postarr = array(
//         'ID'                    => 8,
//         'ancestors'             => array(),
//         'comment_count'         => '0',
//         'comment_status'        => 'closed',
//         'context'               => '',
//         'guid'                  => 'http://wordpress/test-06/2024/08/06/front-page/',
//         'import_id'             => 0,
//         'menu_order'            => 0,
//         'page_template'         => '',
//         'ping_status'           => 'closed',
//         'pinged'                => '',
//         'post_author'           => '3',
//         'post_category'         => array(),
//         'post_content'          => '<!-- wp:dragblock/icon {\"dragBlockClientId\":\"21a13d89-382d-4ae4-8cb9-37408c45129c\",\"dragBlockStyles\":[{\"slug\":\"font-size\",\"value\":\"96px\"}],\"dragBlockCSS\":\"[data-dragblock-client-id=\\u002221a13d89-382d-4ae4-8cb9-37408c45129c\\u0022]{font-size:96px}\",\"dragBlockAttrs\":[],\"className\":\"wp-block-dragblock-icon\"} -->\n<span class=\"wp-block-dragblock-icon\"><svg viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\" aria-hidden=\"true\"><path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v8.4l-3-2.9c-.3-.3-.8-.3-1 0L11.9 14 9 12c-.3-.2-.6-.2-.8 0l-3.6 2.6V5c-.1-.3.1-.5.4-.5zm14 15H5c-.3 0-.5-.2-.5-.5v-2.4l4.1-3 3 1.9c.3.2.7.2.9-.1L16 12l3.5 3.4V19c0 .3-.2.5-.5.5z\"></path></svg></span>\n<!-- /wp:dragblock/icon -->',
//         'post_content_filtered' => '',
//         'post_date'             => '2024-08-06 02:06:12',
//         'post_date_gmt'         => '2024-08-06 02:06:12',
//         'post_excerpt'          => 'Displays your site\'s homepage, whether it is set to display latest posts or a static page. The Front Page template takes precedence over all templates.',
//         'post_mime_type'        => '',
//         'post_modified'         => '2024-08-06 05:51:37',
//         'post_modified_gmt'     => '2024-08-06 05:51:37',
//         'post_name'             => 'front-page',
//         'post_parent'           => 0,
//         'post_password'         => '',
//         'post_status'           => 'publish',
//         'post_title'            => 'Front Page',
//         'post_type'             => 'wp_template',
//         'tags_input'            => array(),
//         'to_ping'               => ''
//     );

//     // Insert the post into the database.
//     $post_id = wp_insert_post($postarr);

//     // Output the result.
//     if (is_wp_error($post_id)) {
//         // There was an error inserting the post.
//         echo 'Error: ' . $post_id->get_error_message();
//     } else {
//         // The post was inserted successfully.
//         echo 'Post inserted with ID: ' . $post_id . '<br>';

//         // Retrieve the post content
//         $post = get_post($post_id);
//         if ($post) {
//             echo 'Post Content: ' . $post->post_content;
//         } else {
//             echo 'Error retrieving the post.';
//         }
//     }

//     die(); // To stop further execution and see the output.
// }
