<?php
/**
 * Flavor – Restaurant Menu
 *
 * Gutenberg block (Free version) — Card Grid layout, Elegant Dark theme.
 * Server-side rendered. No build step required.
 *
 * @package    FlavorMenu
 * @copyright  Copyright (c) 2024 Flavor Studio
 * @license    GPL-2.0-or-later
 * @link       https://flavor-menu.com
 */

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

class Flavor_Block {

    public static function init() {
        add_action( 'init',                        array( __CLASS__, 'register_block' ) );
        add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'localize_editor_data' ) );
    }

    /**
     * Register the Gutenberg block (server-side rendered).
     */
    public static function register_block() {
        wp_register_script(
            'flavor-block-editor',
            FLAVOR_MENU_URL . 'assets/js/flavor-block-editor.js',
            array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render', 'wp-i18n' ),
            FLAVOR_MENU_VERSION,
            true
        );

        register_block_type( 'flavor-menu/menu', array(
            'editor_script'   => 'flavor-block-editor',
            'render_callback' => array( __CLASS__, 'render_block' ),
            'attributes'      => array(
                'title'            => [ 'type' => 'string',  'default' => 'Our Menu' ],
                'description'      => [ 'type' => 'string',  'default' => '' ],
                'category'         => [ 'type' => 'string',  'default' => '' ],
                'limit'            => [ 'type' => 'integer', 'default' => 12 ],
                'show_filter'      => [ 'type' => 'string',  'default' => 'yes' ],
                'hide_all_btn'     => [ 'type' => 'string',  'default' => '' ],
                'default_category' => [ 'type' => 'string',  'default' => '' ],
                'currency'         => [ 'type' => 'string',  'default' => '€' ],
                'el_class'         => [ 'type' => 'string',  'default' => '' ],
            ),
        ) );
    }

    /**
     * Pass category list to the block editor via JS.
     * Runs after init so the taxonomy is registered.
     */
    public static function localize_editor_data() {
        $cats     = get_terms( [ 'taxonomy' => 'flavor_menu_cat', 'hide_empty' => false ] );
        $cat_opts = [ [ 'label' => __( 'All Categories', 'flavor-restaurant-menu' ), 'value' => '' ] ];
        if ( ! is_wp_error( $cats ) ) {
            foreach ( $cats as $cat ) {
                $cat_opts[] = [ 'label' => $cat->name, 'value' => $cat->slug ];
            }
        }

        wp_localize_script( 'flavor-block-editor', 'flavorBlockData', [
            'categories' => $cat_opts,
        ] );
    }

    /**
     * Server-side render callback — reuses the existing shortcode renderer.
     */
    public static function render_block( $attributes ) {
        return Flavor_Shortcode::render( $attributes );
    }
}
