<?php
namespace GrCop;

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

class GrCop_Main
{
    /**
     * Constructor registers hooks.
     */
    public function __construct()
    {
        // Load textdomain
        add_action('init', [$this, 'load_textdomain']);

        // Initialize sub-components when WooCommerce is active
        add_action('woocommerce_init', [$this, 'init_components'], 20);

        // General admin hooks
        if (is_admin()) {
            add_action('admin_init', [$this, 'admin_init']);
            add_action('admin_menu', [$this, 'admin_menu']);
            add_action('admin_menu', [$this, 'register_setup_wizard_page']);
            add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_assets']);
            add_filter('woocommerce_get_settings_pages', [$this, 'add_settings_page']);
            
            $plugin = plugin_basename(GRCOP_PLUGIN_FILE);
            add_filter("plugin_action_links_$plugin", [$this, 'add_plugin_settings_link']);
            add_action('admin_post_grcop_export_csv', [$this, 'handle_csv_export']);
            add_action('wp_ajax_grcop_save_wizard_settings', [$this, 'ajax_save_wizard_settings']);
            
            // Custom settings field hooks and AJAX
            add_action('woocommerce_admin_field_grcop_log_viewer', [$this, 'render_log_viewer']);
            add_action('woocommerce_admin_field_color', [$this, 'render_color_field']);
            add_action('wp_ajax_grcop_clear_debug_logs', [$this, 'ajax_clear_debug_logs']);

            // Custom Orders List Columns (Classic & HPOS)
            add_filter('manage_edit-shop_order_columns', [$this, 'add_orders_list_column'], 20);
            add_action('manage_shop_order_posts_custom_column', [$this, 'render_orders_list_column_content'], 20, 2);
            add_filter('manage_woocommerce_page_wc-orders_columns', [$this, 'add_orders_list_column'], 20);
            add_action('manage_woocommerce_page_wc-orders_custom_column', [$this, 'render_orders_list_hpos_column_content'], 20, 2);

            // Custom Order Edit Meta Box
            add_action('add_meta_boxes', [$this, 'register_order_meta_box']);

            // GDPR Personal Data Export & Deletion
            add_filter('wp_privacy_exports', [$this, 'register_privacy_exporter']);
            add_filter('wp_privacy_erasers', [$this, 'register_privacy_eraser']);
        }

        // Frontend script & style enqueueing
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);

