<?php
class EazyDocsBlocks {

    public function __construct() {
        add_action("init", [$this, "block_init"]);
    }

    /**
     * Registers custom Gutenberg blocks and sets up their configurations.
     *
     * @return void
     */
    public function block_init() {
        if ($this->ezd_is_premium()) {
            $this->register_block('eazy-docs', array(
                'render_callback' => [$this, 'render_eazy_docs'],
            ));
        }
    }

    /**
     * Render callback for the free block.
     *
     * @param array $attributes Block attributes.
     * @param string $content Block content.
     * @return string Rendered block content.
     */
    public function render_eazy_docs($attributes, $content) {
        return $this->load_block_template($attributes);
    }
    
    /**
     * Loads the block template file based on attributes.
     *
     * @param array $attributes
     * @return string Rendered content
     */
    private function load_block_template($attributes) {
        wp_enqueue_style('elegant-icon');
        wp_enqueue_style('ezd-docs-widgets');
        wp_enqueue_style('eazydocs-pro-frontend');

        ob_start();

        $preset = $attributes['docPreset'] ?? '';
        if (!empty($attributes['docTypes']) && $attributes['docTypes'] == 'single-doc') {
            $preset = $attributes['docSinglePreset'] ?? '';
        }

        $file_path = sprintf(
            '%s/includes/Blocks/%s/%s.php',
            EAZYDOCSPRO_PATH,
            sanitize_text_field($attributes['docTypes'] ?? ''),
            sanitize_text_field($preset)
        );

        if (is_readable($file_path)) {
            require_once $file_path;
        }

        return ob_get_clean();
    }

    /**
     * Registers a Gutenberg block.
     *
     * @param string $name Block name.
     * @param array $options Block options.
     */
    public function register_block($name, $options = array()) {
        register_block_type(EAZYDOCSPRO_PATH . '/build/' . $name, $options);
    }

    /**
     * Checks if the premium version is enabled.
     *
     * @return bool
     */
    private function ezd_is_premium() {
        return function_exists('ezd_is_premium') && ezd_is_premium();
    }
}

// Instantiate the class
new EazyDocsBlocks();
