<?php
/**
 * Dokan Booking Wizard Template - PHP Multi-Step Form
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

/**
 * Helper function to extract wizard data from product
 * Defined early because it is called during template initialization below.
 */
if ( ! function_exists( 'wahrb_extract_wizard_data_from_product' ) ) {
function wahrb_extract_wizard_data_from_product($product_id) {
    $product = wc_get_product($product_id);
    if (!$product) return [];
    
    $offer_type = get_post_meta($product_id, '_wahrb_booking_mode', true) ?: 'day';
    
    return [
        'step_1' => ['offer_type' => $offer_type],
        'step_2' => [
            'use_existing' => true,
            'product_id' => $product_id,
            'product_name' => $product->get_name(),
            'product_description' => $product->get_description(),
            'rental_description' => get_post_meta($product_id, '_wahrb_rental_description', true) ?: '',
            'total_units' => absint(get_post_meta($product_id, '_wahrb_total_units', true)) ?: 1,
        ],
        'step_3' => [
            'recurring_days' => get_post_meta($product_id, '_wahrb_recurring_days', true) ?: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'],
            'min_duration' => absint(get_post_meta($product_id, '_wahrb_min_duration', true)) ?: 1,
            'max_duration' => absint(get_post_meta($product_id, '_wahrb_max_duration', true)) ?: 30,
            'min_booking_window' => absint(get_post_meta($product_id, '_wahrb_min_booking_window', true)) ?: 24,
            'max_booking_window' => absint(get_post_meta($product_id, '_wahrb_max_booking_window', true)) ?: 365,
            'buffer_before' => absint(get_post_meta($product_id, '_wahrb_buffer_before', true)) ?: 0,
            'buffer_after' => absint(get_post_meta($product_id, '_wahrb_buffer_after', true)) ?: 0,
        ],
        'step_4' => [
            'base_price' => floatval(get_post_meta($product_id, '_wahrb_base_price', true)) ?: floatval($product->get_price()),
            'price_unit' => get_post_meta($product_id, '_wahrb_price_unit', true) ?: 'day',
            'rules' => [],
        ],
        'step_5' => [
            'deposit_enabled' => get_post_meta($product_id, '_wahrb_deposit_enabled', true) === 'yes',
            'deposit_type' => get_post_meta($product_id, '_wahrb_deposit_type', true) ?: 'percent',
            'deposit_value' => floatval(get_post_meta($product_id, '_wahrb_deposit_value', true)) ?: 30,
            'security_enabled' => get_post_meta($product_id, '_wahrb_security_deposit_enabled', true) === 'yes',
            'security_amount' => floatval(get_post_meta($product_id, '_wahrb_security_deposit', true)) ?: 0,
            'security_mode' => get_post_meta($product_id, '_wahrb_security_mode', true) ?: 'capture',
            'balance_enabled' => get_post_meta($product_id, '_wahrb_balance_enabled', true) !== 'no',
            'balance_due_days' => absint(get_post_meta($product_id, '_wahrb_balance_due_days', true)) ?: 3,
            'balance_allow_cod' => get_post_meta($product_id, '_wahrb_balance_allow_cod', true) === 'yes',
        ],
        // step_6 = publication (step_7 was renamed to step_6 after photos step removal)
        'step_6' => [
            'cancellation_policy' => get_post_meta($product_id, '_wahrb_cancellation_policy', true) ?: 'flexible',
            'cancellation_days' => absint(get_post_meta($product_id, '_wahrb_cancel_policy_days', true)) ?: 1,
            'cancellation_refund' => absint(get_post_meta($product_id, '_wahrb_cancel_policy_refund', true)) ?: 100,
            'terms_content' => get_post_meta($product_id, '_wahrb_terms_content', true) ?: '',
            'terms_file_url' => get_post_meta($product_id, '_wahrb_terms_file_url', true) ?: '',
            'terms_accepted' => false,
        ],
    ];
}
} // end function_exists wahrb_extract_wizard_data_from_product

// Get current user
$vendor_id = get_current_user_id();

