<?php
/**
 * Biscotti Gutenberg Blocks
 *
 * Registers native Gutenberg Block Editor blocks for all Biscotti shortcodes.
 * These blocks also work automatically with Spectra and Kadence Blocks
 * (Gutenberg block addons).
 *
 * Uses server-side rendering (render_callback) — no build step required.
 *
 * @package Biscotti_CMP
 * @since 3.1.0
 */

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

class Biscotti_Gutenberg_Blocks
{
    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        add_action('init', [$this, 'register_blocks']);
        add_action('enqueue_block_editor_assets', [$this, 'enqueue_editor_assets']);
    }

    /**
     * Register all Biscotti blocks with server-side rendering
     */
    public function register_blocks()
    {
        // Block: Cookie Table
        register_block_type('biscotti/cookie-table', [
            'attributes' => [
                'category' => ['type' => 'string', 'default' => 'all'],
                'showDuration' => ['type' => 'boolean', 'default' => true],
                'showProvider' => ['type' => 'boolean', 'default' => true],
            ],
            'render_callback' => [$this, 'render_cookie_table'],
        ]);

        // Block: Consent Link
        register_block_type('biscotti/consent-link', [
            'attributes' => [
                'text' => ['type' => 'string', 'default' => ''],
                'cssClass' => ['type' => 'string', 'default' => 'biscotti-consent-link'],
            ],
            'render_callback' => [$this, 'render_consent_link'],
        ]);

        // Block: Settings Link
        register_block_type('biscotti/settings-link', [
            'attributes' => [
                'text' => ['type' => 'string', 'default' => ''],
                'cssClass' => ['type' => 'string', 'default' => 'biscotti-settings-link'],
            ],
            'render_callback' => [$this, 'render_settings_link'],
        ]);

        // Block: Data Export
        register_block_type('biscotti/data-export', [
            'render_callback' => [$this, 'render_data_export'],
        ]);

        // Block: Do Not Sell (CCPA)
        register_block_type('biscotti/do-not-sell', [
            'attributes' => [
                'text' => ['type' => 'string', 'default' => ''],
            ],
            'render_callback' => [$this, 'render_do_not_sell'],
        ]);

        // Block: Impressum
        register_block_type('biscotti/impressum', [
            'attributes' => [
                'enableCache' => ['type' => 'boolean', 'default' => true],
                'lang' => ['type' => 'string', 'default' => 'auto'],
            ],
            'render_callback' => [$this, 'render_impressum'],
        ]);

        // Block: Privacy Policy
        register_block_type('biscotti/privacy-policy', [
            'attributes' => [
                'enableCache' => ['type' => 'boolean', 'default' => true],
                'lang' => ['type' => 'string', 'default' => 'auto'],
            ],
            'render_callback' => [$this, 'render_privacy_policy'],
        ]);

        // Block: Cookie Policy
        register_block_type('biscotti/cookie-policy', [
            'attributes' => [
                'enableCache' => ['type' => 'boolean', 'default' => true],
                'lang' => ['type' => 'string', 'default' => 'auto'],
            ],
            'render_callback' => [$this, 'render_cookie_policy'],
        ]);
    }

    // =========================================================================
    // RENDER CALLBACKS
    // =========================================================================

    public function render_cookie_table($attributes)
    {
        $atts = 'category="' . esc_attr($attributes['category'] ?? 'all') . '"';
        $atts .= ' show_duration="' . ($attributes['showDuration'] ? 'true' : 'false') . '"';
        $atts .= ' show_provider="' . ($attributes['showProvider'] ? 'true' : 'false') . '"';
        return do_shortcode('[biscotti_cookies ' . $atts . ']');
    }

    public function render_consent_link($attributes)
    {
        $atts = '';
        if (!empty($attributes['text'])) {
            $atts .= ' text="' . esc_attr($attributes['text']) . '"';
        }
        if (!empty($attributes['cssClass'])) {
            $atts .= ' class="' . esc_attr($attributes['cssClass']) . '"';
        }
        return do_shortcode('[biscotti_consent_link' . $atts . ']');
    }

    public function render_settings_link($attributes)
    {
        $atts = '';
        if (!empty($attributes['text'])) {
            $atts .= ' text="' . esc_attr($attributes['text']) . '"';
        }
        if (!empty($attributes['cssClass'])) {
            $atts .= ' class="' . esc_attr($attributes['cssClass']) . '"';
        }
        return do_shortcode('[biscotti_settings_link' . $atts . ']');
    }

    public function render_data_export($attributes)
    {
        return do_shortcode('[biscotti_data_export]');
    }

    public function render_do_not_sell($attributes)
    {
        $atts = '';
        if (!empty($attributes['text'])) {
            $atts .= ' text="' . esc_attr($attributes['text']) . '"';
        }
        return do_shortcode('[biscotti_do_not_sell' . $atts . ']');
    }

    public function render_impressum($attributes)
    {
        return $this->render_legal_block('biscotti_impressum', $attributes);
    }

    public function render_privacy_policy($attributes)
    {
        return $this->render_legal_block('biscotti_privacy_policy', $attributes);
    }

    public function render_cookie_policy($attributes)
    {
        return $this->render_legal_block('biscotti_cookie_policy', $attributes);
    }

    private function render_legal_block($shortcode, $attributes)
    {
        $atts = ' cache="' . ($attributes['enableCache'] ? 'true' : 'false') . '"';
        if (isset($attributes['lang']) && $attributes['lang'] !== 'auto') {
            $atts .= ' lang="' . esc_attr($attributes['lang']) . '"';
        }
        return do_shortcode('[' . $shortcode . $atts . ']');
    }

    // =========================================================================
    // EDITOR ASSETS
    // =========================================================================

    /**
     * Enqueue block editor JavaScript (no build step — inline registration)
     */
    public function enqueue_editor_assets()
    {
        $lang_options = $this->get_language_options();

        wp_enqueue_script(
            'biscotti-blocks',
            BISCOTTI_PLUGIN_URL . 'assets/js/blocks.js',
            ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render', 'wp-i18n'],
            BISCOTTI_VERSION,
            true
        );

        wp_localize_script('biscotti-blocks', 'biscottiBlocks', [
            'langOptions' => $lang_options,
            'i18n' => [
                'categoryTitle' => __('Biscotti CMP', 'biscotti-cmp'),
                'cookieTable' => __('Cookie Table', 'biscotti-cmp'),
                'cookieTableDesc' => __('Displays a table of cookies used on your site.', 'biscotti-cmp'),
                'consentLink' => __('Consent Link', 'biscotti-cmp'),
                'consentLinkDesc' => __('A link to reopen the consent banner.', 'biscotti-cmp'),
                'settingsLink' => __('Settings Link', 'biscotti-cmp'),
                'settingsLinkDesc' => __('A link to open the cookie settings panel.', 'biscotti-cmp'),
                'dataExport' => __('Data Export', 'biscotti-cmp'),
                'dataExportDesc' => __('GDPR Art. 15 data export button.', 'biscotti-cmp'),
                'doNotSell' => __('Do Not Sell (CCPA)', 'biscotti-cmp'),
                'doNotSellDesc' => __('CCPA "Do Not Sell My Data" link.', 'biscotti-cmp'),
                'impressum' => __('Impressum', 'biscotti-cmp'),
                'impressumDesc' => __('Legal notice from the Biscotti Legal Suite.', 'biscotti-cmp'),
                'privacyPolicy' => __('Privacy Policy', 'biscotti-cmp'),
                'privacyPolicyDesc' => __('Privacy policy from the Biscotti Legal Suite.', 'biscotti-cmp'),
                'cookiePolicy' => __('Cookie Policy', 'biscotti-cmp'),
                'cookiePolicyDesc' => __('Cookie policy from the Biscotti Legal Suite.', 'biscotti-cmp'),
                'category' => __('Category', 'biscotti-cmp'),
                'all' => __('All', 'biscotti-cmp'),
                'essential' => __('Essential', 'biscotti-cmp'),
                'functional' => __('Functional', 'biscotti-cmp'),
                'analytics' => __('Analytics', 'biscotti-cmp'),
                'marketing' => __('Marketing', 'biscotti-cmp'),
                'showDuration' => __('Show Duration', 'biscotti-cmp'),
                'showProvider' => __('Show Provider', 'biscotti-cmp'),
                'linkText' => __('Link Text', 'biscotti-cmp'),
                'cssClass' => __('CSS Class', 'biscotti-cmp'),
                'enableCache' => __('Enable Cache', 'biscotti-cmp'),
                'language' => __('Language', 'biscotti-cmp'),
                'autoFromWP' => __('Auto (from WordPress)', 'biscotti-cmp'),
            ],
        ]);
    }

    /**
     * Get available language options for block settings
     */
    private function get_language_options()
    {
        $options = [
            ['value' => 'auto', 'label' => __('Auto (from WordPress)', 'biscotti-cmp')],
        ];
        foreach (Biscotti_Languages::endonyms() as $bsc_code => $bsc_name) {
            $options[] = ['value' => $bsc_code, 'label' => $bsc_name];
        }
        return $options;
    }
}

// Initialize
Biscotti_Gutenberg_Blocks::get_instance();
