<?php
/**
 * BW Site Map Block
 * 
 * A visual site map block with interactive markers.
 */

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * 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.
 */
function bw_register_site_map_block() {
    // Register block script
    wp_register_script(
        'bw-site-map-editor',
        get_stylesheet_directory_uri() . '/blocks/bw-site-map/block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n'),
        filemtime(get_stylesheet_directory() . '/blocks/bw-site-map/block.js')
    );

    // Register block
    register_block_type('bw/site-map', array(
        'editor_script' => 'bw-site-map-editor',
        'render_callback' => 'bw_site_map_render_callback',
        'attributes' => array(
            'background' => array(
                'type' => 'object',
                'default' => array(
                    'url' => '',
                    'id' => 0,
                    'alt' => ''
                ),
            ),
            'markers' => array(
                'type' => 'array',
                'default' => [],
            ),
        ),
    ));
}
add_action('init', 'bw_register_site_map_block');

/**
 * Server-side rendering of the block.
 *
 * @param array    $attributes Block attributes.
 * @param string   $content    Block default content.
 * @param WP_Block $block      Block instance.
 *
 * @return string Returns the block content.
 */
function bw_site_map_render_callback($attributes, $content, $block) {
    // Default output is a simple placeholder
    $html = '<div class="wp-block-bw-site-map">';
    $html .= '<p>This is a site map block placeholder.</p>';
    $html .= '</div>';
    
    return $html;
}

/**
 * Add custom category for our blocks
 */
function bw_block_categories_site_map($categories, $post) {
    return array_merge(
        $categories,
        array(
            array(
                'slug' => 'bw-blocks',
                'title' => __('BW Blocks', 'kadence-child'),
            ),
        )
    );
}
add_filter('block_categories_all', 'bw_block_categories_site_map', 10, 2);