// Check if vendor — Dokan mode uses dokan_is_seller_enabled(), solo mode checks manage_woocommerce/edit_products
$is_allowed_vendor = false;
if (function_exists('dokan_is_seller_enabled')) {
    $is_allowed_vendor = dokan_is_seller_enabled($vendor_id);
} else {
    // Solo mode: admin, shop_manager, or anyone who can edit products
    $is_allowed_vendor = current_user_can('manage_woocommerce') || current_user_can('edit_products');
}

if (!$is_allowed_vendor) {
    echo '<div class="wahrb-alert wahrb-alert-danger">'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe literal HTML
    echo '<span class="wahrb-alert-icon">⚠️</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe literal HTML
    esc_html_e('You must be an active seller to access this page.', 'wahra-rentals-bookings');
    echo '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe literal HTML
    return;
}

// Note: wizard-php.css, wahrb-wizard-php.js, and wahrb-wizard-steps.js are
// enqueued in enqueue_wizard_assets() (Dokan integration or Solo integration)
// so they are registered before wp_head() fires.

// Get URL parameters
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameters
$current_step = isset($_GET['step']) ? absint(wp_unslash($_GET['step'])) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$draft_id = isset($_GET['draft_id']) ? absint(wp_unslash($_GET['draft_id'])) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$product_id = isset($_GET['product_id']) ? absint(wp_unslash($_GET['product_id'])) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$is_new = isset($_GET['new']);

// Debug: trace step values from URL
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log('WAHRB Wizard load: step=' . $current_step . ' draft_id=' . $draft_id . ' product_id=' . $product_id . ' is_new=' . ($is_new ? '1' : '0') . ' URL=' . (isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : 'unknown'));

// Clamp step to valid range (0 = selection screen, 1-6 = wizard steps)
if ($current_step > 6) {
    $current_step = 6;
}

// Determine mode
$show_selection = !$draft_id && !$product_id && !$is_new && $current_step === 0;

// Initialize wizard data
$wizard_data = [];
$version_hash = '';

