<?php

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

use WP_Error;
use WP_REST_Response;
use Miruni\Elementor\Miruni_Elementor_Service;
use Miruni\Kadence\Miruni_Kadence_Manager;
use Miruni\Miruni_Theme_JSON_Manager;

class Miruni_Theme_JSON_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/theme-json/';

    public static function get_rest_url(int $page_id): string
    {
        return self::_get_rest_url(['page_id' => $page_id]);
    }

    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_theme_json'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
                'args' => [
                    'page_id' => [
                        'required' => true,
                        'validate_callback' => function ($param) {
                            return is_numeric($param);
                        },
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ]);
        });
    }

    /**
     * Get block widgets data from options table
     * @param \WP_REST_Request<array<mixed>> $request
     * @return WP_Error|WP_REST_Response Response object or error
     */
    public static function get_theme_json(\WP_REST_Request $request): WP_Error|WP_REST_Response
    {
        $post_id = (int) $request->get_param('page_id');
        error_log("Miruni_Theme_JSON_API: Fetching theme.json for post ID $post_id");

        // Elementor doesn't use the theme.json file, so we can skip this check
        if (Miruni_Elementor_Service::is_current_page_elementor($post_id)) {
            return new WP_Error('theme_json_error', 'This page uses Elementor, which does not utilize the theme.json file.', ['status' => 400]);
        }

        // Kadence theme has its own customization system and may not fully utilize theme.json
        if (Miruni_Kadence_Manager::is_kadence_page($post_id)) {
            return new WP_Error('theme_json_error', 'This page uses Kadence theme, which has its own customization system and may not fully utilize the theme.json file.', ['status' => 400]);
        }

        $theme_json_data = Miruni_Theme_JSON_Manager::get_theme_json_data();

        if ($theme_json_data === null) {
            return new WP_Error('theme_json_error', 'Unable to retrieve theme.json data.');
        }

        $response_data = [
            'theme_json' => json_encode($theme_json_data),
        ];

        return new WP_REST_Response($response_data, 200);
    }
}
