<?php

declare(strict_types=1);

namespace ProudNerds\Helpers;

use ProudNerds\PostTypes\Example;
use ProudNerds\Trait\Initializable;

/**
 * Class: BlockHooks.
 *
 * Hooks relating to the blocks can be added and altered here.
 */
class BlockHooks
{
    use Initializable;

    /**
     * Block options and settings constructor.
     */
    public function __construct()
    {
        $this->addBlockActions();
        $this->addBlockFilters();
    }

    /**
     * Use this function to add default blocks to a post type.
     * For example use acf/hero to add a hero block to all pages and lock it.
     */
    public function addDefaultTemplate(): void
    {
        global $wp_post_types;
        $exampleBlockName = 'acf/example';
        $page = $wp_post_types['page'];
        $singles = [$wp_post_types[Example::POST_TYPE]];

        $page->template = [
            [
                $exampleBlockName,
                [
                    'lock' => [
                        'move' => true,
                        'remove' => false,
                    ],
                ],
            ],
        ];

        foreach ($singles as $single) {
            $single->template = [
                [
                    $exampleBlockName,
                    [
                        'lock' => [
                            'move' => true,
                            'remove' => true, // lock removing, because we always want this block
                        ],
                    ],
                ],
            ];
        }
    }

    /**
     * Sets correct global post for blocks on archive page
     * @param array $parsedBlock
     * @return array
     */
    public function setPost(array $parsedBlock): array
    {
        global $post;
        $post = is_archive() ? ArchiveHooks::getArchivePost(get_queried_object()->name) : $post;
        return $parsedBlock;
    }

    /**
     * @param string $blockName
     * Check if given slug is first block
     * @return bool
     */
    public function isFirstBlock(string $blockName): bool
    {
        global $post;
        if (has_blocks($post->post_content)) {
            $blocks = parse_blocks($post->post_content);
            if ($blocks[0]['blockName'] == $blockName) {
                return true;
            }
        }
        return false;
    }

    /**
     * Add the required actions.
     */
    private function addBlockActions(): void
    {
        add_action('init', [$this, 'addDefaultTemplate'], 99);
    }

    /**
     * Add the required filters.
     */
    private function addBlockFilters(): void
    {
        add_filter('render_block_data', [$this, 'setPost'], 10, 3);
    }

}
