<?php

/**
 * Cryzel Theme Class
 *
 * This file contains the main theme class that initializes the Cryzel theme.
 * It handles theme setup, file loading, and registration of various WordPress features.
 *
 * @package Cryzel
 * @since 1.0.0
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Cryzel_Theme Class
 *
 * This class handles the theme setup and includes necessary files.
 * It follows the singleton pattern to ensure only one instance exists.
 */
class Cryzel_Theme
{

    /**
     * Instance of this class.
     *
     * @var Cryzel_Theme
     */
    private static $instance = null;

    /**
     * Get the singleton instance of this class.
     *
     * @return Cryzel_Theme
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor - sets up the theme.
     * 
     * Initializes the theme by loading required files and setting up hooks.
     */
    private function __construct()
    {
        $this->load_includes();
        add_action('after_setup_theme', [$this, 'setup_theme']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_theme_styles']);
        add_action('init', [$this, 'register_block_bindings']);
        add_action('init', [$this, 'register_pattern_categories']);

        // Note: SVG upload support has been removed to follow WordPress theme guidelines
        // To enable SVG uploads, use a dedicated plugin or add the following code to a must-use plugin:
        // add_filter('upload_mimes', function($mimes) {
        //     $mimes['svg'] = 'image/svg+xml';
        //     return $mimes;
        // });

        // Register blocks
        add_action('init', [$this, 'register_blocks']);

        // Enqueue lottie animation view script
        add_action('wp_enqueue_scripts', [$this, 'enqueue_lottie_view_script']);

        // Register block styles
        add_action('init', 'cryzel_register_block_styles');

        // Register block categories
        add_filter('block_categories_all', [$this, 'register_block_categories'], 10, 2);
    }

    /**
     * Load necessary files for the theme.
     * 
     * Includes all required PHP files from the includes directory.
     */
    private function load_includes()
    {
        $files = [
            'class-attributes.php',   // Handles custom block attributes
            'block-styles.php',       // Registers custom block styles
            'class-enqueue.php',      // Handles asset loading
            'features/scroll-top.php', // Scroll-to-top feature
            'features/contact-form-handler.php', // Contact form submission handler
            'theme-settings.php',     // Theme settings
            'class-admin-notice.php',        // Handles admin notices
            'blocks/svg-icon-block.php', // SVG Icon block
            'class-woocommerce.php',  // WooCommerce integration
            'class-zoloblocks-installer.php', // ZoloBlocks plugin installer
        ];

        foreach ($files as $file) {
            $path = get_template_directory() . '/includes/' . $file;
            if (file_exists($path)) {
                require_once $path;
            }
        }
    }

    /**
     * Set up theme features and support.
     * 
     * Registers theme support for various WordPress features.
     */
    public function setup_theme()
    {
        // Load theme text domain for translations
        load_theme_textdomain('cryzel', get_template_directory() . '/languages');

        // Add support for post formats
        add_theme_support(
            'post-formats',
            ['aside', 'audio', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video']
        );
    }

    // Note: SVG upload support has been removed to follow WordPress theme guidelines
    // To enable SVG uploads, use a dedicated plugin or add the code to a must-use plugin

    /**
     * Register custom blocks
     */
    public function register_blocks()
    {
        // Register SVG Icon block
        $svg_icon_result = register_block_type_from_metadata(
            get_template_directory() . '/build/features/svg-icon-block',
            [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-svg-icon-block-style',
                        get_theme_file_uri('build/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]
        );

        // Register Button Widget block
        $button_widget_result = register_block_type_from_metadata(
            get_template_directory() . '/build/features/button-widget',
            [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-button-widget-style',
                        get_theme_file_uri('build/features/button-widget/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]
        );

        // Register Card Widget block
        $card_widget_result = register_block_type_from_metadata(
            get_template_directory() . '/build/features/card-widget',
            [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-card-widget-style',
                        get_theme_file_uri('build/features/card-widget/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]
        );

        // Register Contact Form Widget block
        $contact_form_widget_result = register_block_type_from_metadata(
            get_template_directory() . '/build/features/contact-form-widget',
            [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-contact-form-widget-style',
                        get_theme_file_uri('build/features/contact-form-widget/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]
        );

        // Register Live Clock/Date block
        $live_clock_date_path = get_template_directory() . '/build/features/live-clock-date';
        if (file_exists($live_clock_date_path . '/block.json')) {
            wp_register_script(
                'cryzel-live-clock-date-view',
                get_template_directory_uri() . '/build/features/live-clock-date/view.js',
                array(),
                wp_get_theme()->get('Version'),
                true
            );

            $metadata = json_decode(file_get_contents($live_clock_date_path . '/block.json'), true);
            $metadata['view_script'] = 'cryzel-live-clock-date-view';
            
            register_block_type_from_metadata($live_clock_date_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-live-clock-date-style',
                        get_theme_file_uri('build/features/live-clock-date/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // Responsive Navigation Menu block
        $nav_menu_block_path = get_template_directory() . '/build/features/responsive-nav-menu';
        if (file_exists($nav_menu_block_path . '/block.json')) {
            wp_register_script(
                'cryzel-responsive-nav-menu-editor',
                get_template_directory_uri() . '/build/features/responsive-nav-menu/index.js',
                array('wp-blocks', 'wp-element', 'wp-editor'),
                wp_get_theme()->get('Version'),
                true
            );

            wp_register_script(
                'cryzel-responsive-nav-menu-view',
                get_template_directory_uri() . '/build/features/responsive-nav-menu/view.js',
                array(),
                wp_get_theme()->get('Version'),
                true
            );

            // Use theme-compliant block registration with explicit script handles
            $metadata = json_decode(file_get_contents($nav_menu_block_path . '/block.json'), true);
            $metadata['editor_script'] = 'cryzel-responsive-nav-menu-editor';
            $metadata['view_script'] = 'cryzel-responsive-nav-menu-view';
            register_block_type_from_metadata($nav_menu_block_path, $metadata);
        }

        // Scroll Progress Indicator block
        $scroll_progress_block_path = get_template_directory() . '/build/features/scroll-progress-indicator';
        if (file_exists($scroll_progress_block_path . '/block.json')) {
            wp_register_script(
                'cryzel-scroll-progress-indicator-view',
                get_template_directory_uri() . '/build/features/scroll-progress-indicator/view.js',
                array(),
                wp_get_theme()->get('Version'),
                true
            );

            register_block_type_from_metadata($scroll_progress_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Styles are included in the main style-index.css
                    return $content;
                }
            ]);
        }

        // Interactive Hotspot Image block
        $interactive_hotspot_block_path = get_template_directory() . '/build/features/interactive-hotspot-image';
        if (file_exists($interactive_hotspot_block_path . '/block.json')) {
            register_block_type_from_metadata($interactive_hotspot_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-interactive-hotspot-image-style',
                        get_theme_file_uri('build/features/interactive-hotspot-image/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // Advanced Icon Button block
        $advanced_icon_button_path = get_template_directory() . '/build/features/advanced-icon-button';
        if (file_exists($advanced_icon_button_path . '/block.json')) {
            register_block_type_from_metadata($advanced_icon_button_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-advanced-icon-button-style',
                        get_theme_file_uri('build/features/advanced-icon-button/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // Animated Counter Block
        $animated_counter_block_path = get_template_directory() . '/build/features/animated-counter-block';
        if (file_exists($animated_counter_block_path . '/block.json')) {
            register_block_type_from_metadata($animated_counter_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-animated-counter-block-style',
                        get_theme_file_uri('build/features/animated-counter-block/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // 3D Tilt Card Block
        $tilt_card_block_path = get_template_directory() . '/build/features/3d-tilt-card-block';
        if (file_exists($tilt_card_block_path . '/block.json')) {
            wp_register_script(
                'cryzel-three-d-tilt-card-view',
                get_template_directory_uri() . '/build/features/3d-tilt-card-block/view.js',
                array(),
                wp_get_theme()->get('Version'),
                true
            );

            $metadata = json_decode(file_get_contents($tilt_card_block_path . '/block.json'), true);
            $metadata['view_script'] = 'cryzel-three-d-tilt-card-view';

            register_block_type_from_metadata($tilt_card_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-three-d-tilt-card-style',
                        get_theme_file_uri('build/features/3d-tilt-card-block/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // Button Group Block
        $button_group_block_path = get_template_directory() . '/build/features/button-group-block';
        if (file_exists($button_group_block_path . '/block.json')) {
            register_block_type_from_metadata($button_group_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Enqueue the block's frontend styles
                    wp_enqueue_style(
                        'cryzel-button-group-style',
                        get_theme_file_uri('build/features/button-group-block/style-index.css'),
                        [],
                        wp_get_theme()->get('Version')
                    );

                    return $content;
                }
            ]);
        }

        // Button Item Block (Child of Button Group)
        $button_item_block_path = get_template_directory() . '/build/features/button-group-block/button-item';
        if (file_exists($button_item_block_path . '/block.json')) {
            register_block_type_from_metadata($button_item_block_path, [
                'render_callback' => function ($attributes, $content) {
                    // Styles are registered with the block
                    return $content;
                }
            ]);
        }
    }

    /**
     * Enqueue theme styles.
     */
    public function enqueue_theme_styles()
    {
        wp_enqueue_style(
            'cryzel-style',
            get_parent_theme_file_uri('style.css'),
            [],
            wp_get_theme()->get('Version')
        );
    }

    /**
     * Enqueue Lottie Animation view script on frontend.
     */
    public function enqueue_lottie_view_script()
    {
        // Always enqueue on frontend - the script will check if blocks exist
        wp_enqueue_script(
            'cryzel-lottie-animation-view',
            get_theme_file_uri('build/features/lottie-animation/view.js'),
            [],
            wp_get_theme()->get('Version'),
            true
        );
    }

    /**
     * Register block bindings for dynamic content.
     * 
     * Sets up custom block bindings for the theme.
     */
    public function register_block_bindings()
    {
        register_block_bindings_source(
            'cryzel/format',
            [
                'label'              => _x('Post format name', 'Label for the block binding placeholder in the editor', 'cryzel'),
                'get_value_callback' => [$this, 'format_binding_callback'],
            ]
        );
    }

    /**
     * Callback for the post format binding.
     * 
     * Returns the formatted post format name.
     * 
     * @return string|null The post format name or null if standard format.
     */
    public function format_binding_callback()
    {
        $post_format_slug = get_post_format();
        if ($post_format_slug && 'standard' !== $post_format_slug) {
            return get_post_format_string($post_format_slug);
        }
    }

    /**
     * Register block pattern categories.
     * 
     * Creates custom pattern categories for the theme.
     */
    public function register_pattern_categories()
    {
        register_block_pattern_category(
            'cryzel_page',
            [
                'label'       => __('Pages', 'cryzel'),
                'description' => __('A collection of full page layouts.', 'cryzel'),
            ]
        );

        register_block_pattern_category(
            'cryzel_post-format',
            [
                'label'       => __('Post formats', 'cryzel'),
                'description' => __('A collection of post format patterns.', 'cryzel'),
            ]
        );
    }

    /**
     * Register custom block categories.
     * 
     * Adds a custom category for Cryzel blocks.
     * 
     * @param array $categories Array of block categories.
     * @param object $post Post object.
     * @return array Modified array of block categories.
     */
    public function register_block_categories($categories, $post)
    {
        return array_merge(
            [
                [
                    'slug'  => 'cryzel-blocks',
                    'title' => __('Cryzel Blocks', 'cryzel'),
                    'icon'  => 'admin-customizer',
                ],
            ],
            $categories
        );
    }
}
