<?php
/**
 * Gutenberg block registration for maca Restu.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Block category for maca blocks in the editor.
 *
 * @param array<int, array<string, mixed>> $categories Block categories.
 * @return array<int, array<string, mixed>>
 */
function maca_menulist_register_block_category($categories) {
    return array_merge(
        array(
            array(
                'slug' => 'maca-restu-pro',
                'title' => __('maca Restu', 'maca-restu-pro'),
            ),
        ),
        $categories
    );
}

/**
 * Register the dynamic block without loading block.json metadata on init.
 */
function maca_menulist_register_block_type() {
    if (!function_exists('register_block_type')) {
        return;
    }

    add_filter('block_categories_all', 'maca_menulist_register_block_category');

    $registry = class_exists('WP_Block_Type_Registry') ? WP_Block_Type_Registry::get_instance() : null;

    maca_menulist_register_legacy_block_aliases($registry);

    if (!$registry || !$registry->is_registered('maca-restu/maca-menu-list')) {
        register_block_type(
            'maca-restu/maca-menu-list',
            array(
                'render_callback' => 'maca_menulist_render_block_callback',
            )
        );
    }

    if (defined('MACA_MENULIST_PRO') && MACA_MENULIST_PRO) {
        if (!$registry || !$registry->is_registered('maca-restu/maca-table-booking')) {
            register_block_type(
                'maca-restu/maca-table-booking',
                array(
                    'render_callback' => 'maca_menulist_render_table_booking_block_callback',
                    'attributes' => array(
                        'button' => array(
                            'type' => 'string',
                            'default' => '',
                        ),
                        'title' => array(
                            'type' => 'string',
                            'default' => '',
                        ),
                    ),
                )
            );
        }

        if (!$registry || !$registry->is_registered('maca-restu/maca-opening-hours')) {
            register_block_type(
                'maca-restu/maca-opening-hours',
                array(
                    'render_callback' => 'maca_menulist_render_opening_hours_block_callback',
                    'attributes' => array(
                        'title' => array(
                            'type' => 'string',
                            'default' => '',
                        ),
                        'showTitle' => array(
                            'type' => 'boolean',
                            'default' => true,
                        ),
                        'highlightToday' => array(
                            'type' => 'boolean',
                            'default' => true,
                        ),
                        'mondayFirst' => array(
                            'type' => 'boolean',
                            'default' => true,
                        ),
                    ),
                )
            );
        }

        if (
            function_exists('maca_menulist_info_hub_feature_available')
            && maca_menulist_info_hub_feature_available()
        ) {
            if (!$registry || !$registry->is_registered('maca-restu/maca-info-news')) {
                register_block_type(
                    'maca-restu/maca-info-news',
                    array(
                        'render_callback' => 'maca_menulist_render_info_news_block_callback',
                        'attributes' => array(
                            'limit' => array(
                                'type' => 'number',
                                'default' => 5,
                            ),
                            'showImage' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'showDate' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'showExcerpt' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'layout' => array(
                                'type' => 'string',
                                'default' => 'list',
                            ),
                            'bannerScroll' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                        ),
                    )
                );
            }

            if (!$registry || !$registry->is_registered('maca-restu/maca-info-events')) {
                register_block_type(
                    'maca-restu/maca-info-events',
                    array(
                        'render_callback' => 'maca_menulist_render_info_events_block_callback',
                        'attributes' => array(
                            'limit' => array(
                                'type' => 'number',
                                'default' => 10,
                            ),
                            'view' => array(
                                'type' => 'string',
                                'default' => 'list',
                            ),
                            'showImage' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'showLocation' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'mondayFirst' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                            'showSubscribe' => array(
                                'type' => 'boolean',
                                'default' => true,
                            ),
                        ),
                    )
                );
            }
        }

        if (function_exists('maca_menulist_site_chat_feature_available') && maca_menulist_site_chat_feature_available()) {
            if (!$registry || !$registry->is_registered('maca-restu/maca-site-chat')) {
                register_block_type(
                    'maca-restu/maca-site-chat',
                    array(
                        'title' => __('Chatt', 'maca-restu-pro'),
                        'render_callback' => 'maca_menulist_render_site_chat_block_callback',
                    )
                );
            }
        }
    }
}

