<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Tool
{
    public const VERSION = '1.0.0';

    public function __construct()
    {
        if (is_admin()) {
            add_action('enqueue_block_editor_assets', array($this, 'enqueue_editor_assets'));
        } add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public function register_rest_routes()
    {
        register_rest_route('puffergo/v1', '/ai/process-html', array('methods' => 'POST', 'permission_callback' => function () { return current_user_can('edit_posts'); }, 'callback' => array($this, 'rest_import_process_html'), 'args' => array('html' => array('required' => true, 'type' => 'string', 'sanitize_callback' => null, ), 'compilerConfig' => array('required' => false, 'type' => 'object', 'default' => array(), ), ), ));
        register_rest_route('puffergo/v1', '/unit-config', array('methods' => 'GET', 'permission_callback' => function () { return current_user_can('edit_posts'); }, 'callback' => array($this, 'rest_get_unit_config'), ));
        register_rest_route('puffergo/v1', '/components', array('methods' => 'GET', 'permission_callback' => function () { return current_user_can('edit_posts'); }, 'callback' => array($this, 'rest_get_components'), ));
        register_rest_route('puffergo/v1', '/components/compiled', array('methods' => 'GET', 'permission_callback' => function () { return current_user_can('edit_posts'); }, 'callback' => array($this, 'rest_get_compiled'), 'args' => array('slug' => array('required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ), ));
    }

    public function rest_get_unit_config()
    {
        if (! class_exists('PufferGo_Unit_Config')) {
            require_once PUFFERGO_PLUGIN_DIR . 'php/config/class-puffergo-unit-config.php';
        } $config = PufferGo_Unit_Config::format_for_js();

        return new WP_REST_Response($config, 200);
    }

    public function rest_get_components()
    {
        return new WP_REST_Response(PufferGo_Component_Loader::get_components(), 200);
    }

    public function rest_get_compiled(WP_REST_Request $request)
    {
        $slug = $request->get_param('slug');
        $result = PufferGo_Component_Loader::get_compiled($slug);

        if (is_wp_error($result)) {
            return new WP_REST_Response(array('message' => $result->get_error_message()), 404);
        }

return new WP_REST_Response($result, 200);
    }

    public function rest_import_process_html($request)
    {
        $params = $request->get_json_params();

        if (! is_array($params)) {
            $params = array();
        } $html = isset($params['html']) ? $params['html'] : '';
        $compiler_config = isset($params['compilerConfig']) && is_array($params['compilerConfig']) ? $params['compilerConfig'] : array();
        $ai_scene = isset($params['aiScene']) && is_string($params['aiScene']) ? sanitize_text_field(wp_unslash($params['aiScene'])) : 'import.html_process';

        if (! is_string($html) || trim($html) === '') {
            return new WP_REST_Response(array('success' => false, 'message' => __('HTML content is required.', 'puffergo'), ), 400);
        }

if (! class_exists('PufferGo_API_Client')) {
            return new WP_REST_Response(array('success' => false, 'message' => __('API client is not available.', 'puffergo'), ), 503);
        }

try {
            $api_client = PufferGo_API_Client::get_instance();
            $data = $api_client->post('/api/ai/process-html', array('html' => $html, 'compilerConfig' => $compiler_config, 'aiScene' => $ai_scene, ), array('timeout' => 60, 'log_prefix' => 'PufferGo Import', ));

            return new WP_REST_Response(array('success' => true, 'data' => is_array($data) ? $data : array('processedHtml' => '', 'tailwindCss' => '', 'dependencies' => array()), ), 200);
        } catch (PufferGo_API_Exception $e) {
            return new WP_REST_Response($e->toArray(), $e->getCode());
        } catch (Exception $e) {
            return new WP_REST_Response(array('success' => false, 'message' => $e->getMessage(), ), 500);
        }
    }

    public function enqueue_editor_assets()
    {
        $screen = get_current_screen();

        if (! $screen || ! in_array($screen->base, array('post', 'post-new'), true)) {
            return;
        } $plugin_url = plugin_dir_url(dirname(__FILE__));
        $plugin_dir = plugin_dir_path(dirname(__FILE__));
        $asset_file = $plugin_dir . 'build/admin/puffergo-tool/index.asset.php';

        if (file_exists($asset_file)) {
            $asset = include $asset_file;
            $deps = $asset['dependencies'];
            $version = $asset['version'];
        } else {
            $deps = array('wp-plugins', 'wp-edit-post', 'wp-editor', 'wp-element', 'wp-components', 'wp-data', 'wp-api-fetch', 'wp-blocks', 'wp-i18n', 'wp-notices', );
            $version = self::VERSION;
        } $js_file = $plugin_dir . 'build/admin/puffergo-tool/index.js';

        if (file_exists($js_file)) {
            wp_enqueue_script('puffergo-tool', $plugin_url . 'build/admin/puffergo-tool/index.js', $deps, $version, true);
            $feedback_url = class_exists('PufferGo_Telemetry') ? PufferGo_Telemetry::get_feedback_url() : '';
            $post_id = get_the_ID();
            $post_type = $post_id ? get_post_type($post_id) : '';
            $preview_url = '';

            if ($post_id && in_array($post_type, array('puffergo_product', 'post'), true)) {
                $preview_url = get_preview_post_link($post_id);
            } wp_localize_script('puffergo-tool', 'puffergoTool', array('restUrl' => rest_url('puffergo/v1/'), 'nonce' => wp_create_nonce('wp_rest'), 'feedbackUrl' => $feedback_url, 'hasApiKey' => ! empty(get_option('puffergo_api_key', '')), 'connectUrl' => PUFFERGO_BASE_URL . '/dashboard/connect', 'siteName' => get_bloginfo('name'), 'siteUrl' => home_url('/'), 'dashboardUrl' => admin_url('admin.php?page=puffergo'), 'postId' => $post_id ? absint($post_id) : 0, 'postType' => $post_type ? sanitize_key($post_type) : '', 'previewUrl' => $preview_url, 'initialTab' => sanitize_key(wp_unslash($_GET['puffergo_tab'] ?? '')), 'quickStyleCss' => PufferGo_Theme_Bridge::get_quick_style_css(), 'polylangActive' => PufferGo_Polylang::is_active(), 'pluginInstallUrl' => current_user_can('install_plugins') ? admin_url('plugin-install.php?s=polylang&tab=search&type=term') : admin_url('plugins.php'), 'coreCssUrl' => plugins_url('assets/css/puffergo.css', PUFFERGO_PLUGIN_FILE), ));
            PufferGo_Runtime::attach('puffergo-tool');
            PufferGo_Workflow_Jobs_REST::add_poll_config_inline_script('puffergo-tool');
        } $css_file = $plugin_dir . 'build/admin/puffergo-tool/style-index.css';

        if (file_exists($css_file)) {
            wp_enqueue_style('puffergo-tool', $plugin_url . 'build/admin/puffergo-tool/style-index.css', array('wp-components'), $version);
        } $index_css = $plugin_dir . 'build/admin/puffergo-tool/index.css';

        if (file_exists($index_css)) {
            $index_deps = file_exists($plugin_dir . 'build/admin/puffergo-tool/style-index.css') ? array('puffergo-tool') : array('wp-components');
            wp_enqueue_style('puffergo-tool-index', $plugin_url . 'build/admin/puffergo-tool/index.css', $index_deps, $version);
        } $block_style_css = $plugin_dir . 'build/blocks/ai-site-builder-app/style-index.css';

        if (file_exists($block_style_css)) {
            wp_enqueue_style('puffergo-tool-edit-tab-styles', $plugin_url . 'build/blocks/ai-site-builder-app/style-index.css', array('puffergo-tool-index'), $version);
        }
    }
} new PufferGo_Tool();