        // REST API init hooks
        add_action('rest_api_init', [$this, 'register_rest_routes']);
    }

    /**
     * Loads plugin textdomain for localization.
     */
    public function load_textdomain()
    {
        // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound
        load_plugin_textdomain(
            'gr-odstop-od-pogodbe',
            false,
            dirname(plugin_basename(GRCOP_PLUGIN_FILE)) . '/languages'
        );
    }

    /**
     * Initializes components after WooCommerce is loaded.
     */
    public function init_components()
    {
        // Create form logic
        new GrCop_Form();
    }

    /**
     * Activation logic. Creates the database table and automatically sets up the return form page.
     */
    public static function activate()
    {
        // Call Log helper to create database table
        GrCop_Log::create_table();

        // Auto-create page if not already set
        $page_id = get_option('grcop_form_page');
        if (empty($page_id)) {
            // Check if page already exists with the shortcode to avoid duplicates
            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $existing_page_id = $wpdb->get_var("
                SELECT ID FROM $wpdb->posts 
                WHERE post_content LIKE '%[gr_odstop_od_pogodbe_form]%' 
                AND post_type = 'page' 
                AND post_status = 'publish' 
                LIMIT 1
            ");

            if ($existing_page_id) {
                update_option('grcop_form_page', $existing_page_id);
            } else {
                $post_data = [
                    'post_title'   => __('Odstop od pogodbe', 'gr-odstop-od-pogodbe'),
                    'post_content' => '[gr_odstop_od_pogodbe_form]',
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_author'  => 1,
                    'post_comment_status' => 'closed',
                    'post_ping_status'    => 'closed',
                ];
                
                // Include post.php core file if not loaded (sometimes during activation hooks)
                if (!function_exists('wp_insert_post')) {
                    require_once ABSPATH . 'wp-admin/includes/post.php';
                }
                
                $new_page_id = wp_insert_post($post_data);
                if ($new_page_id && !is_wp_error($new_page_id)) {
                    update_option('grcop_form_page', $new_page_id);
                }
            }
        }

        // Set transient/option to trigger settings redirect on next page load
        update_option('grcop_do_activation_redirect', true);
    }

    /**
     * Deactivation logic.
     */
    public static function deactivate()
    {
        // Nothing major to flush, keep data to avoid loss.
    }

    /**
     * Admin warnings (like missing WooCommerce) and settings check.
     */
    public function admin_init()
    {
        if (wp_doing_ajax()) {
            return;
        }

        // Handle activation redirect
        if (get_option('grcop_do_activation_redirect', false)) {
            delete_option('grcop_do_activation_redirect');
            if (class_exists('WooCommerce') && current_user_can('manage_woocommerce')) {
                if (get_option('grcop_setup_wizard_completed', 'no') !== 'yes') {
                    wp_safe_redirect(admin_url('admin.php?page=grcop-setup-wizard'));
                } else {
                    wp_safe_redirect(admin_url('admin.php?page=wc-settings&tab=grcop_settings'));
                }
                exit;
            }
        }

        if (!class_exists('WooCommerce')) {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error"><p>' .
                    esc_html__('Vtičnik GR Odstop od pogodbe potrebuje WooCommerce za delovanje!', 'gr-odstop-od-pogodbe') .
                    '</p></div>';
            });
        }

        // Check if settings page is set up properly
        $page_id = get_option('grcop_form_page');
        $page_exists = $page_id ? get_post($page_id) : false;

        if (!$page_id || !$page_exists || 'publish' !== $page_exists->post_status) {
            add_action('admin_notices', [$this, 'render_missing_page_notice']);
        }
    }

    /**
     * Render warning notice if the return page is not set up correctly.
     */
    public function render_missing_page_notice()
    {
        // Show notice only to administrators
        if (!current_user_can('manage_options')) {
            return;
        }
        
        $settings_url = admin_url('admin.php?page=wc-settings&tab=grcop_settings');
        ?>
        <div class="notice notice-warning is-dismissible">
            <p>
                <strong><?php esc_html_e('GR Odstop od pogodbe:', 'gr-odstop-od-pogodbe'); ?></strong>
                <?php esc_html_e('Stran z obrazcem za odstop ni izbrana ali pa ne obstaja. Prosimo, izberite jo v nastavitvah, da bodo gumbi in e-poštne povezave delovali pravilno.', 'gr-odstop-od-pogodbe'); ?>
                <a href="<?php echo esc_url($settings_url); ?>" class="button button-small" style="margin-left: 10px;"><?php esc_html_e('Uredi nastavitve', 'gr-odstop-od-pogodbe'); ?></a>
            </p>
        </div>
        <?php
    }

    /**
     * Registers custom menu page under WooCommerce for withdrawals log.
     */
    public function admin_menu()
    {
        add_submenu_page(
            'woocommerce',
            __('Odstopi od pogodbe', 'gr-odstop-od-pogodbe'),
            __('Odstopi od pogodbe', 'gr-odstop-od-pogodbe'),
            'manage_options',
            'grcop-withdrawals-log',
            [$this, 'render_withdrawals_log_page']
        );
    }

    /**
     * Renders the withdrawals log page in WordPress admin.
     */
    public function render_withdrawals_log_page()
    {
        $log_list_table = new GrCop_Log();
        $log_list_table->prepare_items();
        
        $export_url = admin_url('admin-post.php?action=grcop_export_csv&_wpnonce=' . wp_create_nonce('grcop_export_csv'));

        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e('Evidenca odstopov od pogodb', 'gr-odstop-od-pogodbe'); ?></h1>
            <a href="<?php echo esc_url($export_url); ?>" class="page-title-action"><?php esc_html_e('Izvozi v CSV', 'gr-odstop-od-pogodbe'); ?></a>
            <hr class="wp-header-end">
            
            <form id="grcop-withdrawals-log-form" method="get">
                <input type="hidden" name="page" value="grcop-withdrawals-log" />
                <?php
                $log_list_table->views();
                $log_list_table->display();
                ?>
            </form>
        </div>
        <?php
    }

    /**
     * Handle CSV Export.
     */
    public function handle_csv_export()
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Nimate dovoljenja za dostop do te strani.', 'gr-odstop-od-pogodbe'));
        }

        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'grcop_export_csv')) {
            wp_die(esc_html__('Neveljavna varnostna koda.', 'gr-odstop-od-pogodbe'));
        }

        GrCop_Log::export_to_csv();
        exit;
    }

    /**
     * Enqueue CSS and JS assets on the frontend.
     */
    public function enqueue_frontend_assets()
    {
        $css_path = plugin_dir_path(GRCOP_PLUGIN_FILE) . 'src/assets/css/main.css';
        $css_version = file_exists($css_path) ? filemtime($css_path) : '1.0.0';
        wp_enqueue_style(
            'grcop-frontend-css',
            plugin_dir_url(GRCOP_PLUGIN_FILE) . 'src/assets/css/main.css',
            [],
            $css_version
        );

        // Inject custom button colors and border-radius
        $bg_color = get_option('grcop_btn_bg_color', '#2563eb');
        $text_color = get_option('grcop_btn_text_color', '#ffffff');
        $radius = get_option('grcop_btn_border_radius', '6');
        
        $form_bg = get_option('grcop_form_bg_color', '#ffffff');
        $form_radius = get_option('grcop_form_border_radius', '12');

        $custom_css = "
            :root {
                --grcop-primary: " . esc_attr($bg_color) . ";
                --grcop-primary-hover: " . esc_attr($bg_color) . ";
                --grcop-btn-text: " . esc_attr($text_color) . ";
                --grcop-radius-sm: " . esc_attr($radius) . "px;
                --grcop-background: " . esc_attr($form_bg) . ";
                --grcop-radius-lg: " . esc_attr($form_radius) . "px;
                --grcop-radius-md: " . esc_attr(floor(intval($form_radius) * 0.75)) . "px;
            }
        ";
        wp_add_inline_style('grcop-frontend-css', $custom_css);

        $js_path = plugin_dir_path(GRCOP_PLUGIN_FILE) . 'src/assets/js/main.js';
        $js_version = file_exists($js_path) ? filemtime($js_path) : '1.0.0';
        wp_enqueue_script(
            'grcop-frontend-js',
            plugin_dir_url(GRCOP_PLUGIN_FILE) . 'src/assets/js/main.js',
            ['jquery'],
            $js_version,
            true
        );

        // Localize for AJAX
        wp_localize_script('grcop-frontend-js', 'grcop_ajax', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('grcop_frontend_nonce'),
            'strings'  => [
                'error_select_item' => __('Prosimo, izberite vsaj en izdelek za odstop.', 'gr-odstop-od-pogodbe'),
                'error_qty'         => __('Neveljavna količina za vračilo.', 'gr-odstop-od-pogodbe'),
                'confirm_title'     => __('Potrditev odstopa', 'gr-odstop-od-pogodbe'),
                'confirm_text'      => __('Ali ste prepričani, da želite odstopiti od pogodbe za izbrane izdelke?', 'gr-odstop-od-pogodbe'),
                'confirm_button'    => __('Da, potrdi odstop', 'gr-odstop-od-pogodbe'),
                'cancel_button'     => __('Prekliči', 'gr-odstop-od-pogodbe')
            ]
        ]);
    }

    /**
     * Enqueue CSS assets on the backend.
     */
    public function admin_enqueue_assets($hook)
    {
        if (
            'woocommerce_page_wc-settings' === $hook ||
            'woocommerce_page_grcop-withdrawals-log' === $hook ||
            'toplevel_page_woocommerce' === $hook ||
            'edit.php' === $hook ||
            'woocommerce_page_wc-orders' === $hook ||
            'post.php' === $hook
        ) {
            $css_path = plugin_dir_path(GRCOP_PLUGIN_FILE) . 'src/assets/css/main.css';
            $css_version = file_exists($css_path) ? filemtime($css_path) : '1.0.0';
            wp_enqueue_style(
                'grcop-admin-css',
                plugin_dir_url(GRCOP_PLUGIN_FILE) . 'src/assets/css/main.css',
                [],
                $css_version
            );
        }
    }

    /**
     * Adds Settings Tab.
     */
    public function add_settings_page($settings)
    {
        if (class_exists('WC_Settings_Page')) {
            $settings[] = new WC_Settings_GrCop();
        }
        return $settings;
    }

    /**
     * Adds settings link next to the plugin name in Plugins page.
     */
    public function add_plugin_settings_link($links)
    {
        $links[] = '<a href="admin.php?page=wc-settings&tab=grcop_settings">' . esc_html__('Nastavitve', 'gr-odstop-od-pogodbe') . '</a>';
        return $links;
    }

    /**
     * Render the custom log viewer setting field.
     */
    public function render_log_viewer($value)
    {
        $upload_dir = wp_upload_dir();
        $log_file = $upload_dir['basedir'] . '/grcop-logs/debug.log';
        $logs = '';

        if (file_exists($log_file)) {
            $file_lines = @file($log_file);
            if (is_array($file_lines)) {
                $last_lines = array_slice($file_lines, -100);
                $logs = implode('', $last_lines);
            }
        }

        if (empty($logs)) {
            $logs = __('Ni podatkov v logu.', 'gr-odstop-od-pogodbe');
        }

        $is_checked = get_option('grcop_enable_debug_logging') === 'yes';
        $display = $is_checked ? 'table-row' : 'none';

        ?>
        <tr valign="top" id="grcop-log-viewer-row" style="display: <?php echo esc_attr($display); ?>;">
            <th scope="row" class="titledesc">
                <label><?php echo esc_html($value['title']); ?></label>
            </th>
            <td class="forminp forminp-textarea">
                <textarea readonly style="width: 100%; height: 250px; font-family: monospace; font-size: 12px; background: #fafafa; color: #333; border: 1px solid #ccc; padding: 10px;" id="grcop-logs-textarea"><?php echo esc_textarea($logs); ?></textarea>
                <p class="description"><?php echo esc_html($value['desc']); ?></p>
                <button type="button" class="button" id="grcop-clear-logs-btn" style="margin-top: 10px;"><?php esc_html_e('Počisti loge', 'gr-odstop-od-pogodbe'); ?></button>
            </td>
        </tr>
        <script>
            jQuery(document).ready(function($) {
                // Toggle log viewer display when checkbox is changed
                $('#grcop_enable_debug_logging').on('change', function() {
                    if ($(this).is(':checked')) {
                        $('#grcop-log-viewer-row').show();
                    } else {
                        $('#grcop-log-viewer-row').hide();
                    }
                });

                // Clear logs click
                $('#grcop-clear-logs-btn').on('click', function(e) {
                    e.preventDefault();
                    if (confirm('<?php echo esc_js(__('Ali ste prepričani, da želite počistiti log datoteko?', 'gr-odstop-od-pogodbe')); ?>')) {
                        $.post(ajaxurl, {
                            action: 'grcop_clear_debug_logs',
                            security: '<?php echo esc_attr(wp_create_nonce("grcop_clear_debug_logs")); ?>'
                        }, function(response) {
                            if (response.success) {
                                $('#grcop-logs-textarea').val('<?php echo esc_js(__('Log datoteka je bila počiščena.', 'gr-odstop-od-pogodbe')); ?>');
                            } else {
                                alert(response.data.message);
                            }
                        });
                    }
                });
            });
        </script>
        <?php
    }

    /**
     * AJAX endpoint to clear logs.
     */
    public function ajax_clear_debug_logs()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Nimate dovoljenja.', 'gr-odstop-od-pogodbe')]);
        }
        check_ajax_referer('grcop_clear_debug_logs', 'security');

        $upload_dir = wp_upload_dir();
        $log_file = $upload_dir['basedir'] . '/grcop-logs/debug.log';
        if (file_exists($log_file)) {
            @file_put_contents($log_file, '');
            wp_send_json_success();
            return;
        }
        wp_send_json_error(['message' => __('Log datoteka ne obstaja.', 'gr-odstop-od-pogodbe')]);
    }

    /**
     * Render a custom color picker settings field.
     */
    public function render_color_field($value)
    {
        $option_value = get_option($value['id'], $value['default']);
        $tooltip_html = '';
        if (isset($value['desc_tip']) && true === $value['desc_tip']) {
            $tooltip_html = wc_help_tip($value['desc']);
        }

        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
                <?php echo wp_kses_post($tooltip_html); ?>
            </th>
            <td class="forminp forminp-color">
                <div style="display: flex; align-items: center; gap: 8px;">
                    <input
                        name="<?php echo esc_attr($value['id']); ?>"
                        id="<?php echo esc_attr($value['id']); ?>"
                        type="color"
                        style="width: 40px; height: 30px; padding: 0; border: 1px solid #ccc; cursor: pointer; vertical-align: middle;"
                        value="<?php echo esc_attr($option_value); ?>"
                        class="<?php echo esc_attr($value['class'] ?? ''); ?>"
                    />
                    <input
                        type="text"
                        id="<?php echo esc_attr($value['id']); ?>_text"
                        value="<?php echo esc_attr($option_value); ?>"
                        style="width: 100px; font-family: monospace; vertical-align: middle;"
                        oninput="document.getElementById('<?php echo esc_attr($value['id']); ?>').value = this.value;"
                    />
                    <script>
                        document.getElementById('<?php echo esc_attr($value['id']); ?>').addEventListener('input', function() {
                            document.getElementById('<?php echo esc_attr($value['id']); ?>_text').value = this.value;
                        });
                    </script>
                </div>
                <?php if (isset($value['desc_tip']) && false === $value['desc_tip'] && !empty($value['desc'])) : ?>
                    <p class="description"><?php echo esc_html($value['desc']); ?></p>
                <?php endif; ?>
            </td>
        </tr>
        <?php
    }

    /**
     * Add column header to WooCommerce order list.
     */
    public function add_orders_list_column($columns)
    {
        $new_columns = [];
        foreach ($columns as $key => $column) {
            $new_columns[$key] = $column;
            if ('order_number' === $key || 'order_title' === $key) {
                $new_columns['grcop_withdrawal'] = __('Odstop', 'gr-odstop-od-pogodbe');
            }
        }
        if (!isset($new_columns['grcop_withdrawal'])) {
            $new_columns['grcop_withdrawal'] = __('Odstop', 'gr-odstop-od-pogodbe');
        }
        return $new_columns;
    }

    /**
     * Render column content for classic order list.
     */
    public function render_orders_list_column_content($column, $post_id)
    {
        if ('grcop_withdrawal' === $column) {
            $this->display_list_badge($post_id);
        }
    }

    /**
     * Render column content for HPOS order list.
     */
    public function render_orders_list_hpos_column_content($column, $order)
    {
        if ('grcop_withdrawal' === $column && is_a($order, 'WC_Order')) {
            $this->display_list_badge($order->get_id());
        }
    }

    /**
     * Helper to render the badge based on request status in orders listing.
     */
    private function display_list_badge($order_id)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $request = $wpdb->get_row($wpdb->prepare("SELECT status FROM $table_name WHERE order_id = %d ORDER BY created_at DESC LIMIT 1", $order_id));

        if ($request) {
            $status = $request->status;
            $labels = [
                'pending'  => __('V obdelavi', 'gr-odstop-od-pogodbe'),
                'approved' => __('Odobreno', 'gr-odstop-od-pogodbe'),
                'refunded' => __('Povrnjeno', 'gr-odstop-od-pogodbe'),
                'rejected' => __('Zavrnjeno', 'gr-odstop-od-pogodbe')
            ];
            $label = $labels[$status] ?? ucfirst($status);
            $class = 'grcop-status-' . esc_attr($status);
            echo sprintf('<span class="grcop-status-badge %s" style="font-size:10px; padding:2px 6px;">%s</span>', esc_attr($class), esc_html($label));
        } else {
            echo '<span class="na">&ndash;</span>';
        }
    }

    /**
     * Register order meta boxes for both HPOS and classic layout.
     */
    public function register_order_meta_box()
    {
        $screens = ['shop_order', 'woocommerce_page_wc-orders'];
        foreach ($screens as $screen) {
            add_meta_box(
                'grcop_withdrawal_details_box',
                __('Zahtevki za odstop od pogodbe', 'gr-odstop-od-pogodbe'),
                [$this, 'render_order_meta_box'],
                $screen,
                'side',
                'high'
            );
        }
    }

    /**
     * Render meta box with withdrawal details on WooCommerce edit order page.
     */
    public function render_order_meta_box($post_or_order)
    {
        $order_id = 0;
        if (is_a($post_or_order, 'WP_Post')) {
            $order_id = $post_or_order->ID;
        } elseif (is_a($post_or_order, 'WC_Order')) {
            $order_id = $post_or_order->get_id();
        } elseif (is_numeric($post_or_order)) {
            $order_id = intval($post_or_order);
        }

        if ($order_id <= 0) {
            echo '<p>' . esc_html__('Naročilo ni najdeno.', 'gr-odstop-od-pogodbe') . '</p>';
            return;
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $requests = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE order_id = %d ORDER BY created_at DESC", $order_id), ARRAY_A);

        if (empty($requests)) {
            echo '<p class="description">' . esc_html__('Za to naročilo ni bil oddan noben zahtevek za odstop.', 'gr-odstop-od-pogodbe') . '</p>';
            return;
        }

        $labels = [
            'pending'  => __('V obdelavi', 'gr-odstop-od-pogodbe'),
            'approved' => __('Odobreno', 'gr-odstop-od-pogodbe'),
            'refunded' => __('Povrnjeno', 'gr-odstop-od-pogodbe'),
            'rejected' => __('Zavrnjeno', 'gr-odstop-od-pogodbe')
        ];

        foreach ($requests as $req) {
            $status = $req['status'];
            $label = $labels[$status] ?? ucfirst($status);
            $class = 'grcop-status-' . esc_attr($status);
            $date = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($req['created_at']));
            $items = json_decode($req['items_json'], true);

            echo '<div style="border-bottom: 1px solid #eee; padding-bottom: 12px; margin-bottom: 12px;">';
            echo '<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 8px;">';
            echo '<span class="description" style="font-size:11px;">' . esc_html($date) . '</span>';
            echo sprintf('<span class="grcop-status-badge %s" style="font-size:10px; padding:2px 6px;">%s</span>', esc_attr($class), esc_html($label));
            echo '</div>';

            echo '<p style="margin:4px 0;"><strong>' . esc_html__('Artikli za vračilo:', 'gr-odstop-od-pogodbe') . '</strong></p>';
            if (is_array($items)) {
                echo '<ul style="margin:4px 0 8px 16px; padding:0; list-style-type:disc;">';
                foreach ($items as $itm) {
                    echo '<li>' . esc_html($itm['name']) . ' x <strong>' . esc_html($itm['qty']) . '</strong></li>';
                }
                echo '</ul>';
            }

            $method_labels = [
                'original' => __('Originalna metoda', 'gr-odstop-od-pogodbe'),
                'iban'     => __('Vračilo na TRR (IBAN)', 'gr-odstop-od-pogodbe'),
                'coupon'   => __('Dobropis / Kupon', 'gr-odstop-od-pogodbe'),
                'default'  => __('Zakonito vračilo', 'gr-odstop-od-pogodbe')
            ];
            $method = $method_labels[$req['refund_method']] ?? esc_html($req['refund_method']);
            echo '<p style="margin:4px 0; font-size:12px;"><strong>' . esc_html__('Način vračila:', 'gr-odstop-od-pogodbe') . '</strong> ' . esc_html($method) . '</p>';
            
            if (!empty($req['refund_details'])) {
                echo '<p style="margin:4px 0; font-size:11px; background:#fafafa; border:1px solid #eee; padding:6px; font-family:monospace; white-space:pre-wrap;">' . esc_html($req['refund_details']) . '</p>';
            }
            echo '</div>';
        }

        echo '<div style="margin-top: 12px; text-align:right;">';
        echo '<a href="' . esc_url(admin_url('admin.php?page=grcop-withdrawals-log')) . '" class="button button-small">' . esc_html__('Uredi odstope', 'gr-odstop-od-pogodbe') . '</a>';
        echo '</div>';
    }

    /**
     * Register privacy exporter for GDPR.
     */
    public function register_privacy_exporter($exporters)
    {
        $exporters['grcop-withdrawals'] = [
            'exporter_friendly_name' => __('GR Odstopi od pogodbe', 'gr-odstop-od-pogodbe'),
            'callback'               => [$this, 'privacy_exporter_callback'],
        ];
        return $exporters;
    }

    /**
     * Callback to export personal data related to contract withdrawals.
     */
    public function privacy_exporter_callback($email_address, $page = 1)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';
        $number = 100;
        $offset = ($page - 1) * $number;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE customer_email = %s ORDER BY created_at DESC LIMIT %d OFFSET %d", $email_address, $number, $offset));

        $data_to_export = [];

        foreach ($results as $row) {
            $items = json_decode($row->items_json, true);
            $items_str = '';
            if (is_array($items)) {
                $item_parts = [];
                foreach ($items as $item) {
                    $item_parts[] = $item['name'] . ' x ' . $item['qty'];
                }
                $items_str = implode(', ', $item_parts);
            }

            $data_to_export[] = [
                'group_id'    => 'grcop-withdrawals-log',
                'group_label' => __('Odstopi od pogodb', 'gr-odstop-od-pogodbe'),
                'item_id'     => 'grcop-withdrawal-' . $row->id,
                'data'        => [
                    [
                        'name'  => __('Številka naročila', 'gr-odstop-od-pogodbe'),
                        'value' => $row->order_id,
                    ],
                    [
                        'name'  => __('Kupec', 'gr-odstop-od-pogodbe'),
                        'value' => $row->customer_name,
                    ],
                    [
                        'name'  => __('E-pošta', 'gr-odstop-od-pogodbe'),
                        'value' => $row->customer_email,
                    ],
                    [
                        'name'  => __('Vrnjeni artikli', 'gr-odstop-od-pogodbe'),
                        'value' => $items_str,
                    ],
                    [
                        'name'  => __('Metoda vračila', 'gr-odstop-od-pogodbe'),
                        'value' => $row->refund_method,
                    ],
                    [
                        'name'  => __('Podrobnosti vračila', 'gr-odstop-od-pogodbe'),
                        'value' => $row->refund_details,
                    ],
                    [
                        'name'  => __('Status', 'gr-odstop-od-pogodbe'),
                        'value' => $row->status,
                    ],
                    [
                        'name'  => __('IP Naslov', 'gr-odstop-od-pogodbe'),
                        'value' => $row->ip_address,
                    ],
                    [
                        'name'  => __('Ustvarjeno ob', 'gr-odstop-od-pogodbe'),
                        'value' => $row->created_at,
                    ],
                ],
            ];
        }

        $done = count($results) < $number;
        return [
            'data' => $data_to_export,
            'done' => $done,
        ];
    }

    /**
     * Register privacy eraser for GDPR.
     */
    public function register_privacy_eraser($erasers)
    {
        $erasers['grcop-withdrawals'] = [
            'eraser_friendly_name' => __('GR Odstopi od pogodbe', 'gr-odstop-od-pogodbe'),
            'callback'             => [$this, 'privacy_eraser_callback'],
        ];
        return $erasers;
    }

    /**
     * Callback to erase personal data related to contract withdrawals.
     */
    public function privacy_eraser_callback($email_address, $page = 1)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';
        $number = 100;
        $offset = ($page - 1) * $number;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $results = $wpdb->get_results($wpdb->prepare("SELECT id FROM $table_name WHERE customer_email = %s LIMIT %d OFFSET %d", $email_address, $number, $offset));

        $items_removed = 0;
        $items_retained = 0;

        foreach ($results as $row) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $updated = $wpdb->update(
                $table_name,
                [
                    'customer_name'  => __('Anonimizirano', 'gr-odstop-od-pogodbe'),
                    'customer_email' => 'deleted@localhost',
                    'refund_details' => __('Podatki izbrisani zaradi zahtevka za zasebnost', 'gr-odstop-od-pogodbe'),
                    'ip_address'     => '0.0.0.0',
                    'user_agent'     => 'Anonymized',
                ],
                ['id' => $row->id]
            );

            if ($updated !== false) {
                $items_removed++;
            } else {
                $items_retained++;
            }
        }

        $done = count($results) < $number;
        return [
            'items_removed'  => $items_removed,
            'items_retained' => $items_retained,
            'messages'       => [],
            'done'           => $done,
        ];
    }

    /**
     * Register custom REST API routes for contract withdrawals.
     */
    public function register_rest_routes()
    {
        register_rest_route('grcop/v1', '/withdrawals', [
            [
                'methods'             => \WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_api_withdrawals'],
                'permission_callback' => [$this, 'check_api_permissions'],
            ]
        ]);

        register_rest_route('grcop/v1', '/withdrawals/(?P<id>\d+)', [
            [
                'methods'             => \WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_api_withdrawal'],
                'permission_callback' => [$this, 'check_api_permissions'],
            ],
            [
                'methods'             => \WP_REST_Server::EDITABLE,
                'callback'            => [$this, 'update_api_withdrawal_status'],
                'permission_callback' => [$this, 'check_api_permissions'],
                'args'                => [
                    'status' => [
                        'required'          => true,
                        'sanitize_callback' => 'sanitize_text_field',
                        'validate_callback' => function($param) {
                            return in_array($param, ['pending', 'approved', 'refunded', 'rejected']);
                        }
                    ]
                ]
            ]
        ]);
    }

    /**
     * Permission callback for secure REST API endpoints.
     */
    public function check_api_permissions()
    {
        return current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }

    /**
     * GET endpoint: Retrieve contract withdrawals.
     */
    public function get_api_withdrawals($request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';

        $page = $request->get_param('page') ? intval($request->get_param('page')) : 1;
        $per_page = $request->get_param('per_page') ? intval($request->get_param('per_page')) : 20;
        $status = $request->get_param('status') ? sanitize_text_field($request->get_param('status')) : '';
        $order_id = $request->get_param('order_id') ? intval($request->get_param('order_id')) : 0;

        $offset = ($page - 1) * $per_page;

        $where = ['1=1'];
        $params = [];

        if (!empty($status)) {
            $where[] = "status = %s";
            $params[] = $status;
        }

        if ($order_id > 0) {
            $where[] = "order_id = %d";
            $params[] = $order_id;
        }

        $where_sql = implode(' AND ', $where);

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $sql = "SELECT * FROM $table_name WHERE $where_sql ORDER BY created_at DESC LIMIT %d OFFSET %d";
        $params[] = $per_page;
        $params[] = $offset;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $results = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A);

        foreach ($results as &$row) {
            $row['items'] = json_decode($row['items_json'], true);
            unset($row['items_json']);
        }

        return rest_ensure_response($results);
    }

    /**
     * GET endpoint: Retrieve a single contract withdrawal request.
     */
    public function get_api_withdrawal($request)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'grcop_withdrawals';
        $id = intval($request['id']);

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $id), ARRAY_A);
        if (!$row) {
            return new \WP_Error('grcop_not_found', __('Zapis ni najden.', 'gr-odstop-od-pogodbe'), ['status' => 404]);
        }

        $row['items'] = json_decode($row['items_json'], true);
        unset($row['items_json']);

        return rest_ensure_response($row);
    }

    /**
     * POST/PUT endpoint: Update status of a contract withdrawal request.
     */
    public function update_api_withdrawal_status($request)
    {
        $id = intval($request['id']);
        $new_status = $request->get_param('status');
        $comment = $request->get_param('comment') ? sanitize_textarea_field(wp_unslash($request->get_param('comment'))) : '';

        $success = GrCop_Log::update_withdrawal_status($id, $new_status, $comment);
        if (!$success) {
            return new \WP_Error('grcop_update_failed', __('Posodobitev statusa ni uspela ali zapis ne obstaja.', 'gr-odstop-od-pogodbe'), ['status' => 400]);
        }

        return rest_ensure_response([
            'success' => true,
            /* translators: %s: status slug */
            'message' => sprintf(__('Status uspešno spremenjen v: %s', 'gr-odstop-od-pogodbe'), $new_status)
        ]);
    }

    /**
     * Get default store address from WooCommerce configuration.
     */
    public static function get_default_store_address()
    {
        $address = get_option('woocommerce_store_address', '');
        $address_2 = get_option('woocommerce_store_address_2', '');
        $city = get_option('woocommerce_store_city', '');
        $postcode = get_option('woocommerce_store_postcode', '');
        $store_name = get_bloginfo('name');
        return trim(sprintf("%s\n%s %s\n%s %s", $store_name, $address, $address_2, $postcode, $city));
    }

    /**
     * Register hidden setup wizard page in admin.
     */
    public function register_setup_wizard_page()
    {
        add_submenu_page(
            null,
            __('Čarovnik za namestitev - GR Odstop od pogodbe', 'gr-odstop-od-pogodbe'),
            __('Čarovnik za namestitev', 'gr-odstop-od-pogodbe'),
            'manage_woocommerce',
            'grcop-setup-wizard',
            [$this, 'render_setup_wizard_page']
        );
    }

    /**
     * AJAX handler to save wizard settings.
     */
    public function ajax_save_wizard_settings()
    {
        // Check security nonce
        if (!check_ajax_referer('grcop_wizard_nonce', 'security', false)) {
            wp_send_json_error(__('Varnostno preverjanje ni uspelo. Osvežite stran in poskusite znova.', 'gr-odstop-od-pogodbe'), 403);
        }

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(__('Nimate ustreznih pravic.', 'gr-odstop-od-pogodbe'), 403);
        }

        // Save Page & Footer setting
        $page_id = 0;
        if (isset($_POST['grcop_form_page'])) {
            $page_val = sanitize_text_field(wp_unslash($_POST['grcop_form_page']));
            if ($page_val === 'create_new') {
                // Create new page with shortcode
                $post_data = [
                    'post_title'   => __('Odstop od pogodbe', 'gr-odstop-od-pogodbe'),
                    'post_content' => '[gr_odstop_od_pogodbe_form]',
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_author'  => get_current_user_id(),
                    'post_comment_status' => 'closed',
                    'post_ping_status'    => 'closed',
                ];
                
                if (!function_exists('wp_insert_post')) {
                    require_once ABSPATH . 'wp-admin/includes/post.php';
                }
                
                $new_page_id = wp_insert_post($post_data);
                if ($new_page_id && !is_wp_error($new_page_id)) {
                    update_option('grcop_form_page', $new_page_id);
                    $page_id = $new_page_id;
                }
            } else {
                $page_id = intval($page_val);
                update_option('grcop_form_page', $page_id);
            }
        }
        update_option('grcop_enable_footer_link', isset($_POST['grcop_enable_footer_link']) && $_POST['grcop_enable_footer_link'] === 'yes' ? 'yes' : 'no');

        // Save Rules & Eligibility setting
        if (isset($_POST['grcop_withdrawal_window'])) {
            update_option('grcop_withdrawal_window', intval($_POST['grcop_withdrawal_window']));
        }
        if (isset($_POST['grcop_eligible_statuses']) && is_array($_POST['grcop_eligible_statuses'])) {
            $statuses = array_map('sanitize_text_field', wp_unslash($_POST['grcop_eligible_statuses']));
            update_option('grcop_eligible_statuses', $statuses);
        } else {
            update_option('grcop_eligible_statuses', []);
        }
        if (isset($_POST['grcop_excluded_categories']) && is_array($_POST['grcop_excluded_categories'])) {
            $cats = array_map('sanitize_text_field', wp_unslash($_POST['grcop_excluded_categories']));
            update_option('grcop_excluded_categories', $cats);
        } else {
            update_option('grcop_excluded_categories', []);
        }
        if (isset($_POST['grcop_excluded_products'])) {
            update_option('grcop_excluded_products', sanitize_text_field(wp_unslash($_POST['grcop_excluded_products'])));
        }

        // Save Design & Color Settings
        if (isset($_POST['grcop_button_text'])) {
            update_option('grcop_button_text', sanitize_text_field(wp_unslash($_POST['grcop_button_text'])));
        }
        if (isset($_POST['grcop_btn_bg_color'])) {
            $bg_color = sanitize_text_field(wp_unslash($_POST['grcop_btn_bg_color']));
            update_option('grcop_btn_bg_color', $bg_color);
            update_option('grcop_email_btn_bg_color', $bg_color);
        }
        if (isset($_POST['grcop_btn_text_color'])) {
            $text_color = sanitize_text_field(wp_unslash($_POST['grcop_btn_text_color']));
            update_option('grcop_btn_text_color', $text_color);
            update_option('grcop_email_btn_text_color', $text_color);
        }
        if (isset($_POST['grcop_btn_border_radius'])) {
            update_option('grcop_btn_border_radius', intval($_POST['grcop_btn_border_radius']));
        }
        if (isset($_POST['grcop_form_bg_color'])) {
            update_option('grcop_form_bg_color', sanitize_text_field(wp_unslash($_POST['grcop_form_bg_color'])));
        }
        if (isset($_POST['grcop_form_border_radius'])) {
            update_option('grcop_form_border_radius', intval($_POST['grcop_form_border_radius']));
        }

        // Save Refund Methods & Return Address
        if (isset($_POST['grcop_refund_methods']) && is_array($_POST['grcop_refund_methods'])) {
            $refund_methods = array_map('sanitize_text_field', wp_unslash($_POST['grcop_refund_methods']));
            update_option('grcop_refund_methods', $refund_methods);
        } else {
            update_option('grcop_refund_methods', []);
        }
        if (isset($_POST['grcop_return_address'])) {
            update_option('grcop_return_address', sanitize_textarea_field(wp_unslash($_POST['grcop_return_address'])));
        }

        // Save Notification & Logging
        if (isset($_POST['grcop_email_admin_recipient'])) {
            $email = sanitize_email(wp_unslash($_POST['grcop_email_admin_recipient']));
            update_option('grcop_email_admin_recipient', $email);
        }
        update_option('grcop_enable_debug_logging', isset($_POST['grcop_enable_debug_logging']) && $_POST['grcop_enable_debug_logging'] === 'yes' ? 'yes' : 'no');

        // Set completed flag
        update_option('grcop_setup_wizard_completed', 'yes');

        $permalink = '';
        if ($page_id > 0) {
            $permalink = get_permalink($page_id);
        }
        wp_send_json_success([
            'message'   => __('Nastavitve uspešno shranjene.', 'gr-odstop-od-pogodbe'),
            'permalink' => esc_url($permalink)
        ]);
    }

    /**
     * Render the setup wizard page.
     */
    public function render_setup_wizard_page()
    {
        if (!current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('Nimate dovoljenja za dostop do te strani.', 'gr-odstop-od-pogodbe'));
        }

        // Query pages for step 1
        $pages = get_pages(['post_type' => 'page', 'post_status' => 'publish']);
        $selected_page = get_option('grcop_form_page', '');

        // Query categories for step 2
        $categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]);
        $selected_cats = get_option('grcop_excluded_categories', []);

        // Order statuses
        $status_options = [];
        if (function_exists('wc_get_order_statuses')) {
            $order_statuses = wc_get_order_statuses();
            foreach ($order_statuses as $key => $label) {
                $status_options[str_replace('wc-', '', $key)] = $label;
            }
        }
        $selected_statuses = get_option('grcop_eligible_statuses', ['completed', 'processing', 'on-hold']);

        // Default settings values
        $btn_text = get_option('grcop_button_text', __('Odstopi od pogodbe tukaj', 'gr-odstop-od-pogodbe'));
        $btn_bg = get_option('grcop_btn_bg_color', '#2563eb');
        $btn_text_color = get_option('grcop_btn_text_color', '#ffffff');
        $btn_radius = get_option('grcop_btn_border_radius', '6');
        $form_bg = get_option('grcop_form_bg_color', '#ffffff');
        $form_radius = get_option('grcop_form_border_radius', '12');

        $refund_methods = get_option('grcop_refund_methods', ['original', 'iban']);
        
        $default_address = self::get_default_store_address();
        $return_address = get_option('grcop_return_address', $default_address);

        $admin_recipient = get_option('grcop_email_admin_recipient', '');
        $debug_logging = get_option('grcop_enable_debug_logging', 'no');
        ?>
        <style>
            #grcop-wizard-container {
                max-width: 850px;
                margin: 20px 0;
                background: #ffffff;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                overflow: hidden;
                color: #1f2937;
                position: relative;
            }
            .grcop-wizard-header {
                background: linear-gradient(135deg, #4f46e5 0%, #1e1b4b 100%);
                padding: 35px 40px;
                color: #ffffff;
                position: relative;
            }
            .grcop-wizard-header-wrapper {
                display: flex;
                align-items: center;
                gap: 20px;
            }
            .grcop-wizard-header-logo img {
                width: 60px;
                height: 60px;
                border-radius: 12px;
                display: block;
                background: #ffffff;
                padding: 4px;
                box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
            }
            .grcop-wizard-header h1 {
                margin: 0 0 8px 0;
                color: #ffffff;
                font-size: 26px;
                font-weight: 700;
                line-height: 1.2;
            }
            .grcop-wizard-header p {
                margin: 0;
                color: #c7d2fe;
                font-size: 15px;
            }
            .grcop-wizard-steps {
                display: flex;
                justify-content: space-between;
                background: #f9fafb;
                border-bottom: 1px solid #f3f4f6;
                padding: 15px 40px;
                overflow-x: auto;
            }
            .grcop-wizard-step-indicator {
                display: flex;
                align-items: center;
                font-size: 13px;
                font-weight: 600;
                color: #9ca3af;
                white-space: nowrap;
                margin-right: 15px;
            }
            .grcop-wizard-step-indicator:last-child {
                margin-right: 0;
            }
            .grcop-wizard-step-indicator .indicator-number {
                width: 24px;
                height: 24px;
                border-radius: 50%;
                background: #e5e7eb;
                color: #4b5563;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 8px;
                font-size: 11px;
                font-weight: 700;
            }
            .grcop-wizard-step-indicator.active {
                color: #4f46e5;
            }
            .grcop-wizard-step-indicator.active .indicator-number {
                background: #4f46e5;
                color: #ffffff;
            }
            .grcop-wizard-step-indicator.completed {
                color: #10b981;
            }
            .grcop-wizard-step-indicator.completed .indicator-number {
                background: #10b981;
                color: #ffffff;
            }
            .grcop-wizard-body {
                padding: 40px;
                min-height: 380px;
            }
            .grcop-wizard-step-content {
                display: none;
                animation: grcopFadeIn 0.3s ease-in-out forwards;
            }
            .grcop-wizard-step-content.active {
                display: block;
            }
            @keyframes grcopFadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .grcop-wizard-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-top: 1px solid #f3f4f6;
                padding: 20px 40px;
                background: #f9fafb;
            }
            .grcop-wizard-navigation {
                margin-left: auto;
                display: flex;
                gap: 10px;
            }
            .grcop-btn {
                padding: 11px 22px;
                border-radius: 6px;
                font-weight: 600;
                font-size: 14px;
                cursor: pointer;
                border: none;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s;
                text-decoration: none;
            }
            .grcop-btn-primary {
                background-color: #4f46e5;
                color: #ffffff;
            }
            .grcop-btn-primary:hover {
                background-color: #4338ca;
            }
            .grcop-btn-secondary {
                background-color: #e5e7eb;
                color: #4b5563;
            }
            .grcop-btn-secondary:hover {
                background-color: #d1d5db;
            }
            .grcop-btn:disabled {
                opacity: 0.5;
                cursor: not-allowed;
            }
            .grcop-form-group {
                margin-bottom: 25px;
            }
            .grcop-form-group:last-child {
                margin-bottom: 0;
            }
            .grcop-label {
                display: block;
                font-weight: 600;
                margin-bottom: 8px;
                font-size: 14px;
                color: #374151;
            }
            .grcop-input-text, .grcop-select, .grcop-textarea {
                width: 100%;
                padding: 11px 14px;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                background: #ffffff;
                color: #1f2937;
                font-size: 14px;
                box-sizing: border-box;
                transition: border-color 0.2s, box-shadow 0.2s;
            }
            .grcop-input-text:focus, .grcop-select:focus, .grcop-textarea:focus {
                border-color: #4f46e5;
                box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
                outline: none;
            }
            .grcop-help-text {
                display: block;
                margin-top: 6px;
                font-size: 13px;
                color: #6b7280;
                line-height: 1.4;
            }
            .grcop-checkbox-group {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                gap: 12px;
                margin-top: 8px;
            }
            .grcop-checkbox-label {
                display: flex;
                align-items: center;
                font-size: 14px;
                color: #4b5563;
                cursor: pointer;
            }
            .grcop-checkbox-label input[type="checkbox"] {
                margin-right: 8px;
                border-radius: 4px;
                border: 1px solid #d1d5db;
                width: 16px;
                height: 16px;
                cursor: pointer;
            }
            .grcop-design-layout {
                display: grid;
                grid-template-columns: 1.2fr 0.8fr;
                gap: 30px;
            }
            .grcop-preview-card {
                background: #f9fafb;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 25px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                text-align: center;
                align-self: start;
            }
            .grcop-preview-label {
                font-size: 12px;
                text-transform: uppercase;
                letter-spacing: 0.05em;
                color: #6b7280;
                margin-bottom: 20px;
                font-weight: 700;
            }
            .grcop-preview-button-container {
                margin: 20px 0;
                min-height: 60px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .grcop-preview-hint {
                font-size: 12px;
                color: #9ca3af;
                margin-top: 15px;
            }
            .grcop-color-picker-wrapper {
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .grcop-color-picker-input {
                width: 50px;
                height: 38px;
                padding: 0;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                cursor: pointer;
            }
            .grcop-finish-screen {
                text-align: center;
                padding: 20px 0;
            }
            .grcop-finish-icon {
                width: 64px;
                height: 64px;
                background: #d1fae5;
                color: #10b981;
                border-radius: 50%;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 20px;
            }
            .grcop-finish-icon svg {
                width: 32px;
                height: 32px;
                fill: none;
                stroke: currentColor;
                stroke-width: 3;
                stroke-linecap: round;
                stroke-linejoin: round;
            }
            .grcop-finish-title {
                font-size: 24px;
                font-weight: 700;
                color: #111827;
                margin-bottom: 12px;
            }
            .grcop-finish-desc {
                color: #4b5563;
                font-size: 16px;
                max-width: 550px;
                margin: 0 auto 30px auto;
                line-height: 1.5;
            }
            .grcop-finish-actions {
                display: flex;
                justify-content: center;
                gap: 15px;
                margin-top: 20px;
            }
            .grcop-cancel-link {
                color: #9ca3af;
                text-decoration: none;
                font-size: 13px;
                transition: color 0.2s;
            }
            .grcop-cancel-link:hover {
                color: #4b5563;
            }
            .grcop-spinner-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.7);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 100;
                opacity: 0;
                pointer-events: none;
                transition: opacity 0.2s;
            }
            .grcop-spinner-overlay.active {
                opacity: 1;
                pointer-events: auto;
            }
            .grcop-spinner {
                border: 3px solid #f3f4f6;
                border-top: 3px solid #4f46e5;
                border-radius: 50%;
                width: 35px;
                height: 35px;
                animation: spin 1s linear infinite;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>

        <div id="grcop-wizard-container">
            <div class="grcop-spinner-overlay" id="grcop-spinner-overlay">
                <div class="grcop-spinner"></div>
            </div>

            <div class="grcop-wizard-header">
                <div class="grcop-wizard-header-wrapper">
                    <div class="grcop-wizard-header-logo">
                        <img src="<?php echo esc_url(plugins_url('assets/icon-256x256.png', GRCOP_PLUGIN_FILE)); ?>" alt="Logo">
                    </div>
                    <div>
                        <h1><?php esc_html_e('Čarovnik za namestitev - GR Odstop od pogodbe', 'gr-odstop-od-pogodbe'); ?></h1>
                        <p><?php esc_html_e('V nekaj preprostih korakih prilagodite obrazec in nastavitve skladno z ZVPot-1.', 'gr-odstop-od-pogodbe'); ?></p>
                    </div>
                </div>
            </div>

            <div class="grcop-wizard-steps">
                <div class="grcop-wizard-step-indicator active" data-step="1">
                    <span class="indicator-number">1</span><?php esc_html_e('Strani', 'gr-odstop-od-pogodbe'); ?>
                </div>
                <div class="grcop-wizard-step-indicator" data-step="2">
                    <span class="indicator-number">2</span><?php esc_html_e('Pravila', 'gr-odstop-od-pogodbe'); ?>
                </div>
                <div class="grcop-wizard-step-indicator" data-step="3">
                    <span class="indicator-number">3</span><?php esc_html_e('Izgled', 'gr-odstop-od-pogodbe'); ?>
                </div>
                <div class="grcop-wizard-step-indicator" data-step="4">
                    <span class="indicator-number">4</span><?php esc_html_e('Vračila & Naslov', 'gr-odstop-od-pogodbe'); ?>
                </div>
                <div class="grcop-wizard-step-indicator" data-step="5">
                    <span class="indicator-number">5</span><?php esc_html_e('Obvestila', 'gr-odstop-od-pogodbe'); ?>
                </div>
                <div class="grcop-wizard-step-indicator" data-step="6">
                    <span class="indicator-number">6</span><?php esc_html_e('Zaključek', 'gr-odstop-od-pogodbe'); ?>
                </div>
            </div>

            <form id="grcop-wizard-form" method="post">
                <?php wp_nonce_field('grcop_wizard_nonce', 'grcop_wizard_security'); ?>
                <div class="grcop-wizard-body">
                    <!-- Step 1: Page setup -->
                    <div class="grcop-wizard-step-content active" data-step="1">
                        <div class="grcop-form-group">
                            <label class="grcop-label" for="grcop_form_page"><?php esc_html_e('Stran z obrazcem za odstop', 'gr-odstop-od-pogodbe'); ?></label>
                            <select id="grcop_form_page" name="grcop_form_page" class="grcop-select">
                                <option value="create_new" <?php selected($selected_page, ''); ?>><?php esc_html_e('+ Ustvari novo stran za odstop (avtomatsko)', 'gr-odstop-od-pogodbe'); ?></option>
                                <?php foreach ($pages as $p) : ?>
                                    <option value="<?php echo esc_attr($p->ID); ?>" <?php selected($selected_page, $p->ID); ?>>
                                        <?php echo esc_html($p->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <span class="grcop-help-text">
                                <?php esc_html_e('Izberite stran, na kateri je vstavljena kratka koda [gr_odstop_od_pogodbe_form]. Ob aktivaciji smo jo samodejno ustvarili za vas.', 'gr-odstop-od-pogodbe'); ?>
                            </span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-checkbox-label">
                                <input type="checkbox" name="grcop_enable_footer_link" value="yes" <?php checked(get_option('grcop_enable_footer_link', 'yes'), 'yes'); ?>>
                                <?php esc_html_e('Samodejno dodaj povezavo do obrazca v nogo (Footer) spletne strani', 'gr-odstop-od-pogodbe'); ?>
                            </label>
                            <span class="grcop-help-text">
                                <?php esc_html_e('Zakon zahteva, da je obrazec kupcem vedno enostavno dostopen. Priporočamo, da povezavo pustite vključeno.', 'gr-odstop-od-pogodbe'); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Step 2: Rules & Eligibility -->
                    <div class="grcop-wizard-step-content" data-step="2">
                        <div class="grcop-form-group">
                            <label class="grcop-label" for="grcop_withdrawal_window"><?php esc_html_e('Obdobje za odstop (v dneh)', 'gr-odstop-od-pogodbe'); ?></label>
                            <input type="number" id="grcop_withdrawal_window" name="grcop_withdrawal_window" class="grcop-input-text" min="1" step="1" value="<?php echo esc_attr(get_option('grcop_withdrawal_window', '14')); ?>">
                            <span class="grcop-help-text"><?php esc_html_e('Število dni po zaključku naročila, ko stranka še lahko odstopi od pogodbe. Po zakonu je rok najmanj 14 dni.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-label"><?php esc_html_e('Statusi naročil za odstop', 'gr-odstop-od-pogodbe'); ?></label>
                            <div class="grcop-checkbox-group">
                                <?php foreach ($status_options as $slug => $label) : ?>
                                    <label class="grcop-checkbox-label">
                                        <input type="checkbox" name="grcop_eligible_statuses[]" value="<?php echo esc_attr($slug); ?>" <?php checked(in_array($slug, $selected_statuses)); ?>>
                                        <?php echo esc_html($label); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <span class="grcop-help-text"><?php esc_html_e('Izberite, v katerih statusih naročila je odstop od pogodbe mogoč.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-label"><?php esc_html_e('Izključene kategorije', 'gr-odstop-od-pogodbe'); ?></label>
                            <div class="grcop-checkbox-group">
                                <?php if (!is_wp_error($categories) && !empty($categories)) : ?>
                                    <?php foreach ($categories as $category) : ?>
                                        <label class="grcop-checkbox-label">
                                            <input type="checkbox" name="grcop_excluded_categories[]" value="<?php echo esc_attr($category->slug); ?>" <?php checked(in_array($category->slug, $selected_cats)); ?>>
                                            <?php echo esc_html($category->name); ?>
                                        </label>
                                    <?php endforeach; ?>
                                <?php else : ?>
                                    <span class="grcop-help-text"><?php esc_html_e('Ni najdenih kategorij izdelkov.', 'gr-odstop-od-pogodbe'); ?></span>
                                <?php endif; ?>
                            </div>
                            <span class="grcop-help-text"><?php esc_html_e('Izdelki v izbranih kategorijah ne bodo imeli možnosti odstopa od pogodbe (npr. personalizirani izdelki ali odprta kozmetika).', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-label" for="grcop_excluded_products"><?php esc_html_e('Izključeni izdelki (ID-ji)', 'gr-odstop-od-pogodbe'); ?></label>
                            <input type="text" id="grcop_excluded_products" name="grcop_excluded_products" class="grcop-input-text" value="<?php echo esc_attr(get_option('grcop_excluded_products', '')); ?>" placeholder="npr. 123, 456">
                            <span class="grcop-help-text"><?php esc_html_e('Vnesite ID-je izdelkov, ločene z vejico, za katere želite preprečiti odstop.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>
                    </div>

                    <!-- Step 3: Design & Customization (with live preview) -->
                    <div class="grcop-wizard-step-content" data-step="3">
                        <div class="grcop-design-layout">
                            <div class="grcop-design-fields">
                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_button_text"><?php esc_html_e('Besedilo gumba', 'gr-odstop-od-pogodbe'); ?></label>
                                    <input type="text" id="grcop_button_text" name="grcop_button_text" class="grcop-input-text" value="<?php echo esc_attr($btn_text); ?>">
                                    <span class="grcop-help-text"><?php esc_html_e('Napišite jasno besedilo (zakonsko mora biti nedvoumno).', 'gr-odstop-od-pogodbe'); ?></span>
                                </div>

                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_btn_bg_color"><?php esc_html_e('Barva ozadja gumba', 'gr-odstop-od-pogodbe'); ?></label>
                                    <div class="grcop-color-picker-wrapper">
                                        <input type="color" id="grcop_btn_bg_color" name="grcop_btn_bg_color" class="grcop-color-picker-input" value="<?php echo esc_attr($btn_bg); ?>">
                                        <input type="text" id="grcop_btn_bg_color_hex" class="grcop-input-text" style="width: 100px;" value="<?php echo esc_attr($btn_bg); ?>">
                                    </div>
                                </div>

                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_btn_text_color"><?php esc_html_e('Barva besedila gumba', 'gr-odstop-od-pogodbe'); ?></label>
                                    <div class="grcop-color-picker-wrapper">
                                        <input type="color" id="grcop_btn_text_color" name="grcop_btn_text_color" class="grcop-color-picker-input" value="<?php echo esc_attr($btn_text_color); ?>">
                                        <input type="text" id="grcop_btn_text_color_hex" class="grcop-input-text" style="width: 100px;" value="<?php echo esc_attr($btn_text_color); ?>">
                                    </div>
                                </div>

                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_btn_border_radius"><?php esc_html_e('Zaobljenost robov gumba (px)', 'gr-odstop-od-pogodbe'); ?></label>
                                    <input type="number" id="grcop_btn_border_radius" name="grcop_btn_border_radius" class="grcop-input-text" min="0" step="1" value="<?php echo esc_attr($btn_radius); ?>">
                                </div>

                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_form_bg_color"><?php esc_html_e('Barva ozadja obrazca', 'gr-odstop-od-pogodbe'); ?></label>
                                    <div class="grcop-color-picker-wrapper">
                                        <input type="color" id="grcop_form_bg_color" name="grcop_form_bg_color" class="grcop-color-picker-input" value="<?php echo esc_attr($form_bg); ?>">
                                        <input type="text" id="grcop_form_bg_color_hex" class="grcop-input-text" style="width: 100px;" value="<?php echo esc_attr($form_bg); ?>">
                                    </div>
                                </div>

                                <div class="grcop-form-group">
                                    <label class="grcop-label" for="grcop_form_border_radius"><?php esc_html_e('Zaobljenost robov obrazca (px)', 'gr-odstop-od-pogodbe'); ?></label>
                                    <input type="number" id="grcop_form_border_radius" name="grcop_form_border_radius" class="grcop-input-text" min="0" step="1" value="<?php echo esc_attr($form_radius); ?>">
                                </div>
                            </div>

                            <div class="grcop-preview-card" id="grcop-preview-form-card" style="background-color: <?php echo esc_attr($form_bg); ?>; border-radius: <?php echo esc_attr($form_radius); ?>px; padding: 25px; border: 1px solid #e5e7eb; box-shadow: 0 4px 12px rgba(0,0,0,0.05); text-align: left; width: 100%; box-sizing: border-box; align-self: start;">
                                <span class="grcop-preview-label" style="display: block; font-size: 11px; text-transform: uppercase; color: #6b7280; font-weight: bold; margin-bottom: 15px; border-bottom: 1px solid #f3f4f6; padding-bottom: 5px;"><?php esc_html_e('Predogled obrazca', 'gr-odstop-od-pogodbe'); ?></span>
                                <h3 style="margin: 0 0 15px 0; font-size: 16px; font-weight: bold; color: #111827;"><?php esc_html_e('Odstop od pogodbe', 'gr-odstop-od-pogodbe'); ?></h3>
                                <div style="margin-bottom: 15px;">
                                    <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 5px; color: #374151;"><?php esc_html_e('Številka naročila', 'gr-odstop-od-pogodbe'); ?></label>
                                    <input type="text" disabled value="#10234" style="width: 100%; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 4px; font-size: 13px; background: #fff; cursor: default; box-sizing: border-box;">
                                </div>
                                <div style="text-align: center; margin-top: 20px;">
                                    <button type="button" id="grcop-preview-btn-element" style="background-color: <?php echo esc_attr($btn_bg); ?>; color: <?php echo esc_attr($btn_text_color); ?>; border-radius: <?php echo esc_attr($btn_radius); ?>px; border: none; padding: 11px 22px; font-weight: 600; cursor: default; font-size: 13px; width: 100%; box-sizing: border-box; transition: all 0.2s;">
                                        <?php echo esc_html($btn_text); ?>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Step 4: Refund Options & Return Address -->
                    <div class="grcop-wizard-step-content" data-step="4">
                        <div class="grcop-form-group">
                            <label class="grcop-label"><?php esc_html_e('Dovoljene metode vračila kupnine', 'gr-odstop-od-pogodbe'); ?></label>
                            <div class="grcop-checkbox-group">
                                <label class="grcop-checkbox-label">
                                    <input type="checkbox" name="grcop_refund_methods[]" value="original" <?php checked(in_array('original', $refund_methods)); ?>>
                                    <?php esc_html_e('Originalna metoda plačila', 'gr-odstop-od-pogodbe'); ?>
                                </label>
                                <label class="grcop-checkbox-label">
                                    <input type="checkbox" name="grcop_refund_methods[]" value="iban" <?php checked(in_array('iban', $refund_methods)); ?>>
                                    <?php esc_html_e('Vračilo na TRR (vnos IBAN)', 'gr-odstop-od-pogodbe'); ?>
                                </label>
                                <label class="grcop-checkbox-label">
                                    <input type="checkbox" name="grcop_refund_methods[]" value="coupon" <?php checked(in_array('coupon', $refund_methods)); ?>>
                                    <?php esc_html_e('Kupon / Dobropis trgovine', 'gr-odstop-od-pogodbe'); ?>
                                </label>
                            </div>
                            <span class="grcop-help-text"><?php esc_html_e('Stranka bo lahko izbrala eno izmed teh treh možnosti na obrazcu.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-label" for="grcop_return_address"><?php esc_html_e('Naslov za vračilo blaga in navodila', 'gr-odstop-od-pogodbe'); ?></label>
                            <textarea id="grcop_return_address" name="grcop_return_address" class="grcop-textarea" rows="4"><?php echo esc_textarea($return_address); ?></textarea>
                            <span class="grcop-help-text"><?php esc_html_e('Ta naslov se izpiše na potrditvenem zaslonu, na e-poštnem potrdilu in na nalepki za paket.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>
                    </div>

                    <!-- Step 5: Notifications & Traceability -->
                    <div class="grcop-wizard-step-content" data-step="5">
                        <div class="grcop-form-group">
                            <label class="grcop-label" for="grcop_email_admin_recipient"><?php esc_html_e('Prejemnik obvestil trgovca', 'gr-odstop-od-pogodbe'); ?></label>
                            <input type="email" id="grcop_email_admin_recipient" name="grcop_email_admin_recipient" class="grcop-input-text" value="<?php echo esc_attr($admin_recipient); ?>" placeholder="<?php echo esc_attr(get_option('admin_email')); ?>">
                            <span class="grcop-help-text"><?php esc_html_e('E-poštni naslov, kamor boste prejemali obvestila o novih odstopih. Če pustite prazno, bo uporabljena e-pošta skrbnika spletnega mesta.', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>

                        <div class="grcop-form-group">
                            <label class="grcop-checkbox-label">
                                <input type="checkbox" name="grcop_enable_debug_logging" value="yes" <?php checked($debug_logging, 'yes'); ?>>
                                <?php esc_html_e('Vklopi debug logiranje', 'gr-odstop-od-pogodbe'); ?>
                            </label>
                            <span class="grcop-help-text"><?php esc_html_e('Beleži diagnostične informacije v WooCommerce dnevnik (uporabno v primeru težav).', 'gr-odstop-od-pogodbe'); ?></span>
                        </div>
                    </div>

                    <!-- Step 6: Finish -->
                    <div class="grcop-wizard-step-content" data-step="6">
                        <div class="grcop-finish-screen">
                            <div class="grcop-finish-icon">
                                <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"></polyline></svg>
                            </div>
                            <h2 class="grcop-finish-title"><?php esc_html_e('Čestitamo! Nastavitev je končana.', 'gr-odstop-od-pogodbe'); ?></h2>
                            <p class="grcop-finish-desc"><?php esc_html_e('Vtičnik GR Odstop od pogodbe je uspešno nastavljen in pripravljen za uporabo. Vse oddane zahteve se bodo beležile v vašem sistemu.', 'gr-odstop-od-pogodbe'); ?></p>

                            <div class="grcop-finish-actions">
                                <a href="<?php echo esc_url(get_permalink($selected_page)); ?>" class="grcop-btn grcop-btn-primary" id="grcop-finish-view-page-btn" target="_blank">
                                    <?php esc_html_e('Prikaži spletno stran z obrazcem', 'gr-odstop-od-pogodbe'); ?>
                                </a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=grcop-withdrawals-log')); ?>" class="grcop-btn grcop-btn-secondary">
                                    <?php esc_html_e('Nadzorna plošča odstopov', 'gr-odstop-od-pogodbe'); ?>
                                </a>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=grcop_settings')); ?>" class="grcop-btn grcop-btn-secondary">
                                    <?php esc_html_e('Uredi napredne nastavitve', 'gr-odstop-od-pogodbe'); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="grcop-wizard-footer">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=grcop_settings')); ?>" class="grcop-cancel-link" id="grcop-cancel-wizard">
                        <?php esc_html_e('Prekliči in pojdi v nadzorno ploščo', 'gr-odstop-od-pogodbe'); ?>
                    </a>
                    
                    <div class="grcop-wizard-navigation">
                        <button type="button" class="grcop-btn grcop-btn-secondary" id="grcop-prev-btn" style="display:none;">
                            &larr; <?php esc_html_e('Nazaj', 'gr-odstop-od-pogodbe'); ?>
                        </button>
                        <button type="button" class="grcop-btn grcop-btn-primary" id="grcop-next-btn">
                            <?php esc_html_e('Naprej', 'gr-odstop-od-pogodbe'); ?> &rarr;
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <script>
            (function() {
                let currentStep = 1;
                const totalSteps = 6;

                const nextBtn = document.getElementById('grcop-next-btn');
                const prevBtn = document.getElementById('grcop-prev-btn');
                const cancelBtn = document.getElementById('grcop-cancel-wizard');
                const form = document.getElementById('grcop-wizard-form');

                // Color picker elements
                const bgPicker = document.getElementById('grcop_btn_bg_color');
                const bgHex = document.getElementById('grcop_btn_bg_color_hex');
                const textPicker = document.getElementById('grcop_btn_text_color');
                const textHex = document.getElementById('grcop_btn_text_color_hex');
                const borderRad = document.getElementById('grcop_btn_border_radius');
                const btnLabel = document.getElementById('grcop_button_text');
                const previewBtn = document.getElementById('grcop-preview-btn-element');

                const formBgPicker = document.getElementById('grcop_form_bg_color');
                const formBgHex = document.getElementById('grcop_form_bg_color_hex');
                const formBorderRad = document.getElementById('grcop_form_border_radius');
                const previewFormCard = document.getElementById('grcop-preview-form-card');

                // Dynamic update of preview button
                function updatePreview() {
                    if (previewBtn) {
                        previewBtn.style.backgroundColor = bgPicker.value;
                        previewBtn.style.color = textPicker.value;
                        previewBtn.style.borderRadius = (borderRad.value || 0) + 'px';
                        previewBtn.innerText = btnLabel.value || '';
                    }
                    if (previewFormCard) {
                        previewFormCard.style.backgroundColor = formBgPicker.value;
                        previewFormCard.style.borderRadius = (formBorderRad.value || 0) + 'px';
                    }
                }

                // Setup sync between color input and text hex
                function syncColors(picker, hexInput) {
                    if (!picker || !hexInput) return;
                    picker.addEventListener('input', function() {
                        hexInput.value = picker.value;
                        updatePreview();
                    });
                    hexInput.addEventListener('input', function() {
                        let val = hexInput.value;
                        if (val.match(/^#[0-9a-fA-F]{6}$/)) {
                            picker.value = val;
                            updatePreview();
                        }
                    });
                }

                syncColors(bgPicker, bgHex);
                syncColors(textPicker, textHex);
                syncColors(formBgPicker, formBgHex);
                if (borderRad) borderRad.addEventListener('input', updatePreview);
                if (btnLabel) btnLabel.addEventListener('input', updatePreview);
                if (formBorderRad) formBorderRad.addEventListener('input', updatePreview);

                function goToStep(step) {
                    if (step < 1 || step > totalSteps) return;

                    // Toggle step content visibility
                    document.querySelectorAll('.grcop-wizard-step-content').forEach(el => {
                        el.classList.remove('active');
                    });
                    const targetContent = document.querySelector('.grcop-wizard-step-content[data-step="' + step + '"]');
                    if (targetContent) targetContent.classList.add('active');

                    // Toggle step indicators classes
                    document.querySelectorAll('.grcop-wizard-step-indicator').forEach(el => {
                        const s = parseInt(el.getAttribute('data-step'), 10);
                        el.classList.remove('active', 'completed');
                        if (s === step) {
                            el.classList.add('active');
                        } else if (s < step) {
                            el.classList.add('completed');
                        }
                    });

                    currentStep = step;

                    // Handle button texts & visibility
                    if (currentStep === 1) {
                        prevBtn.style.display = 'none';
                        cancelBtn.style.display = 'inline-block';
                        cancelBtn.href = '<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=grcop_settings')); ?>';
                        cancelBtn.className = 'grcop-cancel-link';
                        cancelBtn.innerHTML = '<?php esc_html_e('Prekliči in pojdi v nadzorno ploščo', 'gr-odstop-od-pogodbe'); ?>';
                    } else {
                        prevBtn.style.display = 'inline-block';
                        cancelBtn.style.display = 'none';
                    }

                    if (currentStep === totalSteps - 1) {
                        nextBtn.innerHTML = '<?php esc_html_e('Dokončaj in shrani', 'gr-odstop-od-pogodbe'); ?> &checkmark;';
                    } else if (currentStep === totalSteps) {
                        nextBtn.style.display = 'none';
                        prevBtn.style.display = 'none';
                        document.querySelector('.grcop-wizard-footer').style.justifyContent = 'center';
                        cancelBtn.style.display = 'inline-block';
                        cancelBtn.href = '<?php echo esc_url(admin_url()); ?>';
                        cancelBtn.innerHTML = '<?php esc_html_e('Pojdi v nadzorno ploščo', 'gr-odstop-od-pogodbe'); ?>';
                        cancelBtn.className = 'grcop-btn grcop-btn-primary';
                        
                        // Dynamically update view page link in final step in case they changed the select page
                        const pageSelect = document.getElementById('grcop_form_page');
                        const viewPageBtn = document.getElementById('grcop-finish-view-page-btn');
                        if (pageSelect && viewPageBtn) {
                            const selectedOption = pageSelect.options[pageSelect.selectedIndex];
                            if (selectedOption && pageSelect.value) {
                                // Request page permalink via AJAX or just use admin redirect logic if we can't easily fetch it
                                // But since we are saving it, let's just make sure it links correctly
                            }
                        }
                    } else {
                        nextBtn.style.display = 'inline-block';
                        nextBtn.innerHTML = '<?php esc_html_e('Naprej', 'gr-odstop-od-pogodbe'); ?> &rarr;';
                    }
                }

                prevBtn.addEventListener('click', function() {
                    goToStep(currentStep - 1);
                });

                nextBtn.addEventListener('click', function() {
                    if (currentStep === totalSteps - 1) {
                        // Submit Form using AJAX on the final configuration step
                        const formData = new FormData(form);
                        formData.append('action', 'grcop_save_wizard_settings');
                        formData.append('security', document.getElementById('grcop_wizard_security').value);

                        document.getElementById('grcop-spinner-overlay').classList.add('active');

                        fetch(ajaxurl, {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('grcop-spinner-overlay').classList.remove('active');
                            if (data.success) {
                                // Dynamically update the final view page link button if a permalink is returned
                                const viewPageBtn = document.getElementById('grcop-finish-view-page-btn');
                                if (viewPageBtn && data.data && data.data.permalink) {
                                    viewPageBtn.href = data.data.permalink;
                                }
                                goToStep(6);
                            } else {
                                alert(data.data || 'Prišlo je do napake pri shranjevanju.');
                            }
                        })
                        .catch(error => {
                            document.getElementById('grcop-spinner-overlay').classList.remove('active');
                            alert('Prišlo je do napake pri povezavi.');
                        });
                    } else {
                        goToStep(currentStep + 1);
                    }
                });

                // Init step 1
                goToStep(1);
            })();
        </script>
        <?php
    }
}