/**
 * Keep older block names working in saved post content.
 *
 * @param WP_Block_Type_Registry|null $registry Block registry.
 * @return void
 */
function maca_menulist_register_legacy_block_aliases($registry) {
    if (!$registry) {
        return;
    }

    $legacy_blocks = array(
        'maca-restu/menu-list' => 'maca_menulist_render_block_callback',
        'maca-restu/table-booking' => 'maca_menulist_render_table_booking_block_callback',
        'maca-menulist/maca-menu-list' => 'maca_menulist_render_block_callback',
        'maca-menulist/menu-list' => 'maca_menulist_render_block_callback',
        'maca-menulist/maca-table-booking' => 'maca_menulist_render_table_booking_block_callback',
        'maca-menulist/table-booking' => 'maca_menulist_render_table_booking_block_callback',
        'maca-menulist/maca-opening-hours' => 'maca_menulist_render_opening_hours_block_callback',
        'maca-menulist/maca-info-news' => 'maca_menulist_render_info_news_block_callback',
        'maca-menulist/maca-info-events' => 'maca_menulist_render_info_events_block_callback',
    );

    foreach ($legacy_blocks as $block_name => $callback) {
        if (!$registry->is_registered($block_name) && is_callable($callback)) {
            register_block_type(
                $block_name,
                array(
                    'render_callback' => $callback,
                )
            );
        }
    }
}

/**
 * Enqueue block editor assets (admin/block editor only).
 */