// Load existing draft if available
if ($draft_id) {
    global $wpdb;
    $db = WAHRB_Database::instance();
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $draft = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$db->table('wizard_drafts')} WHERE draft_id = %d AND vendor_id = %d",
        $draft_id, $vendor_id
    ), ARRAY_A);
    
    if ($draft) {
        $draft_data = json_decode($draft['wizard_data'], true) ?: [];
        $version_hash = $draft['version_hash'];
        $product_id = absint($draft['product_id']);
        
        // CRITICAL: If editing an existing product, first extract its data then overlay draft data
        if ($product_id) {
            $product = wc_get_product($product_id);
            if ($product && (int)get_post_field('post_author', $product_id) === $vendor_id) {
                // Start with existing product data (includes images, configurations)
                $wizard_data = wahrb_extract_wizard_data_from_product($product_id);
                
                // Overlay draft data on top (user's unsaved changes take priority)
                foreach ($draft_data as $key => $value) {
                    if (strpos($key, 'step_') === 0 && is_array($value)) {
                        // Merge step data, keeping draft changes
                        $wizard_data[$key] = array_merge($wizard_data[$key] ?? [], $value);
                    } else {
                        $wizard_data[$key] = $value;
                    }
                }
            } else {
                $wizard_data = $draft_data;
            }
            
            $wizard_data['product_id'] = $product_id;
            $wizard_data['is_existing_product'] = true;
            // Also enofe step_2 has product info
            if (!isset($wizard_data['step_2'])) {
                $wizard_data['step_2'] = [];
            }
            $wizard_data['step_2']['product_id'] = $product_id;
            if ($product) {
                $wizard_data['step_2']['product_name'] = $product->get_name();
            }
        } else {
            $wizard_data = $draft_data;
        }
        if ($current_step === 0) {
            // Use draft's saved current_step (clamped to 1-6), which records
            // the last step the user was on when they saved.
            $saved_step = min(6, max(1, absint($draft['current_step'])));

            // Safety: compute first incomplete step from wizard data to catch
            // corrupted values (e.g. draft saved at step 11 from old 7-step bug).
            // Note: when editing an existing product, wahrb_extract_wizard_data_from_product()
            // pre-fills all steps with defaults, so step_completion may show all complete.
            // In that case, trust the draft's saved step instead.
            $sc = [];
            $sc[1] = !empty($wizard_data['step_1']['offer_type']) || !empty($wizard_data['step_1']['platform_category']);
            $sc[2] = !empty($wizard_data['step_2']['product_name']) || !empty($wizard_data['product_id']);
            $sc[3] = !empty($wizard_data['step_3']['recurring_days']);
            $sc[4] = !empty($wizard_data['step_4']['base_price']) && floatval($wizard_data['step_4']['base_price']) > 0;
            $sc[5] = true; // Payment has defaults
            $first_incomplete = 6;
            for ($i = 1; $i <= 5; $i++) {
                if (empty($sc[$i])) {
                    $first_incomplete = $i;
                    break;
                }
            }

            // Use the lower of saved step vs first incomplete, so we never skip
            // past an incomplete step — but if all steps are "complete" (e.g. from
            // pre-filled product data), trust the draft's saved position.
            $current_step = min($saved_step, $first_incomplete);
        } else {
            // SAFETY GUARD: When a specific step is requested via URL (?step=N),
            // validate it against what the draft actually allows.
            // max_step tracks the highest step ever saved by the user.
            $max_step = absint($wizard_data['max_step'] ?? 0);

            // For existing rental products, all steps are accessible
            if ($product_id && get_post_meta($product_id, '_wahrb_rental_enabled', true) === 'yes') {
                $max_step = 6;
            }

            // Also trust the draft's current_step column as a floor
            $draft_step = absint($draft['current_step']);
            $max_step = max($max_step, $draft_step);

            if ($current_step > $max_step + 1) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log('WAHRB Wizard: Step ' . $current_step . ' exceeds max_step ' . $max_step . ' for draft ' . $draft_id . '. Clamping to ' . ($max_step + 1));
                $current_step = $max_step + 1;
                if ($current_step > 6) {
                    $current_step = 6;
                }
            }
        }
    }
} elseif ($product_id) {
    // Load from existing product
    $product = wc_get_product($product_id);
    if ($product && (int)get_post_field('post_author', $product_id) === $vendor_id) {
        $wizard_data = wahrb_extract_wizard_data_from_product($product_id);
        // Store product_id in wizard_data so steps know we're editing an existing product
        $wizard_data['product_id'] = $product_id;
        $wizard_data['is_existing_product'] = true;
        // Also store in step_2 for redundancy
        if (!isset($wizard_data['step_2'])) {
            $wizard_data['step_2'] = [];
        }
        $wizard_data['step_2']['product_id'] = $product_id;
        $wizard_data['step_2']['product_name'] = $product->get_name();

        // SAFETY: Without a draft, the user must start from step 1
        // (unless the product is already rental-enabled, then any step is OK)
        $has_rental = get_post_meta($product_id, '_wahrb_rental_enabled', true) === 'yes';
        if ($has_rental && $current_step > 0) {
            // Existing rental product — allow navigating to any step
            // (keep $current_step from URL)
        } else {
            $current_step = 1;
        }
    }
} elseif ($is_new) {
    $current_step = 1;
}

// Debug: trace final step value
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log('WAHRB Wizard final: step=' . $current_step . ' draft_id=' . $draft_id . ' product_id=' . $product_id . ' show_selection=' . ($show_selection ? '1' : '0') . ' max_step=' . ($wizard_data['max_step'] ?? 'n/a'));

// Get vendor products for selection
$vendor_products = [];
if ($show_selection) {
    $vendor_products = wc_get_products([
        'author' => $vendor_id,
        'limit' => 50,
        'status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC',
    ]);
    
    // Get drafts
    global $wpdb;
    $db = WAHRB_Database::instance();
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $drafts = $wpdb->get_results($wpdb->prepare(
        "SELECT draft_id, product_id, current_step, updated_at, wizard_data 
         FROM {$db->table('wizard_drafts')}
         WHERE vendor_id = %d AND is_complete = 0
         ORDER BY updated_at DESC",
        $vendor_id
    ), ARRAY_A);
}

