<?php
/**
 * Dynamic Block Registration
 *
 * @package Author_Website_Templates
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class AWT_Blocks
 * 
 * Handles dynamic discovery and registration of blocks.
 */
class AWT_Blocks
{

    /**
     * Constructor
     */
    public function __construct()
    {
        // We can hook this immediately or call it from the loader.
        // Loader calls 'new AWT_Blocks()' or we adding action here?
        // The loader creates an instance? No, the loader didn't instantiate this class,
        // but it included the file. 
        // Best practice: Hook into 'init' here if the file is included.
        add_action('init', [$this, 'register_blocks']);

        // Also handle the inline script for global vars
        add_action('wp_enqueue_scripts', [$this, 'enqueue_global_vars']);
        add_action('enqueue_block_editor_assets', [$this, 'enqueue_global_vars']);
    }

    /**
     * Register Blocks
     */
    public function register_blocks()
    {
        // Dynamic Block Registration from all subdirectories in build/blocks/
        // Scans build/blocks/*/ (e.g., child-author, author-pro, etc.)
        $blocks_base_dir = RSWPTHEMES_AWT_PLUGIN_PATH . 'build/blocks/';

        if (file_exists($blocks_base_dir)) {
            // Get all category directories (child-author, author-pro, etc.)
            $category_dirs = glob($blocks_base_dir . '*', GLOB_ONLYDIR);

            if ($category_dirs) {
                foreach ($category_dirs as $category_dir) {
                    // Get all block directories within each category
                    $block_dirs = glob($category_dir . '/*', GLOB_ONLYDIR);

                    if ($block_dirs) {
                        foreach ($block_dirs as $block_dir) {
                            // Check if this is a valid block (has index.asset.php)
                            if (file_exists($block_dir . '/index.asset.php')) {
                                $block_folder_name = basename($block_dir);

                                $args = [
                                    'viewStyle' => 'awt-blocks-css',
                                    'editorStyle' => 'awt-editor-style',
                                ];

                                // Special case: blog-details doesn't use global viewStyle
                                // if ($block_folder_name === 'blog-details') {
                                //     unset($args['viewStyle']);
                                // }

                                register_block_type($block_dir, $args);
                            }
                        }
                    }
                }
            }
        }

        // Main Entry Point (Optional - e.g. for global styles or template library)
        // If src/index.js produced a build/index.js
        $main_asset_path = RSWPTHEMES_AWT_PLUGIN_PATH . 'build/index.asset.php';
        if (file_exists($main_asset_path)) {
            wp_enqueue_script(
                'awt-global-js',
                RSWPTHEMES_AWT_PLUGIN_URL . 'build/index.js',
                array('wp-blocks', 'wp-element', 'wp-editor'),
                filemtime($main_asset_path),
                true
            );
        }

        $asset_file = include( RSWPTHEMES_AWT_PLUGIN_PATH . 'build/template-library/index.asset.php' );

        
        wp_enqueue_script(
            'awt-template-library-script',
            RSWPTHEMES_AWT_PLUGIN_URL . 'build/template-library/index.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        
        if ( file_exists( RSWPTHEMES_AWT_PLUGIN_PATH . 'build/template-library/style-index.css' ) ) {
            wp_enqueue_style(
                'awt-template-library-style',
                RSWPTHEMES_AWT_PLUGIN_URL . 'build/template-library/style-index.css',
                array(),
                $asset_file['version']
            );
        }
    }

    /**
     * Enqueue Global Variables
     */
    public function enqueue_global_vars()
    {
        $is_pro_active = defined('RSWPTHEMES_AWT_PRO_ACTIVE') && RSWPTHEMES_AWT_PRO_ACTIVE;

        // We need to attach this to a handle that exists. 
        // 'awt-global-js' is registered above if index.js exists.
        // If each block is independent, we might need a common handle or attach to one of them?
        // Or we can register a dummy script or attach to 'wp-blocks' if needed (but that loads early).
        // Best is 'awt-global-js' if we are sure it loads, or check if any block loaded.
        // For now, attaching to 'awt-global-js' as per previous logic which seems to assume it exists or relies on block assets.
        // Note: wp_add_inline_script requires the handle to be registered.
        wp_register_style(
            'awt-blocks-css',
            RSWPTHEMES_AWT_PLUGIN_URL . 'build/style-index.css',
            array(),
            filemtime(RSWPTHEMES_AWT_PLUGIN_PATH . 'build/style-index.css')
        );
        wp_register_style(
            'awt-editor-style',
            RSWPTHEMES_AWT_PLUGIN_URL . 'build/index.css',
            [],
            file_exists(RSWPTHEMES_AWT_PLUGIN_PATH . 'build/index.css')
            ? filemtime(RSWPTHEMES_AWT_PLUGIN_PATH . 'build/index.css')
            : '1.0.0'
        );

        wp_register_style(
            'awt-glide-css',
            RSWPTHEMES_AWT_PLUGIN_URL . 'assets/libs/glidejs/glide.core.min.css',
            array(),
            '3.6.0'
        );

        // If awt-global-js is optional/missing, avoiding fatal error:
        if (wp_script_is('awt-global-js', 'registered')) {
            wp_add_inline_script(
                'awt-global-js',
                'window.awtVars = ' . wp_json_encode(array(
                    'isPro' => $is_pro_active,
                    'pluginUrl' => RSWPTHEMES_AWT_PLUGIN_URL,
                    'patternImagesUrl' => RSWPTHEMES_AWT_PLUGIN_URL . 'patterns/assets/',
                )) . ';',
                'before'
            );
        }

        wp_register_script(
            'awt-glide-js',
            RSWPTHEMES_AWT_PLUGIN_URL . 'assets/libs/glidejs/glide.min.js',
            array(),
            '3.6.0',
            true
        );

    }

}

new AWT_Blocks();