function maca_menulist_enqueue_block_editor_assets() {
    wp_enqueue_script(
        'maca-restu-block-editor',
        MACA_MENULIST_PLUGIN_URL . 'blocks/menu-list/editor.js',
        array('wp-blocks', 'wp-element', 'wp-i18n', 'wp-server-side-render', 'wp-components'),
        MACA_MENULIST_VERSION,
        true
    );

    $show_category_picker = !(function_exists('maca_menulist_is_dishes_mode') && maca_menulist_is_dishes_mode());
    $block_categories = array();

    if ($show_category_picker && function_exists('maca_menulist_db_get_categories')) {
        foreach (maca_menulist_db_get_categories(true) as $category) {
            if (!isset($category->id, $category->name)) {
                continue;
            }
            $block_categories[] = array(
                'id' => (int) $category->id,
                'name' => (string) $category->name,
            );
        }
    }

    wp_localize_script(
        'maca-restu-block-editor',
        'macaMenulistBlock',
        array(
            'categories' => $block_categories,
            'showCategoryPicker' => $show_category_picker,
            'i18n' => array(
                'displayOptions' => __('Display Options', 'maca-restu-pro'),
                'categoryButtons' => __('Category Buttons', 'maca-restu-pro'),
                'listView' => __('List (vertical buttons)', 'maca-restu-pro'),
                'category' => __('Category', 'maca-restu-pro'),
                'allCategories' => __('All categories', 'maca-restu-pro'),
                'categoryHelp' => __('Show all categories, or only one category on this page.', 'maca-restu-pro'),
            ),
        )
    );

    if (defined('MACA_MENULIST_PRO') && MACA_MENULIST_PRO) {
        wp_enqueue_script(
            'maca-restu-table-booking-block-editor',
            MACA_MENULIST_PLUGIN_URL . 'blocks/table-booking/editor.js',
            array('wp-blocks', 'wp-element', 'wp-i18n', 'wp-server-side-render', 'wp-components'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_enqueue_script(
            'maca-restu-opening-hours-block-editor',
            MACA_MENULIST_PLUGIN_URL . 'blocks/opening-hours/editor.js',
            array('wp-blocks', 'wp-element', 'wp-i18n', 'wp-server-side-render', 'wp-components'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_enqueue_style(
            'maca-menulist-style',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/style.css',
            array(),
            MACA_MENULIST_VERSION
        );

        if (
            function_exists('maca_menulist_info_hub_feature_available')
            && maca_menulist_info_hub_feature_available()
        ) {
            wp_enqueue_script(
                'maca-restu-info-news-block-editor',
                MACA_MENULIST_PLUGIN_URL . 'blocks/info-news/editor.js',
                array('wp-blocks', 'wp-element', 'wp-i18n', 'wp-server-side-render', 'wp-components'),
                MACA_MENULIST_VERSION,
                true
            );

            wp_enqueue_script(
                'maca-restu-info-events-block-editor',
                MACA_MENULIST_PLUGIN_URL . 'blocks/info-events/editor.js',
                array('wp-blocks', 'wp-element', 'wp-i18n', 'wp-server-side-render', 'wp-components'),
                MACA_MENULIST_VERSION,
                true
            );

            wp_enqueue_style(
                'maca-menulist-info-hub',
                MACA_MENULIST_PLUGIN_URL . 'assets/css/info-hub.css',
                array(),
                MACA_MENULIST_VERSION
            );
        }
    }
}

/**
 * Server-side render callback for the table reservation block.
 *
 * @param array<string, mixed> $attributes Block attributes.
 * @return string
 */
function maca_menulist_render_table_booking_block_callback($attributes) {
    $attributes = is_array($attributes) ? $attributes : array();

    return maca_menulist_render_table_booking_form(
        $attributes,
        array(
            'preview' => maca_menulist_is_rest_block_render(),
        )
    );
}

/**
 * Server-side render callback for the opening hours block.
 *
 * @param array<string, mixed> $attributes Block attributes.
 * @return string
 */
function maca_menulist_render_opening_hours_block_callback($attributes) {
    $attributes = is_array($attributes) ? $attributes : array();

    $atts = array(
        'title' => isset($attributes['title']) ? (string) $attributes['title'] : '',
        'show_title' => !empty($attributes['showTitle']) ? '1' : '0',
        'highlight_today' => !array_key_exists('highlightToday', $attributes) || !empty($attributes['highlightToday']) ? '1' : '0',
        'monday_first' => !array_key_exists('mondayFirst', $attributes) || !empty($attributes['mondayFirst']) ? '1' : '0',
    );

    if ($atts['title'] === '') {
        unset($atts['title']);
    }

    return maca_menulist_render_opening_hours(
        $atts,
        array(
            'preview' => maca_menulist_is_rest_block_render(),
        )
    );
}

/**
 * Server-side render callback for the news block.
 *
 * @param array<string, mixed> $attributes Block attributes.
 * @return string
 */
function maca_menulist_render_info_news_block_callback($attributes) {
    $attributes = is_array($attributes) ? $attributes : array();

    return maca_menulist_render_info_news_list(
        $attributes,
        array(
            'preview' => maca_menulist_is_rest_block_render(),
        )
    );
}

/**
 * Server-side render callback for the events block.
 *
 * @param array<string, mixed> $attributes Block attributes.
 * @return string
 */
function maca_menulist_render_info_events_block_callback($attributes) {
    $attributes = is_array($attributes) ? $attributes : array();

    return maca_menulist_render_info_events_list(
        $attributes,
        array(
            'preview' => maca_menulist_is_rest_block_render(),
        )
    );
}

/**
 * Server-side render callback for the site chatbot block.
 *
 * @return string
 */
function maca_menulist_render_site_chat_block_callback() {
    if (!shortcode_exists('maca_site_chat')) {
        return '';
    }

    return do_shortcode('[maca_site_chat]');
}

/**
 * Server-side render callback for the maca Restu block.
 *
 * @param array<string, mixed> $attributes Block attributes.
 * @return string
 */
function maca_menulist_render_block_callback($attributes) {
    $attributes = is_array($attributes) ? $attributes : array();

    if (class_exists('Maca_Menu_List_Frontend')) {
        Maca_Menu_List_Frontend::ensure_frontend_assets();
    }

    $buttons = array_key_exists('buttons', $attributes) ? (bool) $attributes['buttons'] : true;
    $category = isset($attributes['category']) ? (string) $attributes['category'] : '';

    if ($category === '' && !empty($attributes['categoryId'])) {
        $category_name = maca_menulist_db_get_category_name_by_id(intval($attributes['categoryId']));
        if ($category_name) {
            $category = $category_name;
        }
    }

    $shortcode = '[maca_menu_list';

    if (!$buttons) {
        $shortcode .= ' buttons="false"';
    }

    if ($category !== '') {
        $shortcode .= ' category="' . esc_attr($category) . '"';
    }

    $shortcode .= ']';

    return do_shortcode($shortcode);
}