// Step configuration
$steps = [
    1 => ['title' => __('Type', 'wahra-rentals-bookings'), 'file' => 'step-1-offer-type.php'],
    2 => ['title' => __('Product', 'wahra-rentals-bookings'), 'file' => 'step-2-product.php'],
    3 => ['title' => __('Availability', 'wahra-rentals-bookings'), 'file' => 'step-3-availability.php'],
    4 => ['title' => __('Pricing', 'wahra-rentals-bookings'), 'file' => 'step-4-pricing.php'],
    5 => ['title' => __('Payment', 'wahra-rentals-bookings'), 'file' => 'step-5-payment.php'],
    6 => ['title' => __('Publication', 'wahra-rentals-bookings'), 'file' => 'step-7-publish.php'],
];
?>

<div class="dokan-dashboard-wrap">
    <?php do_action('dokan_dashboard_content_before'); ?>

    <div class="dokan-dashboard-content dokan-product-listing">
        <article class="dokan-product-listing-area wahrb-wizard-page">

<div class="wahrb-wizard-container">
    <!-- Header -->
    <header class="wahrb-wizard-header">
        <div class="wahrb-wizard-header-left">
            <a href="<?php echo esc_url(wahrb_get_dashboard_url('bookings')); ?>" class="wahrb-back-link">
                <span class="wahrb-back-icon">←</span>
                <?php esc_html_e('Back', 'wahra-rentals-bookings'); ?>
            </a>
            <h1 class="wahrb-wizard-title"><?php esc_html_e('Rental Assistant', 'wahra-rentals-bookings'); ?></h1>
        </div>
        <?php if ($draft_id): ?>
            <div class="wahrb-wizard-draft-info">
                <span class="wahrb-draft-badge"><?php esc_html_e('Draft', 'wahra-rentals-bookings'); ?></span>
            </div>
        <?php endif; ?>
    </header>

    <?php if ($show_selection): ?>
    <!-- Selection Screen -->
    <div class="wahrb-selection-screen">
        <h2><?php esc_html_e('What would you like to do?', 'wahra-rentals-bookings'); ?></h2>
        
        <!-- Option 1: Configure Existing Product -->
        <?php if (!empty($vendor_products)): ?>
        <div class="wahrb-selection-card">
            <div class="wahrb-card-header">
                <span class="wahrb-card-icon">📦</span>
                <h3><?php esc_html_e('Configure an existing product', 'wahra-rentals-bookings'); ?></h3>
            </div>
            <p><?php esc_html_e('Select a product from your store to configure for rental', 'wahra-rentals-bookings'); ?></p>
            
            <select id="wahrb-product-select" class="wahrb-form-control">
                <option value=""><?php esc_html_e('-- Choose a product --', 'wahra-rentals-bookings'); ?></option>
                <?php foreach ($vendor_products as $product): ?>
                    <option value="<?php echo esc_attr($product->get_id()); ?>">
                        <?php echo esc_html($product->get_name()); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            
            <button type="button" class="wahrb-btn wahrb-btn-primary wahrb-btn-block" id="wahrb-configure-btn" disabled>
                <?php esc_html_e('Configure this product', 'wahra-rentals-bookings'); ?>
            </button>
        </div>
        <?php endif; ?>

        <div class="wahrb-separator"><span><?php esc_html_e('OR', 'wahra-rentals-bookings'); ?></span></div>

        <!-- Option 2: Create New Product -->
        <div class="wahrb-selection-card">
            <div class="wahrb-card-header">
                <span class="wahrb-card-icon">✨</span>
                <h3><?php esc_html_e('Create a new product', 'wahra-rentals-bookings'); ?></h3>
            </div>
            <p><?php esc_html_e('Create a product specifically for rental', 'wahra-rentals-bookings'); ?></p>
            
            <a href="<?php echo esc_url(add_query_arg('new', '1')); ?>" class="wahrb-btn wahrb-btn-secondary wahrb-btn-block">
                <?php esc_html_e('New rental item', 'wahra-rentals-bookings'); ?>
            </a>
        </div>

        <!-- Option 3: Resume Drafts -->
        <?php if (!empty($drafts)): ?>
        <div class="wahrb-separator"><span><?php esc_html_e('OR', 'wahra-rentals-bookings'); ?></span></div>
        
        <div class="wahrb-selection-card">
            <div class="wahrb-card-header">
                <span class="wahrb-card-icon">📝</span>
                <h3><?php esc_html_e('Resume a draft', 'wahra-rentals-bookings'); ?></h3>
            </div>
            <?php /* translators: %d: number of draft bookings */ ?>
            <p><?php printf(esc_html__('You have %d draft(s) in progress', 'wahra-rentals-bookings'), count($drafts)); ?></p>
            
            <div class="wahrb-draft-list">
                <?php foreach ($drafts as $draft): 
                    $data = json_decode($draft['wizard_data'], true);
                    $name = $data['step_2']['product_name'] ?? '';
                    // If no name in wizard data, try to get product name
                    if (empty($name) && !empty($draft['product_id'])) {
                        $product = wc_get_product($draft['product_id']);
                        if ($product) {
                            $name = $product->get_name();
                        }
                    }
                    if (empty($name)) {
                        $name = __('New item', 'wahra-rentals-bookings');
                    }
                ?>
                <div class="wahrb-draft-item" data-draft-id="<?php echo esc_attr($draft['draft_id']); ?>">
                    <div class="wahrb-draft-info">
                        <strong><?php echo esc_html($name); ?></strong>
                        <span><?php 
                        /* translators: %d: Current step number */
                        printf(esc_html__('Step %d/6', 'wahra-rentals-bookings'), absint($draft['current_step'])); 
                        ?></span>
                    </div>
                    <div class="wahrb-draft-actions" style="display: flex; gap: 8px;">
                        <a href="<?php echo esc_url(add_query_arg('draft_id', $draft['draft_id'])); ?>" class="wahrb-btn wahrb-btn-sm wahrb-btn-primary">
                            <?php esc_html_e('Resume', 'wahra-rentals-bookings'); ?>
                        </a>
                        <button type="button" class="wahrb-btn wahrb-btn-sm wahrb-delete-draft-btn" 
                                data-draft-id="<?php echo esc_attr($draft['draft_id']); ?>"
                                data-draft-name="<?php echo esc_attr($name); ?>"
                                style="background: #fee2e2; color: #dc2626; border: 1px solid #fecaca;">
                            🗑️
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php
    // Localize config for selection screen
    $general_settings_sel = get_option('wahrb_settings_general', []);
    wp_localize_script('wahrb-wizard-php-js', 'wahrbWizardPhpConfig', [
        'apiUrl'            => esc_url_raw(untrailingslashit(rest_url('wahrb/v1'))),
        'nonce'             => wp_create_nonce('wp_rest'),
        'wizardUrl'         => esc_url_raw(wahrb_get_dashboard_url('wizard')),
        'productsUrl'       => esc_url_raw(wahrb_is_dokan_active() && function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('products') : admin_url('edit.php?post_type=product')),
        'draftId'           => 0,
        'productId'         => 0,
        'currentStep'       => 0,
        'autosaveEnabled'   => (bool) ($general_settings_sel['wizard_autosave_enabled'] ?? true),
        'autosaveInterval'  => absint($general_settings_sel['wizard_autosave_interval'] ?? 60) * 1000,
        'i18n' => [
            'confirmDeleteDraft' => __('Are you sure you want to delete the draft', 'wahra-rentals-bookings'),
            'errorDeletion'      => __('Error during deletion.', 'wahra-rentals-bookings'),
            'saving'             => __('Saving...', 'wahra-rentals-bookings'),
            'next'               => __('Next', 'wahra-rentals-bookings'),
            'saveAndClose'       => __('Save and close', 'wahra-rentals-bookings'),
            'saveDraft'          => __('Save draft', 'wahra-rentals-bookings'),
            'draftSaved'         => __('Draft saved!', 'wahra-rentals-bookings'),
            'saveError'          => __('Save error', 'wahra-rentals-bookings'),
            'publishing'         => __('Publishing...', 'wahra-rentals-bookings'),
            'publishListing'     => __('Publish listing', 'wahra-rentals-bookings'),
            'publishSuccess'     => __('Listing published successfully!', 'wahra-rentals-bookings'),
            'publishError'       => __('Publish error', 'wahra-rentals-bookings'),
            'acceptTerms'        => __('Please accept the terms and conditions.', 'wahra-rentals-bookings'),
            'validationStep1'    => __('Please select a rental category.', 'wahra-rentals-bookings'),
            'validationStep2'    => __('Please select or name a product.', 'wahra-rentals-bookings'),
            'validationStep3'    => __('Please select at least one availability day.', 'wahra-rentals-bookings'),
            'validationStep4'    => __('Please set a base price.', 'wahra-rentals-bookings'),
        ],
    ]);
    ?>

    <?php else: ?>
    <!-- Wizard Form -->
    <form id="wahrb-wizard-form" method="post" action="">
        <input type="hidden" name="draft_id" value="<?php echo esc_attr($draft_id); ?>">
        <input type="hidden" name="product_id" value="<?php echo esc_attr($product_id); ?>">
        <input type="hidden" name="version_hash" value="<?php echo esc_attr($version_hash); ?>">
        <input type="hidden" name="current_step" id="current_step" value="<?php echo esc_attr($current_step); ?>">
        
        <!-- Progress Steps -->
        <div class="wahrb-wizard-progress">
            <?php 
            // Check which steps are complete
            $step_completion = [];
            $step_completion[1] = !empty($wizard_data['step_1']['offer_type']) || !empty($wizard_data['step_1']['platform_category']);
            $step_completion[2] = !empty($wizard_data['step_2']['product_name']) || !empty($wizard_data['product_id']);
            $step_completion[3] = !empty($wizard_data['step_3']['recurring_days']);
            $step_completion[4] = !empty($wizard_data['step_4']['base_price']) && floatval($wizard_data['step_4']['base_price']) > 0;
            $step_completion[5] = true; // Payment has defaults, always considered OK
            $step_completion[6] = !empty($wizard_data['step_6']['terms_accepted']);
            
            foreach ($steps as $step_num => $step_info): 
                $is_current = ($step_num === $current_step);
                $is_past = ($step_num < $current_step);
                $is_complete = !empty($step_completion[$step_num]);
                
                // Determine CSS class
                $step_class = '';
                if ($is_current) {
                    $step_class = 'active';
                } elseif ($is_past && $is_complete) {
                    $step_class = 'completed';
                } elseif ($is_past && !$is_complete) {
                    $step_class = 'incomplete';
                }
                
                // Determine icon
                if ($is_past && $is_complete) {
                    $step_icon = '✓';
                } elseif ($is_past && !$is_complete) {
                    $step_icon = '⚠️';
                } else {
                    $step_icon = $step_num;
                }
            ?>
                <div class="wahrb-progress-step <?php echo esc_attr($step_class); ?>" data-step="<?php echo esc_attr($step_num); ?>" style="cursor: pointer;">
                    <div class="wahrb-step-number"><?php echo esc_html($step_icon); ?></div>
                    <div class="wahrb-step-label"><?php echo esc_html($step_info['title']); ?></div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Step Content -->
        <div class="wahrb-wizard-content">
            <?php 
            if (isset($steps[$current_step])) {
                $step_file = WAHRB_PLUGIN_DIR . 'templates/dokan/wizard-steps/' . $steps[$current_step]['file'];
                if (file_exists($step_file)) {
                    include $step_file;
                }
            }
            ?>
        </div>

        <!-- Navigation -->
        <div class="wahrb-wizard-nav">
            <?php if ($current_step > 1): ?>
                <button type="button" class="wahrb-btn wahrb-btn-secondary" id="wahrb-prev-btn">
                    ← <?php esc_html_e('Previous', 'wahra-rentals-bookings'); ?>
                </button>
            <?php else: ?>
                <a href="<?php echo esc_url(wahrb_get_dashboard_url('wizard')); ?>" class="wahrb-btn wahrb-btn-secondary">
                    ← <?php esc_html_e('Back', 'wahra-rentals-bookings'); ?>
                </a>
            <?php endif; ?>
            
            <?php if ($current_step < 6): ?>
                <!-- Save Draft button for steps 1-5 -->
                <button type="button" class="wahrb-btn wahrb-btn-outline" id="wahrb-save-close-btn">
                    <?php esc_html_e('Save and close', 'wahra-rentals-bookings'); ?>
                </button>
                <button type="button" class="wahrb-btn wahrb-btn-primary" id="wahrb-next-btn">
                    <?php esc_html_e('Next', 'wahra-rentals-bookings'); ?> →
                </button>
            <?php endif; ?>
            <!-- Step 6 (Publish) has its own specific buttons in step-7-publish.php -->
        </div>
    </form>

    <?php
    // Localize wizard config for steps 1-6
    $general_settings_wiz = get_option('wahrb_settings_general', []);
    wp_localize_script('wahrb-wizard-php-js', 'wahrbWizardPhpConfig', [
        'apiUrl'            => esc_url_raw(untrailingslashit(rest_url('wahrb/v1'))),
        'nonce'             => wp_create_nonce('wp_rest'),
        'wizardUrl'         => esc_url_raw(wahrb_get_dashboard_url('wizard')),
        'productsUrl'       => esc_url_raw(wahrb_is_dokan_active() && function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('products') : admin_url('edit.php?post_type=product')),
        'draftId'           => absint($draft_id),
        'productId'         => absint($product_id),
        'currentStep'       => absint($current_step),
        'autosaveEnabled'   => (bool) ($general_settings_wiz['wizard_autosave_enabled'] ?? true),
        'autosaveInterval'  => absint($general_settings_wiz['wizard_autosave_interval'] ?? 60) * 1000,
        'i18n' => [
            'confirmDeleteDraft' => __('Are you sure you want to delete the draft', 'wahra-rentals-bookings'),
            'errorDeletion'      => __('Error during deletion.', 'wahra-rentals-bookings'),
            'saving'             => __('Saving...', 'wahra-rentals-bookings'),
            'next'               => __('Next', 'wahra-rentals-bookings'),
            'saveAndClose'       => __('Save and close', 'wahra-rentals-bookings'),
            'saveDraft'          => __('Save draft', 'wahra-rentals-bookings'),
            'draftSaved'         => __('Draft saved!', 'wahra-rentals-bookings'),
            'saveError'          => __('Save error', 'wahra-rentals-bookings'),
            'publishing'         => __('Publishing...', 'wahra-rentals-bookings'),
            'publishListing'     => __('Publish listing', 'wahra-rentals-bookings'),
            'publishSuccess'     => __('Listing published successfully!', 'wahra-rentals-bookings'),
            'publishError'       => __('Publish error', 'wahra-rentals-bookings'),
            'acceptTerms'        => __('Please accept the terms and conditions.', 'wahra-rentals-bookings'),
            'validationStep1'    => __('Please select a rental category.', 'wahra-rentals-bookings'),
            'validationStep2'    => __('Please select or name a product.', 'wahra-rentals-bookings'),
            'validationStep3'    => __('Please select at least one availability day.', 'wahra-rentals-bookings'),
            'validationStep4'    => __('Please set a base price.', 'wahra-rentals-bookings'),
        ],
    ]);
    ?>
    <?php endif; ?>
</div>

        </article>
    </div>

    <?php do_action('dokan_dashboard_content_after'); ?>
</div>
