<?php


require_once __DIR__ . '/../../vendor/autoload.php';


use Sibs2\sibsConfig;
use Sibs2\sibsConstants;
use Sibs2\sibsLogger;
use Sibs2\sibsPayments;
use Sibs2\sibsFunctions;
use Sibs2\sibsBrowser;

defined('ABSPATH') || exit;

class Sibs_Admin
{
    public function __construct()
    {
        add_action('init', array($this, 'init_admin'), 15);
    }

    /**
     * Initialize admin functionality
     */
    public function init_admin()
    {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }
        
        if (is_admin()) {
            add_action('admin_menu', array($this, 'add_admin_menu'));
            add_action('admin_menu', array($this, 'add_beta_tab'));
            add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
            
            // AJAX handlers
            add_action('wp_ajax_sibs_test_blocks_compatibility', array($this, 'ajax_test_blocks_compatibility'));
            add_action('wp_ajax_sibs_migrate_to_blocks', array($this, 'ajax_migrate_to_blocks'));
            add_action('wp_ajax_sibs_save_settings', array($this, 'ajax_save_settings'));
        }
    }

    /**
     * Add main admin menu
     */
    public function add_admin_menu()
    {
        // Menu principal SIBS
        add_menu_page(
            __('SIBS Payment Gateway', 'sibs-woo-stg'),
            __('SIBS', 'sibs-woo-stg'),
            'manage_woocommerce',
            'sibs',
            array($this, 'render_main_page'),
            'dashicons-money-alt',
            56
        );

        // Submenu: Configurações Gerais
        add_submenu_page(
            'sibs',
            __('General Settings', 'sibs-woo-stg'),
            __('General Settings', 'sibs-woo-stg'),
            'manage_woocommerce',
            'sibs',
            array($this, 'render_main_page')
        );
    }

    /**
     * Add Beta tab
     */
    public function add_beta_tab()
    {
        add_submenu_page(
            'sibs',
            __('Beta Features', 'sibs-woo-stg'),
            __('Beta Features', 'sibs-woo-stg'),
            'manage_woocommerce',
            'sibs-beta',
            array($this, 'render_beta_page')
        );
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook)
    {
        // Só carregar nas páginas do SIBS
        if (strpos($hook, 'sibs') === false) {
            return;
        }

        wp_enqueue_style(
            'sibs-admin-style',
            WC_GATEWAY_SIBS_URL . '/assets/css/admin.css',
            array(),
            SIBS_VERSION
        );

        wp_enqueue_script(
            'sibs-admin-script',
            WC_GATEWAY_SIBS_URL . '/assets/js/admin.js',
            array('jquery'),
            SIBS_VERSION,
            true
        );

        // Localizar script
        wp_localize_script('sibs-admin-script', 'sibsAdmin', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('sibs_admin_nonce'),
            'strings' => array(
                'saving' => __('Saving...', 'sibs-woo-stg'),
                'saved' => __('Settings saved successfully!', 'sibs-woo-stg'),
                'error' => __('Error saving settings', 'sibs-woo-stg'),
                'testing' => __('Testing...', 'sibs-woo-stg'),
                'confirm_migrate' => __('Are you sure you want to migrate to blocks?', 'sibs-woo-stg'),
                'confirm_rollback' => __('Are you sure you want to rollback?', 'sibs-woo-stg')
            )
        ));
    }

    /**
     * Render main settings page
     */
    public function render_main_page()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Entrou em render_main_page', sibsConstants::SIBS_LOG);
        }

        // Handle form submission
        $saved = false;
        if (isset($_POST['sibs_save']) && wp_verify_nonce($_POST['sibs_nonce'], 'sibs_save_settings')) {
            $saved = $this->save_settings($_POST);
        }

        // Handle file upload (verificar se sibsConfig está disponível)
        if (class_exists('Sibs2\\sibsConfig') && 
            isset($_FILES[sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association'])) {
            $this->handle_apple_pay_file_upload();
        }

        // Preparar dados para a view
        $view_data = $this->prepare_view_data();

        // Passar dados para a view através de variáveis
        $environment = $view_data['environment'];
        $languages = $view_data['languages'];
        $system_info = $view_data['system_info'];
        $current_settings = $view_data['current_settings'];
        $field_config = $view_data['field_config'];

        include_once WC_GATEWAY_SIBS_PATH . '/includes/admin/views/sibs-main-page.php';
    }

    /**
     * Preparar dados para a view
     */
    private function prepare_view_data()
    {
        $data = array();

        try {
            // Environment data
            if (class_exists('Sibs2\\sibsFunctions')) {
                $environment_file = sibsFunctions::get_environment();
                $data['environment'] = $environment_file['environment'] ?? array();
            } else {
                $data['environment'] = array(
                    'sandbox' => __('Sandbox', 'sibs-woo-stg'),
                    'production' => __('Production', 'sibs-woo-stg')
                );
            }

            // Languages
            if (defined('Sibs2\\sibsConstants::SIBS_LANGUAGES')) {
                $data['languages'] = sibsConstants::SIBS_LANGUAGES;
            } else {
                $data['languages'] = array(
                    'pt' => __('Portuguese', 'sibs-woo-stg'),
                    'en' => __('English', 'sibs-woo-stg')
                );
            }

            // Field configuration - definir nomes dos campos com fallback
            if (class_exists('Sibs2\\sibsConfig')) {
                $config_prefix = sibsConfig::SIBS_GENERAL_CONFIG;
            } else {
                $config_prefix = 'sibs_general_config';
            }

            $data['field_config'] = array(
                'prefix' => $config_prefix,
                'merchant_no' => $config_prefix . '_merchant_no',
                'client_id' => $config_prefix . '_client_id',
                'bearer_token' => $config_prefix . '_bearer_token',
                'environment' => $config_prefix . '_environment',
                'language' => $config_prefix . '_language',
                'webhook_secret' => $config_prefix . '_webhook_secret',
                'merchant_domain_association' => $config_prefix . '_merchant_domain_association'
            );

            // System info
            $data['system_info'] = $this->get_system_info();

             $data['current_settings'] = array(
                    'terminal_id' => sibsConfig::getTerminalId(),
                    'client_id' => sibsConfig::getClientId(),
                    'bearer_token' => sibsConfig::getToken(),
                    'environment' => sibsConfig::getEnvironment(),
                    'language' => sibsConfig::getLanguageDefault(),
                    'webhook_secret' => sibsConfig::getWebhookSecret()
                );

            // Webhook description
            if (class_exists('Sibs2\\sibsPayments')) {
                $data['webhook_description'] = sibsPayments::webhook_description();
            } else {
                $data['webhook_description'] = __('Secret key for webhook validation from SIBS', 'sibs-woo-stg');
            }

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Error preparing view data: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }
            
            // Dados de fallback
            $data = array(
                'environment' => array('sandbox' => 'Sandbox', 'production' => 'Production'),
                'languages' => array('pt' => 'Portuguese', 'en' => 'English'),
                'system_info' => array(),
                'field_config' => array(
                    'prefix' => 'sibs_general_config',
                    'merchant_no' => 'sibs_general_config_merchant_no',
                    'client_id' => 'sibs_general_config_client_id',
                    'bearer_token' => 'sibs_general_config_bearer_token',
                    'environment' => 'sibs_general_config_environment',
                    'language' => 'sibs_general_config_language',
                    'webhook_secret' => 'sibs_general_config_webhook_secret',
                    'merchant_domain_association' => 'sibs_general_config_merchant_domain_association'
                ),
                'current_settings' => array(
                    'terminal_id' => '',
                    'client_id' => '',
                    'bearer_token' => '',
                    'environment' => 'sandbox',
                    'language' => 'pt',
                    'webhook_secret' => ''
                ),
                'webhook_description' => __('Secret key for webhook validation from SIBS', 'sibs-woo-stg')
            );
        }

        return $data;
    }

    /**
     * Render error page
     */
    private function render_error_page($message)
    {
        ?>
        <div class="wrap">
            <h1><?php _e('SIBS Payment Gateway', 'sibs-woo-stg'); ?></h1>
            <div class="notice notice-error">
                <p><strong><?php _e('Error:', 'sibs-woo-stg'); ?></strong> <?php echo esc_html($message); ?></p>
                <p><?php _e('Please deactivate and reactivate the plugin, or contact support.', 'sibs-woo-stg'); ?></p>
            </div>
        </div>
        <?php
    }

    /**
     * Render Beta page
     */
    public function render_beta_page()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Entrou em render_beta_page', sibsConstants::SIBS_LOG);
        }

        // Handle form submissions
        if (isset($_POST['migrate_to_blocks']) && wp_verify_nonce($_POST['sibs_migrate_nonce'], 'sibs_migrate_blocks')) {
            $this->handle_blocks_migration();
        }

        if (isset($_POST['rollback_blocks']) && wp_verify_nonce($_POST['sibs_rollback_nonce'], 'sibs_rollback_blocks')) {
            $this->handle_blocks_rollback();
        }

        include_once WC_GATEWAY_SIBS_PATH . '/includes/admin/views/sibs-beta-page.php';
    }

    /**
     * Save settings
     */
    private function save_settings($post_data)
    {
        try {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::debug('Saving SIBS settings', sibsConstants::SIBS_LOG);
            }

            // Obter configuração de campos
            $view_data = $this->prepare_view_data();
            $field_config = $view_data['field_config'];

            // Validar dados usando configuração dinâmica
            $required_fields = array(
                $field_config['merchant_no'],
                $field_config['client_id'],
                $field_config['bearer_token']
            );

            foreach ($required_fields as $field) {
                if (empty($post_data[$field])) {
                    add_action('admin_notices', function() use ($field) {
                        echo '<div class="notice notice-error is-dismissible"><p>' . 
                             sprintf(__('Field %s is required', 'sibs-woo-stg'), $field) . 
                             '</p></div>';
                    });
                    return false;
                }
            }

            // Salvar usando sibsPayments se disponível, senão usar options diretamente
            if (class_exists('Sibs2\\sibsPayments')) {
                $saved = sibsPayments::saveData($post_data);
            } else {
                // Fallback: salvar diretamente nas opções do WordPress
                $saved = true;
                foreach ($field_config as $key => $field_name) {
                    if ($key !== 'prefix' && isset($post_data[$field_name])) {
                        update_option($field_name, sanitize_text_field($post_data[$field_name]));
                    }
                }
            }

            if ($saved) {
                add_action('admin_notices', function() {
                    echo '<div class="notice notice-success is-dismissible"><p>' . 
                         __('Settings saved successfully!', 'sibs-woo-stg') . 
                         '</p></div>';
                });
            }

            return $saved;

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Error saving settings: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }
            
            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error is-dismissible"><p>' . 
                     __('Error saving settings: ', 'sibs-woo-stg') . esc_html($e->getMessage()) . 
                     '</p></div>';
            });
            
            return false;
        }
    }

    /**
     * Handle Apple Pay file upload
     */
    private function handle_apple_pay_file_upload()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Handling Apple Pay file upload', sibsConstants::SIBS_LOG);
        }

        $domain_onboarding_file_name = 'apple-developer-merchantid-domain-association';
        $domain_onboarding_file_directory = '.well-known';
        $onboarding_file_dir = untrailingslashit(ABSPATH) . '/' . $domain_onboarding_file_directory;
        $onboarding_file_path = $onboarding_file_dir . '/' . $domain_onboarding_file_name;

        try {
            // Criar diretório se não existir
            if (!file_exists($onboarding_file_dir)) {
                if (!wp_mkdir_p($onboarding_file_dir)) {
                    throw new Exception(__('Cannot create .well-known directory', 'sibs-woo-stg'));
                }
            }

            // Validar arquivo
            $file = $_FILES[sibsConfig::SIBS_GENERAL_CONFIG . '_merchant_domain_association'];
            
            if ($file['error'] !== UPLOAD_ERR_OK) {
                throw new Exception(__('File upload error', 'sibs-woo-stg'));
            }

            // Mover arquivo
            if (!move_uploaded_file($file['tmp_name'], $onboarding_file_path)) {
                throw new Exception(__('Cannot move uploaded file', 'sibs-woo-stg'));
            }

            add_action('admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible"><p>' . 
                     __('Apple Pay domain association file uploaded successfully!', 'sibs-woo-stg') . 
                     '</p></div>';
            });

            return true;

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Apple Pay file upload error: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }

            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error is-dismissible"><p>' . 
                     __('Apple Pay file upload failed: ', 'sibs-woo-stg') . esc_html($e->getMessage()) . 
                     '</p></div>';
            });

            return false;
        }
    }

    /**
     * Get system information for sidebar
     */
    public function get_system_info()
    {
        $info = array();

        try {
            // Informações do sistema
            if (class_exists('Sibs2\\sibsPayments')) {
                $info['system'] = array(
                    'title' => __('System Information', 'sibs-woo-stg'),
                    'content' => sibsPayments::version_description()
                );

                // Informações de descriptografia
                $info['decryption'] = array(
                    'title' => __('Decryption Information', 'sibs-woo-stg'),
                    'content' => sibsPayments::decrypt_description()
                );

                // Outras informações
                $info['other'] = array(
                    'title' => __('Other Information', 'sibs-woo-stg'),
                    'content' => sibsPayments::other_description()
                );
            } else {
                // Fallback se sibsPayments não estiver disponível
                $info['system'] = array(
                    'title' => __('System Information', 'sibs-woo-stg'),
                    'content' => $this->get_basic_system_info()
                );
            }

            // Informações do browser
            if (class_exists('Sibs2\\sibsBrowser')) {
                $browser = new sibsBrowser($_SERVER['HTTP_USER_AGENT'] ?? '');
                $browser_info = $browser->__toString();
                
                if (defined('Sibs2\\sibsBrowser::BROWSER_SAFARI') && 
                    $browser->getBrowser() == sibsBrowser::BROWSER_SAFARI) {
                    $browser_info .= '<br>' . __('Safari detected - Apple Pay compatible', 'sibs-woo-stg');
                }

                $info['browser'] = array(
                    'title' => __('Browser Information', 'sibs-woo-stg'),
                    'content' => $browser_info
                );
            } else {
                $info['browser'] = array(
                    'title' => __('Browser Information', 'sibs-woo-stg'),
                    'content' => $_SERVER['HTTP_USER_AGENT'] ?? __('Unknown', 'sibs-woo-stg')
                );
            }

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Error getting system info: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }
            
            $info['error'] = array(
                'title' => __('System Information', 'sibs-woo-stg'),
                'content' => __('Error loading system information', 'sibs-woo-stg')
            );
        }

        return $info;
    }

    /**
     * Get basic system information (fallback)
     */
    private function get_basic_system_info()
    {
        $info = array();
        
        $info[] = '<strong>' . __('Plugin Version:', 'sibs-woo-stg') . '</strong> ' . (defined('SIBS_VERSION') ? SIBS_VERSION : __('Unknown', 'sibs-woo-stg'));
        $info[] = '<strong>' . __('WordPress Version:', 'sibs-woo-stg') . '</strong> ' . get_bloginfo('version');
        $info[] = '<strong>' . __('WooCommerce Version:', 'sibs-woo-stg') . '</strong> ' . (defined('WC_VERSION') ? WC_VERSION : __('Not installed', 'sibs-woo-stg'));
        $info[] = '<strong>' . __('PHP Version:', 'sibs-woo-stg') . '</strong> ' . PHP_VERSION;
        
        return implode('<br>', $info);
    }

    /**
     * Handle blocks migration
     */
    private function handle_blocks_migration()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Starting blocks migration', sibsConstants::SIBS_LOG);
        }

        try {
            // Verificar pré-requisitos
            if (!class_exists('Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry')) {
                throw new Exception(__('WooCommerce Blocks plugin is required', 'sibs-woo-stg'));
            }

            // Ativar suporte para blocks
            update_option('sibs_blocks_enabled', 'yes');
            update_option('sibs_migration_date', current_time('Y-m-d H:i:s'));

            // Migrar configurações
            $this->migrate_gateway_settings_to_blocks();

            // Registrar blocks
            $this->register_payment_blocks();

            add_action('admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible"><p>' . 
                     __('Migration to blocks completed successfully!', 'sibs-woo-stg') . 
                     '</p></div>';
            });

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Migration error: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }

            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error is-dismissible"><p>' . 
                     __('Migration failed: ', 'sibs-woo-stg') . esc_html($e->getMessage()) . 
                     '</p></div>';
            });
        }
    }

    /**
     * Migrate gateway settings to blocks
     */
    private function migrate_gateway_settings_to_blocks()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Migrating gateway settings to blocks', sibsConstants::SIBS_LOG);
        }

        $gateways = ['sibs_stg_cc', 'sibs_stg_xpay', 'sibs_stg_blik', 'sibs_stg_pblkv', 'sibs_stg_pbl'];

        foreach ($gateways as $gateway_id) {
            $settings = get_option('woocommerce_' . $gateway_id . '_settings', array());

            if (!empty($settings)) {
                $block_settings = array_merge($settings, array(
                    'blocks_enabled' => 'yes',
                    'migrated_from_classic' => 'yes',
                    'migration_date' => current_time('Y-m-d H:i:s')
                ));

                update_option('woocommerce_' . $gateway_id . '_blocks_settings', $block_settings);

                if (class_exists('Sibs2\\sibsLogger')) {
                    sibsLogger::debug("Settings migrated for {$gateway_id}", sibsConstants::SIBS_LOG);
                }
            }
        }
    }

    /**
     * Register payment blocks
     */
    private function register_payment_blocks()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Registering payment blocks', sibsConstants::SIBS_LOG);
        }

        // Registrar blocks se não estiverem registrados
        add_action('woocommerce_blocks_payment_method_type_registration', function($payment_method_registry) {
            if (!$payment_method_registry->is_registered('sibs_stg_cc')) {
                $payment_method_registry->register(new WC_Sibs_Blocks_Support('sibs_stg_cc'));
            }
            if (!$payment_method_registry->is_registered('sibs_stg_xpay')) {
                $payment_method_registry->register(new WC_Sibs_Blocks_Support('sibs_stg_xpay'));
            }
            if (!$payment_method_registry->is_registered('sibs_stg_blik')) {
                $payment_method_registry->register(new WC_Sibs_Blocks_Support('sibs_stg_blik'));
            }
            if (!$payment_method_registry->is_registered('sibs_stg_pblkv')) {
                $payment_method_registry->register(new WC_Sibs_Blocks_Support('sibs_stg_pblkv'));
            }
            if (!$payment_method_registry->is_registered('sibs_stg_pbl')) {
                $payment_method_registry->register(new WC_Sibs_Blocks_Support('sibs_stg_pbl'));
            }
        });
    }

    /**
     * Handle blocks rollback
     */
    private function handle_blocks_rollback()
    {
        if (class_exists('Sibs2\\sibsLogger')) {
            sibsLogger::debug('Rolling back blocks', sibsConstants::SIBS_LOG);
        }

        try {
            update_option('sibs_blocks_enabled', 'no');
            update_option('sibs_rollback_date', current_time('Y-m-d H:i:s'));

            add_action('admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible"><p>' . 
                     __('Rollback completed successfully!', 'sibs-woo-stg') . 
                     '</p></div>';
            });

        } catch (Exception $e) {
            if (class_exists('Sibs2\\sibsLogger')) {
                sibsLogger::error('Rollback error: ' . $e->getMessage(), sibsConstants::SIBS_LOG);
            }
        }
    }

    /**
     * Get migration status
     */
    public function get_migration_status()
    {
        $gateways = array(
            'sibs_stg_cc' => __('Credit Card', 'sibs-woo-stg'),
            'sibs_stg_xpay' => __('Apple Pay', 'sibs-woo-stg'),
            'sibs_stg_blik' => __('BLIK', 'sibs-woo-stg'),
            'sibs_stg_pblkv' => __('Pay by Link KV', 'sibs-woo-stg'),
            'sibs_stg_pbl' => __('Pay by Link', 'sibs-woo-stg')
        );

        $status = array();

        foreach ($gateways as $gateway_id => $gateway_name) {
            $classic_settings = get_option('woocommerce_' . $gateway_id . '_settings', array());
            $blocks_settings = get_option('woocommerce_' . $gateway_id . '_blocks_settings', array());

            $status[$gateway_id] = array(
                'name' => $gateway_name,
                'classic_enabled' => isset($classic_settings['enabled']) && $classic_settings['enabled'] === 'yes',
                'blocks_ready' => file_exists(WC_GATEWAY_SIBS_PATH . '/build/' . str_replace('_', '-', $gateway_id) . '.js'),
                'migrated' => !empty($blocks_settings) && isset($blocks_settings['migrated_from_classic'])
            );
        }

        return $status;
    }

    /**
     * AJAX: Test blocks compatibility
     */
    public function ajax_test_blocks_compatibility()
    {
        check_ajax_referer('sibs_admin_nonce', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'sibs-woo-stg'));
        }

        $tests = array();

        // Test WooCommerce Blocks
        $blocks_active = class_exists('Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry');
        $tests[] = array(
            'test' => __('WooCommerce Blocks Plugin', 'sibs-woo-stg'),
            'result' => $blocks_active,
            'message' => $blocks_active ? __('Active', 'sibs-woo-stg') : __('Not installed', 'sibs-woo-stg')
        );

        // Test WordPress version
        $wp_version = get_bloginfo('version');
        $wp_compatible = version_compare($wp_version, '5.9', '>=');
        $tests[] = array(
            'test' => __('WordPress Version', 'sibs-woo-stg'),
            'result' => $wp_compatible,
            'message' => sprintf(__('Version %s (Required: 5.9+)', 'sibs-woo-stg'), $wp_version)
        );

        // Test WooCommerce version
        if (defined('WC_VERSION')) {
            $wc_compatible = version_compare(WC_VERSION, '7.4', '>=');
            $tests[] = array(
                'test' => __('WooCommerce Version', 'sibs-woo-stg'),
                'result' => $wc_compatible,
                'message' => sprintf(__('Version %s (Required: 7.4+)', 'sibs-woo-stg'), WC_VERSION)
            );
        }

        // Test block files
        $block_files = ['sibs-stg-cc.js', 'sibs-stg-xpay.js', 'sibs-stg-blik.js', 'sibs-stg-pblkv.js', 'sibs-stg-pbl.js'];
        foreach ($block_files as $file) {
            $exists = file_exists(WC_GATEWAY_SIBS_PATH . '/build/' . $file);
            $tests[] = array(
                'test' => sprintf(__('Block file: %s', 'sibs-woo-stg'), $file),
                'result' => $exists,
                'message' => $exists ? __('Found', 'sibs-woo-stg') : __('Missing - run npm run build', 'sibs-woo-stg')
            );
        }

        // Generate HTML
        $output = '<table class="widefat">';
        $output .= '<thead><tr><th>' . __('Test', 'sibs-woo-stg') . '</th><th>' . __('Result', 'sibs-woo-stg') . '</th></tr></thead><tbody>';

        foreach ($tests as $test) {
            $icon = $test['result'] ? 'dashicons-yes-alt' : 'dashicons-dismiss';
            $color = $test['result'] ? 'green' : 'red';
            $output .= '<tr><td>' . esc_html($test['test']) . '</td>';
            $output .= '<td><span class="dashicons ' . $icon . '" style="color: ' . $color . ';"></span> ' . esc_html($test['message']) . '</td></tr>';
        }

        $output .= '</tbody></table>';

        wp_send_json_success($output);
    }

    /**
     * AJAX: Save settings
     */
    public function ajax_save_settings()
    {
        check_ajax_referer('sibs_admin_nonce', 'nonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_die(__('Permission denied', 'sibs-woo-stg'));
        }

        $saved = $this->save_settings($_POST);

        if ($saved) {
            wp_send_json_success(__('Settings saved successfully!', 'sibs-woo-stg'));
        } else {
            wp_send_json_error(__('Error saving settings', 'sibs-woo-stg'));
        }
    }
}

// Inicializar apenas no admin
if (is_admin()) {
    new Sibs_Admin();
}