<?php

namespace Miruni\RestApi;
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

use WP_Error;
use WP_REST_Response;
use Miruni\BlockWidget\Miruni_Block_Widget_Manager; // Added import

class Miruni_Block_Widgets_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/block-widgets/';

    public static function get_rest_url(): string
    {
        return self::_get_rest_url([]);
    }

    public static function setup(): void
    {
        // Register REST API endpoint
        add_action('rest_api_init', function () {
            register_rest_route(self::$namespace, self::$route, [
                'methods' => 'GET',
                'callback' => [__CLASS__, 'get_block_widgets'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
            ]);
        });
    }

    /**
     * Get block widgets data from options table
     * 
     * @return WP_Error|WP_REST_Response Response object or error
     */
    public static function get_block_widgets(): WP_Error|WP_REST_Response
    {
        $all_widgets_data = Miruni_Block_Widget_Manager::get_all_widgets_data();
        $all_sidebars_data = Miruni_Block_Widget_Manager::get_all_sidebars_data();

        $response_widgets = [];
        foreach ($all_widgets_data as $widget_object) {
            $response_widgets[] = $widget_object->to_array();
        }

        $response_data = [
            'widgets' => $response_widgets,
            'sidebars' => $all_sidebars_data,
        ];

        // Return the structured widget data
        return new WP_REST_Response($response_data, 200);
    }
}
