<?php
/**
 * Copyright (C) 2026 Plugixa (https://plugixa.com)
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

namespace PlugixaRecipe\Blocks;

// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.SlowDBQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom-table data layer: table identifiers are built with $wpdb->prefix and are never user input; all request values are bound via $wpdb->prepare(); ORDER BY / LIMIT fragments come out of internal allow-list maps; content reads go through PlugixaRecipe\Cache (the static sniff cannot trace caching through the wrapper); meta_key/meta_value are dedicated plugin columns, not WP_Query.

defined( 'ABSPATH' ) || exit;

use PlugixaRecipe\Frontend\Shortcodes;

/**
 * RecipeBlock Class - Registers the Gutenberg block 'plugixarecipe/recipes'.
 *
 * Server-side rendering callback that reuses the same logic as the shortcode system.
 */
class RecipeBlock {

    /**
     * Register the Gutenberg block.
     */
    public function register(): void {
        if (!function_exists('register_block_type')) {
            return;
        }

        // Register from block.json if it exists (for editor assets)
        $block_json = PLUGIXARECIPE_PATH . 'assets/build/blocks/recipe-block/block.json';
        if (file_exists($block_json)) {
            register_block_type($block_json, [
                'render_callback' => [$this, 'render_callback'],
            ]);
            return;
        }

        // Fallback: register programmatically
        register_block_type('plugixarecipe/recipes', [
            'api_version'     => 3,
            'editor_script'   => 'plugixarecipe-block-editor',
            'render_callback' => [$this, 'render_callback'],
            'attributes'      => [
                'shortcodeId' => [
                    'type'    => 'number',
                    'default' => 0,
                ],
                'viewId' => [
                    'type'    => 'number',
                    'default' => 0,
                ],
                'categories' => [
                    'type'    => 'string',
                    'default' => '',
                ],
                'limit' => [
                    'type'    => 'number',
                    'default' => 12,
                ],
            ],
        ]);

        // Register editor script
        $editor_asset = PLUGIXARECIPE_PATH . 'assets/build/blocks/recipe-block/index.asset.php';
        $dependencies = ['wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-server-side-render'];
        $version = PLUGIXARECIPE_VERSION;

        if (file_exists($editor_asset)) {
            $asset = require $editor_asset;
            $dependencies = $asset['dependencies'] ?? $dependencies;
            $version = $asset['version'] ?? $version;
        }

        $editor_js = PLUGIXARECIPE_PATH . 'assets/build/blocks/recipe-block/index.js';
        if (file_exists($editor_js)) {
            wp_register_script(
                'plugixarecipe-block-editor',
                PLUGIXARECIPE_URL . 'assets/build/blocks/recipe-block/index.js',
                $dependencies,
                $version,
                true
            );

            // Pass data to the block editor
            wp_localize_script('plugixarecipe-block-editor', 'plugixarecipeBlockData', [
                'shortcodes' => $this->get_shortcodes_for_editor(),
                'views'      => $this->get_views_for_editor(),
                'categories' => $this->get_categories_for_editor(),
            ]);
        }

        // Register editor styles
        $editor_css = PLUGIXARECIPE_PATH . 'assets/build/blocks/recipe-block/index.css';
        if (file_exists($editor_css)) {
            wp_register_style(
                'plugixarecipe-block-editor-style',
                PLUGIXARECIPE_URL . 'assets/build/blocks/recipe-block/index.css',
                [],
                $version
            );
        }
    }

    /**
     * Server-side render callback for the block.
     *
     * Uses the same logic as the [plugixa_recipes] shortcode.
     *
     * @param array $attributes Block attributes.
     * @return string Rendered HTML.
     */
    public function render_callback(array $attributes): string {
        $shortcode_atts = [];

        if (!empty($attributes['shortcodeId'])) {
            $shortcode_atts['id'] = (int) $attributes['shortcodeId'];
        }

        if (!empty($attributes['viewId'])) {
            $shortcode_atts['view'] = (int) $attributes['viewId'];
        }

        if (!empty($attributes['categories'])) {
            $shortcode_atts['categories'] = sanitize_text_field($attributes['categories']);
        }

        if (!empty($attributes['limit'])) {
            $shortcode_atts['limit'] = (int) $attributes['limit'];
        }

        // Reuse the shortcode rendering logic
        $shortcodes = new Shortcodes();
        return $shortcodes->render_recipes($shortcode_atts);
    }

    /**
     * Get available shortcodes for the block editor dropdown.
     */
    private function get_shortcodes_for_editor(): array {
        global $wpdb;
        $table = $wpdb->prefix . 'plugixarecipe_shortcodes';

        $results = $wpdb->get_results(
            "SELECT id, name FROM {$table} ORDER BY name ASC",
            ARRAY_A
        );

        $options = [['label' => __('-- Select a Shortcode --', 'plugixarecipe'), 'value' => 0]];
        foreach ($results ?: [] as $row) {
            $options[] = ['label' => $row['name'], 'value' => (int) $row['id']];
        }

        return $options;
    }

    /**
     * Get available views for the block editor dropdown.
     */
    private function get_views_for_editor(): array {
        global $wpdb;
        $table = $wpdb->prefix . 'plugixarecipe_views';

        $results = $wpdb->get_results(
            "SELECT id, name FROM {$table} ORDER BY name ASC",
            ARRAY_A
        );

        $options = [['label' => __('-- Default View --', 'plugixarecipe'), 'value' => 0]];
        foreach ($results ?: [] as $row) {
            $options[] = ['label' => $row['name'], 'value' => (int) $row['id']];
        }

        return $options;
    }

    /**
     * Get available categories for the block editor.
     */
    private function get_categories_for_editor(): array {
        global $wpdb;
        $table = $wpdb->prefix . 'plugixarecipe_categories';

        $results = $wpdb->get_results(
            "SELECT id, name, slug FROM {$table} ORDER BY display_order ASC",
            ARRAY_A
        );

        return $results ?: [];
    }
}
