<?php


/*
*   ACF blocks
*/
add_action('acf/init', 'acf_init_blocks');
function acf_init_blocks() {
    if( function_exists('acf_register_block_type') ) {

        $filepath = get_template_directory() . '/acf-blocks.json';
        $blocks = json_decode( file_get_contents( $filepath ), true );

        foreach ($blocks as $block) {
            $icon = $block['dashicon'];
            if($block['dashicon']==''){
                
            }
            $example = array();
            if(isset($block['preview']) && !empty($block['preview'])){
                $example = array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'preview_image_help' => $block['preview'],
                        )
                    ),
                );
            }
            acf_register_block_type(array(
                'name'              => $block['slug'],
                'title'             => $block['name'],
                'description'       => $block['description'],
                'render_template'   => 'template-parts/blocks/' . $block['slug'] . '/' . $block['slug'] . '.php',
                'enqueue_assets'    => 'enqueue_block_assets',
                'category'          => 'layout',
                'icon'              => $icon,
                'keywords'          => '',
                'supports'          => array( 'align' => false, ),
                'example'           => $example,
            ));
        }

        function enqueue_block_assets($data) {
            $name = explode('/', $data['name'])[1];

            $filepath = get_template_directory() . '/dist/manifest.json';
            $manifest = json_decode( file_get_contents( $filepath ), true );

            if(is_admin()) {
                if(isset($manifest['entrypoints'][$name . '-editor']['assets']['js'])){
                    foreach ( $manifest['entrypoints'][$name . '-editor']['assets']['js'] as $index => $js ) {
                        $count = count($manifest['entrypoints'][$name . '-editor']['assets']['js']);
                        $dep = [];
                        if ($index != 0) { $dep[] = $name .'-dep-' . ($index-1); }
                        if ($index+1 != $count) {
                            wp_enqueue_script($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                        } else {
                            wp_enqueue_script($name, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                        }
                    }
                }
                if(isset($manifest['entrypoints'][$name . '-editor']['assets']['css'])){
                    foreach ( $manifest['entrypoints'][$name . '-editor']['assets']['css'] as $index => $css ) {
                        $count = count($manifest['entrypoints'][$name . '-editor']['assets']['css']);
                        $dep = [];
                        if ($index != 0) { $dep[] = $name . '-dep-' . ($index-1); }
                        if ($index+1 != $count) {
                            wp_enqueue_style($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                        } else {
                            wp_enqueue_style($name, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                        }
                    }
                }
            } 
            else {
                if (is_archive()) {
                    array_shift($manifest['entrypoints'][$name]['assets']['js']);
                    foreach ($manifest['entrypoints'][$name]['assets']['js'] as $index => $js) {
                        $count = count($manifest['entrypoints'][$name]['assets']['js']);
                        $dep = 'runtime';
                        if ($index != 0) {
                            $dep = $name . '-dep-' . ($index-1);
                        }
                        if ($index + 1 != $count) {
                            wp_enqueue_script($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                        } else {
                            wp_enqueue_script($name, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                        }
                    }
                    foreach ($manifest['entrypoints'][$name]['assets']['css'] as $index => $css) {
                        $count = count($manifest['entrypoints'][$name]['assets']['css']);
                        $dep = '';
                        if ($index != 0) {
                            $dep = $name . '-dep-' . ($index-1);
                        }
                        if ($index + 1 != $count) {
                            wp_enqueue_style($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                        } else {
                            wp_enqueue_style($name, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                        }
                    }
                }
            }
        }
    }
}

/**
 * Has block function which searches as well in reusable blocks.
 *
 * Extends functionality of core's has_block (https://developer.wordpress.org/reference/functions/has_block/)
 *
 * @param mixed $block_name Full Block type to look for.
 * @return bool
 * @author Karolína Vyskočilová <karolina@kybernaut.cz>
 * @since 2021-04-12
 */
function enhanced_has_block($block_name)
{

    if (has_block($block_name)) {
        return true;
    }

    if (has_block('core/block')) {
        $content = get_post_field('post_content');
        $blocks = parse_blocks($content);
        return search_reusable_blocks_within_innerblocks($blocks, $block_name);
    }

    return false;
}

/**
 * Search for selected block within inner blocks.
 *
 * The helper function for enhanced_has_block() function.
 *
 * @param array $blocks Blocks to loop through.
 * @param string $block_name Full Block type to look for.
 * @return bool
 * @since 2021-04-12
 * @author Karolína Vyskočilová <karolina@kybernaut.cz>
 */
function search_reusable_blocks_within_innerblocks($blocks, $block_name)
{
    foreach ($blocks as $block) {
        if (isset($block['innerBlocks']) && !empty($block['innerBlocks'])) {
            search_reusable_blocks_within_innerblocks($block['innerBlocks'], $block_name);
        } elseif ($block['blockName'] === 'core/block' && !empty($block['attrs']['ref']) && \has_block($block_name, $block['attrs']['ref'])) {
            return true;
        }
    }
    return false;
}

/**
 * Register the styles (CSS) for the blocks outside
 * acf_register_block_type() as loading styles
 * using acf_register_block_type() will load the
 * styles in the footer and not in <head> causing
 * CLS issues
 */
//add_action( 'wp_enqueue_scripts', 'register_acf_block_styles' );
function register_acf_block_styles() : void {
    $filepath = get_template_directory() . '/acf-blocks.json';
    $blocks = json_decode(file_get_contents($filepath), true);

    $filepath = get_template_directory() . '/dist/manifest.json';
    $manifest = json_decode(file_get_contents($filepath), true);

    foreach ($blocks as $block) {
        $name = $block['slug'];

        if( enhanced_has_block( 'acf/' . $name ) ) {
            if(isset($manifest['entrypoints'][$name]['assets']['js']) && is_array($manifest['entrypoints'][$name]['assets']['js'])){
                array_shift($manifest['entrypoints'][$name]['assets']['js']);
                foreach ($manifest['entrypoints'][$name]['assets']['js'] as $index => $js) {
                    $count = count($manifest['entrypoints'][$name]['assets']['js']);
                    $dep = 'runtime';
                    if ($index != 0) {
                        $dep = $name . '-dep-' . ($index-1);
                    }
                    if ($index + 1 != $count) {
                        wp_enqueue_script($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                    } else {
                        wp_enqueue_script($name, get_template_directory_uri() . '/dist/' . $js, $dep, null, true);
                    }
                }
            }
            if(isset($manifest['entrypoints'][$name]['assets']['css']) && is_array($manifest['entrypoints'][$name]['assets']['css'])){
                foreach ($manifest['entrypoints'][$name]['assets']['css'] as $index => $css) {
                    $count = count($manifest['entrypoints'][$name]['assets']['css']);
                    $dep = '';
                    if ($index != 0) {
                        $dep = $name . '-dep-' . ($index-1);
                    }
                    if ($index + 1 != $count) {
                        wp_enqueue_style($name . '-dep-' . $index, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                    } else {
                        wp_enqueue_style($name, get_template_directory_uri() . '/dist/' . $css, $dep, null);
                    }
                }
            }
        }
    }
}

/**
 * This function allows to disable gutenberg editor for custom post types
 * (uncomment add_filter to start using)
 */
add_filter('use_block_editor_for_post_type', 'custom_disable_gutenberg', 10, 2);
function custom_disable_gutenberg($current_status, $post_type)
{
    if ($post_type === 'benefit') return false;
    return $current_status;
}

/**
 * Allow only custom gutenberg blocks from this theme
 */
add_filter('allowed_block_types_all', 'custom_allow_blocks', 25, 2);
function custom_allow_blocks($allowed_blocks, $editor_context)
{
    $filepath = get_template_directory() . '/acf-blocks.json';
    $blocks = json_decode(file_get_contents($filepath), true);

    $allowed_blocks = [];
    foreach ($blocks as $block) {
        $allowed_blocks[] = 'acf/' . $block['slug'];
    }
    $allowed_blocks[] = 'core/block';
    $allowed_blocks[] = 'core/pattern';

    return $allowed_blocks;
}

/**
 * Add reusable blocks to menu
 */
add_action('admin_menu', 'add_reusables_to_menu');
function add_reusables_to_menu()
{
    add_menu_page(
        'Reusable Blocks',
        'Reusable Blocks',
        'delete_published_posts',
        'edit.php?post_type=wp_block',
        '',
        'dashicons-layout',
        21
    );
}

function acf_color_palette() {
    ?>
    <script type="text/javascript">
        (function ($) {
            acf.add_filter('color_picker_args', function (args, $field) {
                // add the hexadecimal codes here for the colors you want to appear as swatches
                args.palettes = ['#E9F6DC', '#FFFEDD', '#F1E7E9', '#E7EBDC', '#DFE8ED', '#EDE8DF'];
                // return colors
                return args;
            });
        })(jQuery);
    </script>
    <?php
}

add_action( 'acf/input/admin_footer', 'acf_color_palette' );