<?php
/**
 * Dokan integration
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

/**
 * Dokan integration class
 */
class WAHRB_Dokan_Integration {

    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     */
    private function init_hooks(): void {
        // Add custom query vars (needed for routing)
        add_filter('dokan_query_var_filter', [$this, 'add_query_vars']);

        // Add dashboard menu items - standard filter
        add_filter('dokan_get_dashboard_nav', [$this, 'add_dashboard_menus'], 10);
        
        // Dokan 4.2+ React Dashboard - directly modify the layout config
        // This is the final filter before config is passed to JavaScript
        add_filter('dokan_vendor_dashboard_layout_config', [$this, 'modify_react_dashboard_config'], 10, 2);

        // Load custom templates
        add_action('dokan_load_custom_template', [$this, 'load_templates']);
        add_action('dokan_render_new_product_template', [$this, 'maybe_load_wizard']);
        
        // Template content for Dokan routes
        add_action('dokan_booking-wizard_content', [$this, 'render_wizard_content']);
        add_action('dokan_wahrb-bookings_content', [$this, 'render_bookings_content']);
        add_action('dokan_wahrb-calendar_content', [$this, 'render_calendar_content']);
        add_action('dokan_wahrb-analytics_content', [$this, 'render_analytics_content']);
        add_action('dokan_wahrb-settings_content', [$this, 'render_settings_content']);
        add_action('dokan_wahrb-form-builder_content', [$this, 'render_form_builder_content']);

        // Add product edit fields (Dokan passes post object and post_id)
        add_action('dokan_product_edit_after_inventory', [$this, 'add_product_rental_fields'], 10, 2);

        // Save product fields
        add_action('dokan_product_updated', [$this, 'save_product_rental_fields'], 10, 2);
        add_action('dokan_new_product_added', [$this, 'save_product_rental_fields'], 10, 2);

        // Enqueue scripts
        add_action('dokan_enqueue_scripts', [$this, 'enqueue_scripts']);

        // Add dashboard widget
        add_action('dokan_dashboard_content_inside_before', [$this, 'add_dashboard_widget']);

        // Filter vendor products
        add_filter('dokan_product_listing_filter_args', [$this, 'filter_rental_products']);
        
        // Fix sidebar active state for our submenu pages
        add_filter('dokan_dashboard_nav_active', [$this, 'fix_sidebar_active_menu'], 10, 3);
        
        // Flush rewrite rules if needed
        add_action('init', [$this, 'maybe_flush_rewrite_rules'], 999);
    }
    
    /**
     * Modify the React dashboard layout config for Dokan 4.2+
     * This directly injects our menu items into the sidebarNav
     *
     * @param array $config Dashboard config
     * @param mixed $vendor Vendor object
     * @return array Modified config
     */
    public function modify_react_dashboard_config(array $config, $vendor): array {
        // Check if sidebarNav exists
        if (!isset($config['sidebarNav'])) {
            return $config;
        }

        // Create parent menu with submenus
        $booking_menu = [
            'title'      => __('Bookings', 'wahra-rentals-bookings'),
            'icon'       => '<i class="fas fa-calendar-check"></i>',
            'icon_name'  => 'CalendarCheck',
            'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahra-rentals-bookings') : home_url('/dashboard/wahrb-bookings/'),
            'pos'        => 35,
            'permission' => 'dokan_view_store_menu',
            'submenu'    => [
                'booking-wizard' => [
                    'title'      => __('Rental Wizard', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-magic"></i>',
                    'icon_name'  => 'Wand',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('booking-wizard') : home_url('/dashboard/booking-wizard/'),
                    'pos'        => 10,
                ],
                'wahra-rentals-bookings' => [
                    'title'      => __('My Bookings', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-list"></i>',
                    'icon_name'  => 'List',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahra-rentals-bookings') : home_url('/dashboard/wahrb-bookings/'),
                    'pos'        => 20,
                ],
                'wahrb-calendar' => [
                    'title'      => __('Calendar', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-calendar-alt"></i>',
                    'icon_name'  => 'Calendar',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahrb-calendar') : home_url('/dashboard/wahrb-calendar/'),
                    'pos'        => 30,
                ],
                'wahrb-analytics' => [
                    'title'      => __('Statistics', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-chart-line"></i>',
                    'icon_name'  => 'BarChart3',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahrb-analytics') : home_url('/dashboard/wahrb-analytics/'),
                    'pos'        => 40,
                ],
                'wahrb-form-builder' => [
                    'title'      => __('Form Builder', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-clipboard-list"></i>',
                    'icon_name'  => 'ClipboardList',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahrb-form-builder') : home_url('/dashboard/wahrb-form-builder/'),
                    'pos'        => 45,
                ],
                'wahrb-settings' => [
                    'title'      => __('Settings', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-cog"></i>',
                    'icon_name'  => 'Settings',
                    'url'        => function_exists('dokan_get_navigation_url') ? dokan_get_navigation_url('wahrb-settings') : home_url('/dashboard/wahrb-settings/'),
                    'pos'        => 50,
                ],
            ],
        ];

        // Add parent menu to sidebarNav
        if (!isset($config['sidebarNav']['wahrb-reservation'])) {
            $config['sidebarNav']['wahrb-reservation'] = $booking_menu;
        }

        return $config;
    }
    
    /**
     * Flush rewrite rules if needed
     */
    public function maybe_flush_rewrite_rules(): void {
        if (get_option('wahrb_flush_rewrite_rules')) {
            flush_rewrite_rules();
            delete_option('wahrb_flush_rewrite_rules');
        }
    }
    
    /**
     * Render wizard content (for Dokan content action)
     */
    public function render_wizard_content(): void {
        $this->load_wizard_template();
    }
    
    /**
     * Render bookings content
     */
    public function render_bookings_content(): void {
        $this->load_bookings_template();
    }
    
    /**
     * Render calendar content
     */
    public function render_calendar_content(): void {
        $this->load_calendar_template();
    }
    
    /**
     * Render analytics content
     */
    public function render_analytics_content(): void {
        $this->load_analytics_template();
    }
    
    /**
     * Render settings content
     */
    public function render_settings_content(): void {
        $this->load_settings_template();
    }

    /**
     * Render form builder content
     */
    public function render_form_builder_content(): void {
        $this->load_form_builder_template();
    }
    
    /**
     * Maybe load wizard (for add new product)
     */
    public function maybe_load_wizard($template_name): void {
        // This is called when adding a new product in Dokan
    }

    /**
     * Add custom query vars
     *
     * @param array $vars Query vars
     * @return array Modified query vars
     */
    public function add_query_vars(array $vars): array {
        // Register our custom endpoints (Dokan uses indexed array)
        $vars[] = 'booking-wizard';
        $vars[] = 'wahra-rentals-bookings';
        $vars[] = 'wahrb-booking-detail';
        $vars[] = 'wahrb-calendar';
        $vars[] = 'wahrb-analytics';
        $vars[] = 'wahrb-settings';
        $vars[] = 'wahrb-form-builder';

        return $vars;
    }

    /**
     * Fix sidebar active menu detection for our submenu pages.
     *
     * Dokan determines the active parent menu from the URL path using
     * 'parent/submenu' format. Our endpoints are flat (e.g., 'wahrb-form-builder'),
     * so Dokan cannot match them to the parent 'wahrb-reservation'.
     * This filter rewrites the active menu to 'wahrb-reservation/{submenu-key}'
     * so Dokan can properly highlight the parent and submenu item.
     *
     * @param string $active_menu  Current active menu slug
     * @param string $request      Full request path
     * @param array  $active_parts Split path parts
     * @return string Possibly rewritten active menu
     */
    public function fix_sidebar_active_menu(string $active_menu, string $request, array $active_parts): string {
        $our_submenus = [
            'booking-wizard',
            'wahra-rentals-bookings',
            'wahrb-calendar',
            'wahrb-analytics',
            'wahrb-settings',
            'wahrb-form-builder',
        ];

        if (in_array($active_menu, $our_submenus, true)) {
            return 'wahrb-reservation/' . $active_menu;
        }

        return $active_menu;
    }

    /**
     * Add dashboard menu items (for legacy Dokan dashboard)
     *
     * @param array $urls Menu URLs
     * @return array Modified menu URLs
     */
    public function add_dashboard_menus(array $urls): array {
        // Parent menu: Réservation / Bookings
        $urls['wahrb-reservation'] = [
            'title'      => __('Bookings', 'wahra-rentals-bookings'),
            'icon'       => '<i class="fas fa-calendar-check"></i>',
            'icon_name'  => 'CalendarCheck',
            'url'        => dokan_get_navigation_url('wahra-rentals-bookings'),
            'pos'        => 35,
            'permission' => 'dokan_view_store_menu',
            'submenu'    => [
                'booking-wizard' => [
                    'title'      => __('Rental Wizard', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-magic"></i>',
                    'url'        => dokan_get_navigation_url('booking-wizard'),
                    'pos'        => 10,
                ],
                'wahra-rentals-bookings' => [
                    'title'      => __('My Bookings', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-list"></i>',
                    'url'        => dokan_get_navigation_url('wahra-rentals-bookings'),
                    'pos'        => 20,
                ],
                'wahrb-calendar' => [
                    'title'      => __('Calendar', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-calendar-alt"></i>',
                    'url'        => dokan_get_navigation_url('wahrb-calendar'),
                    'pos'        => 30,
                ],
                'wahrb-analytics' => [
                    'title'      => __('Statistics', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-chart-line"></i>',
                    'url'        => dokan_get_navigation_url('wahrb-analytics'),
                    'pos'        => 40,
                ],
                'wahrb-form-builder' => [
                    'title'      => __('Form Builder', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-clipboard-list"></i>',
                    'url'        => dokan_get_navigation_url('wahrb-form-builder'),
                    'pos'        => 45,
                ],
                'wahrb-settings' => [
                    'title'      => __('Settings', 'wahra-rentals-bookings'),
                    'icon'       => '<i class="fas fa-cog"></i>',
                    'url'        => dokan_get_navigation_url('wahrb-settings'),
                    'pos'        => 50,
                ],
            ],
        ];

        return $urls;
    }

    /**
     * Load custom templates
     *
     * @param array $query_vars Query vars
     */
    public function load_templates(array $query_vars): void {
        if (isset($query_vars['booking-wizard'])) {
            $this->load_wizard_template();
            return;
        }
        
        if (isset($query_vars['wahra-rentals-bookings'])) {
            $this->load_bookings_template();
            return;
        }

        if (isset($query_vars['wahrb-booking-detail'])) {
            $this->load_booking_detail_template();
            return;
        }
        
        if (isset($query_vars['wahrb-calendar'])) {
            $this->load_calendar_template();
            return;
        }
        
        if (isset($query_vars['wahrb-analytics'])) {
            $this->load_analytics_template();
            return;
        }
        
        if (isset($query_vars['wahrb-settings'])) {
            $this->load_settings_template();
            return;
        }

        if (isset($query_vars['wahrb-form-builder'])) {
            $this->load_form_builder_template();
            return;
        }
    }

    /**
     * Load wizard template (React app container)
     */
    private function load_wizard_template(): void {
        // Enqueue React wizard app
        $this->enqueue_wizard_assets();

        // Get product ID if editing
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
        $product_id = isset($_GET['product_id']) ? absint(wp_unslash($_GET['product_id'])) : null;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
        $draft_id = isset($_GET['draft_id']) ? absint(wp_unslash($_GET['draft_id'])) : null;

        // Verify product belongs to vendor
        if ($product_id) {
            $product = wc_get_product($product_id);
            if (!$product || get_post_field('post_author', $product_id) != get_current_user_id()) {
                $product_id = null;
            }
        }

        // Load template
        include WAHRB_PLUGIN_DIR . 'templates/dokan/booking-wizard.php';
    }

    /**
     * Load bookings list template
     */
    private function load_bookings_template(): void {
        $this->enqueue_vendor_assets();

        // Flatpickr for manual booking date picker with blocked dates
        wp_enqueue_style('flatpickr', WAHRB_PLUGIN_URL . 'assets/vendor/flatpickr/flatpickr.min.css', [], '4.6.13');
        wp_enqueue_script('flatpickr', WAHRB_PLUGIN_URL . 'assets/vendor/flatpickr/flatpickr.min.js', [], '4.6.13', true);
        wp_enqueue_script('flatpickr-fr', WAHRB_PLUGIN_URL . 'assets/vendor/flatpickr/l10n/fr.js', ['flatpickr'], '4.6.13', true);

        include WAHRB_PLUGIN_DIR . 'templates/dokan/bookings-list.php';
    }

    /**
     * Load booking detail template (vendor-facing)
     */
    private function load_booking_detail_template(): void {
        $this->enqueue_vendor_assets();
        include WAHRB_PLUGIN_DIR . 'templates/dokan/booking-detail.php';
    }

    /**
     * Load calendar template
     */
    private function load_calendar_template(): void {
        $this->enqueue_vendor_assets();
        $this->enqueue_calendar_assets();
        include WAHRB_PLUGIN_DIR . 'templates/dokan/calendar.php';
    }

    /**
     * Load analytics template
     */
    private function load_analytics_template(): void {
        wp_enqueue_script(
            'chartjs',
            WAHRB_PLUGIN_URL . 'assets/vendor/chartjs/chart.min.js',
            [],
            '4.5.1',
            true
        );
        $this->enqueue_vendor_assets();
        include WAHRB_PLUGIN_DIR . 'templates/dokan/analytics.php';
    }

    /**
     * Load settings template
     */
    private function load_settings_template(): void {
        $this->enqueue_vendor_assets();
        include WAHRB_PLUGIN_DIR . 'templates/dokan/settings.php';
    }

    /**
     * Load form builder template
     */
    private function load_form_builder_template(): void {
        $this->enqueue_vendor_assets();
        $this->enqueue_form_builder_assets();
        include WAHRB_PLUGIN_DIR . 'templates/dokan/form-builder.php';
    }

    /**
     * Enqueue form builder assets (SortableJS + builder CSS/JS)
     */
    private function enqueue_form_builder_assets(): void {
        wp_enqueue_script(
            'sortablejs',
            WAHRB_PLUGIN_URL . 'assets/vendor/sortablejs/Sortable.min.js',
            [],
            '1.15.6',
            true
        );

        wp_enqueue_style(
            'wahrb-form-builder-css',
            WAHRB_PLUGIN_URL . 'assets/css/wahrb-form-builder.css',
            [],
            WAHRB_VERSION
        );

        wp_enqueue_script(
            'wahrb-form-builder-js',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-form-builder.js',
            ['sortablejs'],
            WAHRB_VERSION,
            true
        );
    }

    /**
     * Enqueue wizard React assets
     */
    private function enqueue_wizard_assets(): void {
        $vendor_id = get_current_user_id();
        
        // Ensure WordPress Media is available
        if (!did_action('wp_enqueue_media')) {
            wp_enqueue_media();
        }

        // Use filemtime for cache-busting (ensures fresh JS after updates)
        $php_js_path = WAHRB_PLUGIN_DIR . 'assets/js/wahrb-wizard-php.js';
        $steps_js_path = WAHRB_PLUGIN_DIR . 'assets/js/wahrb-wizard-steps.js';
        $php_js_ver = WAHRB_VERSION . '.' . (file_exists($php_js_path) ? filemtime($php_js_path) : '0');
        $steps_js_ver = WAHRB_VERSION . '.' . (file_exists($steps_js_path) ? filemtime($steps_js_path) : '0');

        // PHP multi-step wizard styles and scripts (always needed)
        wp_enqueue_style('wahrb-wizard-php', WAHRB_PLUGIN_URL . 'assets/css/wizard-php.css', [], WAHRB_VERSION);

        wp_enqueue_script(
            'wahrb-wizard-php-js',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-wizard-php.js',
            [],
            $php_js_ver,
            true
        );

        wp_enqueue_script(
            'wahrb-wizard-steps',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-wizard-steps.js',
            [],
            $steps_js_ver,
            true
        );

        // Check if built assets exist (Vite outputs to assets/ folder)
        $manifest_path = WAHRB_PLUGIN_DIR . 'assets/.vite/manifest.json';
        $wizard_js_path = WAHRB_PLUGIN_DIR . 'assets/js/wizard.js';
        
        if (file_exists($wizard_js_path)) {
            // Main JS bundle - Vite outputs ES modules, need type="module"
            wp_enqueue_script(
                'wahrb-wizard-app',
                WAHRB_PLUGIN_URL . 'assets/js/wizard.js',
                [], // No dependencies - ES module handles its own imports
                WAHRB_VERSION,
                true
            );

            // Frontend validation script (client-side field validation)
            wp_enqueue_script(
                'wahrb-wizard-validation',
                WAHRB_PLUGIN_URL . 'assets/js/wizard-validation.js',
                ['jquery'],
                WAHRB_VERSION,
                true
            );

            // Add type="module" attribute for ES module support
            add_filter('script_loader_tag', function($tag, $handle, $src) {
                if ($handle === 'wahrb-wizard-app') {
                    $tag = str_replace('<script ', '<script type="module" ', $tag);
                }
                return $tag;
            }, 10, 3);

            // Localize script with config
            wp_localize_script('wahrb-wizard-app', 'wahrbWizardConfig', [
                'apiUrl' => untrailingslashit(rest_url('wahrb/v1')),
                'nonce' => wp_create_nonce('wp_rest'),
                'vendorId' => $vendor_id,
                'locale' => str_replace('_', '-', get_user_locale()),
                'currency' => get_woocommerce_currency(),
                'currencySymbol' => html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8'),
                'timeFormat' => get_option('time_format'),
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
                'productId' => isset($_GET['product_id']) ? absint(wp_unslash($_GET['product_id'])) : null,
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
                'draftId' => isset($_GET['draft_id']) ? absint(wp_unslash($_GET['draft_id'])) : null,
                'settings' => $this->get_vendor_settings($vendor_id),
                'strings' => $this->get_wizard_strings(),
                'serviceTypes' => $this->get_service_types_config(),
                'categories' => $this->get_wizard_categories(),
                'platformCategories' => WAHRB_Platform_Categories::get_js_config(),
            ]);
        }
    }

    /**
     * Enqueue vendor dashboard assets
     */
    private function enqueue_vendor_assets(): void {
        wp_enqueue_style(
            'wahrb-vendor-styles',
            WAHRB_PLUGIN_URL . 'assets/css/wahrb-vendor.css',
            [],
            WAHRB_VERSION
        );

        wp_enqueue_script(
            'wahrb-vendor-script',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-vendor.js',
            ['jquery'],
            WAHRB_VERSION,
            true
        );

        wp_localize_script('wahrb-vendor-script', 'wahrbVendorConfig', [
            'apiUrl' => rest_url('wahrb/v1'),
            'nonce' => wp_create_nonce('wp_rest'),
            'vendorId' => get_current_user_id(),
            'currency' => get_woocommerce_currency(),
            'currencySymbol' => html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8'),
            'i18n' => [
                'confirmBooking'  => __('Confirm this booking?', 'wahra-rentals-bookings'),
                'cancelReason'    => __('Cancellation reason (optional):', 'wahra-rentals-bookings'),
                'checkinNotes'    => __('Check-in notes (optional):', 'wahra-rentals-bookings'),
                'checkoutNotes'   => __('Check-out notes (product condition, damages...):', 'wahra-rentals-bookings'),
                'error'           => __('Error', 'wahra-rentals-bookings'),
                'unknownError'    => __('An error occurred', 'wahra-rentals-bookings'),
                'loading'         => __('Loading...', 'wahra-rentals-bookings'),
                'loadError'       => __('Loading error', 'wahra-rentals-bookings'),
                'noData'          => __('No data', 'wahra-rentals-bookings'),
                'noBookings'      => __('No bookings', 'wahra-rentals-bookings'),
                'bookings'        => __('Bookings', 'wahra-rentals-bookings'),
                'revenue'         => __('Revenue', 'wahra-rentals-bookings'),
                'view'            => __('View', 'wahra-rentals-bookings'),
            ],
        ]);
    }

    /**
     * Enqueue calendar assets
     */
    private function enqueue_calendar_assets(): void {
        // FullCalendar (local vendor files)
        wp_enqueue_style(
            'fullcalendar',
            WAHRB_PLUGIN_URL . 'assets/vendor/fullcalendar/fullcalendar.min.css',
            [],
            '6.1.20'
        );

        wp_enqueue_script(
            'fullcalendar',
            WAHRB_PLUGIN_URL . 'assets/vendor/fullcalendar/fullcalendar.min.js',
            [],
            '6.1.20',
            true
        );

        wp_enqueue_script(
            'fullcalendar-locales',
            WAHRB_PLUGIN_URL . 'assets/vendor/fullcalendar/locales-all.min.js',
            ['fullcalendar'],
            '6.1.20',
            true
        );

        wp_enqueue_style(
            'wahrb-calendar-styles',
            WAHRB_PLUGIN_URL . 'assets/css/wahrb-calendar.css',
            ['fullcalendar'],
            WAHRB_VERSION
        );

        wp_enqueue_script(
            'wahrb-calendar-script',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-calendar.js',
            ['fullcalendar', 'fullcalendar-locales'],
            WAHRB_VERSION,
            true
        );
    }

    /**
     * Get vendor settings
     *
     * @param int $vendor_id Vendor ID
     * @return array Settings
     */
    private function get_vendor_settings(int $vendor_id): array {
        // Get all admin settings
        $general_settings = get_option('wahrb_settings_general', []);
        $booking_settings = get_option('wahrb_settings_booking', []);
        $payment_settings = get_option('wahrb_settings_payment', []);
        $vendor_permissions = get_option('wahrb_settings_vendor_permissions', []);
        $notification_settings = get_option('wahrb_settings_notifications', []);

        // Get per-category pricing rules
        $pricing_rules = [];
        $enabled = WAHRB_Platform_Categories::get_enabled();
        foreach ($enabled as $slug => $cat) {
            $pricing_rules[$slug] = WAHRB_Platform_Categories::get_category_pricing($slug);
        }

        // Get vendor-specific overrides
        $vendor_overrides = get_user_meta($vendor_id, '_wahrb_vendor_settings', true) ?: [];

        // Per-category payment settings
        $payment_by_category = WAHRB_Platform_Categories::get_all_payment_settings();

        // Per-category vendor permissions
        $permissions_by_category = [];
        foreach ($enabled as $slug => $cat) {
            $permissions_by_category[$slug] = WAHRB_Platform_Categories::get_vendor_permissions($slug);
        }

        // Global require_approval flag
        $vendor_permissions = get_option('wahrb_settings_vendor_permissions', []);
        $require_approval   = !empty($vendor_permissions['require_approval']);

        // Build settings from admin config
        $settings = [
            // General - from admin settings
            'timezone' => $general_settings['timezone'] ?? wp_timezone_string(),
            'wizard_welcome_text' => $general_settings['wizard_welcome_text'] ?? '',

            // Date & Time Format
            'date_format' => $general_settings['date_format'] ?? 'Y-m-d',
            'time_format' => $general_settings['time_format'] ?? '24h',

            // Terms & Conditions (for wizard step 7)
            'terms_url' => $general_settings['terms_url'] ?? '',
            'vendor_consent_text' => $general_settings['vendor_consent_text'] ?? __('I accept the terms and conditions', 'wahra-rentals-bookings'),
            'terms_required' => $general_settings['terms_required'] ?? true,

            // Payment - per-category (new structure)
            'payment_by_category' => $payment_by_category,
            
            // Booking - from admin settings
            'min_booking_window_hours' => $booking_settings['min_booking_window_hours'] ?? 24,
            'max_booking_window_days' => $booking_settings['max_booking_window_days'] ?? 365,
            'buffer_before_hours' => $booking_settings['buffer_before_hours'] ?? 0,
            'buffer_after_hours' => $booking_settings['buffer_after_hours'] ?? 0,
            'default_min_stay_days' => $booking_settings['default_min_stay_days'] ?? 1,
            'default_max_stay_days' => $booking_settings['default_max_stay_days'] ?? 30,
            'hold_duration_minutes' => $booking_settings['hold_duration_minutes'] ?? 30,
            
            // Notifications - from admin settings
            'balance_reminder_days' => $notification_settings['balance_reminder_days'] ?? 3,
            
            // Pricing rules - per category
            'pricing_rules' => $pricing_rules,
            
            // Vendor permissions - per category (new structure)
            'permissions_by_category' => $permissions_by_category,
            'require_approval' => $require_approval,
            
            // Currency (override WooCommerce if set in admin)
            'currency_symbol' => !empty($general_settings['currency_symbol']) ? $general_settings['currency_symbol'] : html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8'),
            'currency_position' => $general_settings['currency_position'] ?? 'before',
        ];

        // Allow vendor overrides for permitted fields (per-category)
        // Vendors can override deposit values for categories where can_set_deposit_amount is true
        if (!empty($vendor_overrides)) {
            foreach ($payment_by_category as $cat_slug => $cat_pay) {
                $cat_perms = $permissions_by_category[$cat_slug] ?? [];
                if (!empty($cat_perms['can_set_deposit_amount']) && isset($vendor_overrides["deposit_value_{$cat_slug}"])) {
                    $settings['payment_by_category'][$cat_slug]['deposit_value'] = $vendor_overrides["deposit_value_{$cat_slug}"];
                }
            }
        }

        return $settings;
    }

    /**
     * Get service types configuration from admin settings
     * Only returns enabled types
     *
     * @return array Service types config
     */
    private function get_service_types_config(): array {
        // Derive enabled service types from platform categories
        $enabled = WAHRB_Platform_Categories::get_enabled();
        $modes = [];
        foreach ($enabled as $slug => $cat) {
            foreach ($cat['booking_modes'] as $mode) {
                if (!isset($modes[$mode])) {
                    $modes[$mode] = [
                        'title' => '',
                        'description' => '',
                    ];
                }
            }
        }
        // Set default titles for each mode
        $mode_defaults = [
            'day' => [
                'title' => __('Daily rental', 'wahra-rentals-bookings'),
                'description' => __('Reservation by full day', 'wahra-rentals-bookings'),
            ],
            'slot' => [
                'title' => __('Time slot booking', 'wahra-rentals-bookings'),
                'description' => __('Reservation on specific time slots', 'wahra-rentals-bookings'),
            ],
            'service' => [
                'title' => __('One-time service', 'wahra-rentals-bookings'),
                'description' => __('Single service on a specific date', 'wahra-rentals-bookings'),
            ],
            'product' => [
                'title' => __('Physical Product', 'wahra-rentals-bookings'),
                'description' => __('Product sale without reservation', 'wahra-rentals-bookings'),
            ],
        ];
        foreach ($modes as $mode => &$data) {
            if (isset($mode_defaults[$mode])) {
                $data = $mode_defaults[$mode];
            }
        }
        unset($data);

        // Also merge any legacy service types settings for backward compat
        $legacy = get_option('wahrb_settings_service_types', []);
        foreach ($legacy as $key => $config) {
            if (!empty($config['enabled']) && isset($modes[$key])) {
                if (!empty($config['title'])) {
                    $modes[$key]['title'] = $config['title'];
                }
                if (!empty($config['description'])) {
                    $modes[$key]['description'] = $config['description'];
                }
            }
        }

        return $modes;
    }

    /**
     * Get enabled categories for wizard
     * 
     * @return array
     */
    private function get_wizard_categories(): array {
        $enabled = WAHRB_Platform_Categories::get_enabled();
        $settings = WAHRB_Platform_Categories::get_settings();
        $result = [];

        foreach ($enabled as $slug => $cat) {
            $cat_settings = $settings[$slug] ?? [];
            foreach ($cat['subcategories'] as $sub_slug => $sub_label) {
                if (!empty($cat_settings['subcategories'][$sub_slug])) {
                    $result[] = [
                        'id' => $sub_slug,
                        'label' => $sub_label,
                        'group' => $cat['label'],
                        'category' => $slug,
                    ];
                }
            }
        }

        return $result;
    }

    /**
     * Get wizard strings for i18n
     *
     * @return array Translated strings
     */
    private function get_wizard_strings(): array {
        return [
            // General
            'next' => __('Next', 'wahra-rentals-bookings'),
            'previous' => __('Previous', 'wahra-rentals-bookings'),
            'save' => __('Save', 'wahra-rentals-bookings'),
            'publish' => __('Publish', 'wahra-rentals-bookings'),
            'saveDraft' => __('Save Draft', 'wahra-rentals-bookings'),
            'cancel' => __('Cancel', 'wahra-rentals-bookings'),
            'loading' => __('Loading...', 'wahra-rentals-bookings'),
            'error' => __('Error', 'wahra-rentals-bookings'),
            'success' => __('Success', 'wahra-rentals-bookings'),

            // Step 0
            'step0Title' => __('Rental Wizard', 'wahra-rentals-bookings'),
            'step0Subtitle' => __('Follow the steps to publish your rental listing', 'wahra-rentals-bookings'),
            'createNew' => __('New item to rent', 'wahra-rentals-bookings'),
            'editExisting' => __('Edit existing product', 'wahra-rentals-bookings'),
            'continueDraft' => __('Resume a draft', 'wahra-rentals-bookings'),

            // Step 1
            'step1Title' => __('Offer type', 'wahra-rentals-bookings'),
            'dayRental' => __('Rental (Day)', 'wahra-rentals-bookings'),
            'dayRentalDesc' => __('Rent by day (bike, tools...)', 'wahra-rentals-bookings'),
            'slotRental' => __('Rental (Slots)', 'wahra-rentals-bookings'),
            'slotRentalDesc' => __('Rent by time slot (classes, rooms...)', 'wahra-rentals-bookings'),
            'service' => __('Service', 'wahra-rentals-bookings'),
            'serviceDesc' => __('One-time or appointment-based services', 'wahra-rentals-bookings'),

            // Step 2
            'step2Title' => __('Inventory & Product', 'wahra-rentals-bookings'),
            'productName' => __('Product name', 'wahra-rentals-bookings'),
            'productDescription' => __('Description', 'wahra-rentals-bookings'),
            'isVariable' => __('Variable product (multiple sizes/colors)', 'wahra-rentals-bookings'),
            'variations' => __('Variations', 'wahra-rentals-bookings'),
            'availableUnits' => __('Available units', 'wahra-rentals-bookings'),
            'enableForRental' => __('Enable for rental', 'wahra-rentals-bookings'),

            // Step 3
            'step3Title' => __('Availability', 'wahra-rentals-bookings'),
            'recurrence' => __('Available days', 'wahra-rentals-bookings'),
            'allDays' => __('Every day', 'wahra-rentals-bookings'),
            'weekdays' => __('Monday to Friday', 'wahra-rentals-bookings'),
            'weekends' => __('Saturday and Sunday', 'wahra-rentals-bookings'),
            'custom' => __('Custom', 'wahra-rentals-bookings'),
            'monday' => __('Mon', 'wahra-rentals-bookings'),
            'tuesday' => __('Tue', 'wahra-rentals-bookings'),
            'wednesday' => __('Wed', 'wahra-rentals-bookings'),
            'thursday' => __('Thu', 'wahra-rentals-bookings'),
            'friday' => __('Fri', 'wahra-rentals-bookings'),
            'saturday' => __('Sat', 'wahra-rentals-bookings'),
            'sunday' => __('Sun', 'wahra-rentals-bookings'),
            'blackoutDates' => __('Unavailable dates', 'wahra-rentals-bookings'),
            'addBlackout' => __('Add period', 'wahra-rentals-bookings'),
            'constraints' => __('Booking constraints', 'wahra-rentals-bookings'),
            'minBookingWindow' => __('Minimum booking window (days)', 'wahra-rentals-bookings'),
            'maxBookingWindow' => __('Maximum booking window (days)', 'wahra-rentals-bookings'),
            'minStay' => __('Minimum duration (days)', 'wahra-rentals-bookings'),
            'maxStay' => __('Maximum duration (days)', 'wahra-rentals-bookings'),
            'bufferBefore' => __('Preparation time (hours)', 'wahra-rentals-bookings'),
            'bufferAfter' => __('Cleaning time (hours)', 'wahra-rentals-bookings'),

            // Step 4
            'step4Title' => __('Pricing', 'wahra-rentals-bookings'),
            'basePrice' => __('Base price', 'wahra-rentals-bookings'),
            'perDay' => __('per day', 'wahra-rentals-bookings'),
            'perHour' => __('per hour', 'wahra-rentals-bookings'),
            'pricingRules' => __('Pricing rules', 'wahra-rentals-bookings'),
            'addRule' => __('Add rule', 'wahra-rentals-bookings'),
            'ruleName' => __('Rule name', 'wahra-rentals-bookings'),
            'ruleType' => __('Type', 'wahra-rentals-bookings'),
            'dateRange' => __('Date range', 'wahra-rentals-bookings'),
            'weekday' => __('Weekday', 'wahra-rentals-bookings'),
            'duration' => __('Duration', 'wahra-rentals-bookings'),
            'modifier' => __('Modifier', 'wahra-rentals-bookings'),
            'fixed' => __('Fixed', 'wahra-rentals-bookings'),
            'percent' => __('Percentage', 'wahra-rentals-bookings'),
            'priority' => __('Priority', 'wahra-rentals-bookings'),
            'pricePreview' => __('Price preview', 'wahra-rentals-bookings'),

            // Step 5
            'step5Title' => __('Payments', 'wahra-rentals-bookings'),
            'deposit' => __('Deposit', 'wahra-rentals-bookings'),
            'depositEnabled' => __('Request deposit at booking', 'wahra-rentals-bookings'),
            'depositAmount' => __('Deposit amount', 'wahra-rentals-bookings'),
            'depositRefundable' => __('Refundable on cancellation', 'wahra-rentals-bookings'),
            'securityDeposit' => __('Security deposit', 'wahra-rentals-bookings'),
            'securityEnabled' => __('Request security deposit', 'wahra-rentals-bookings'),
            'securityAmount' => __('Security deposit amount', 'wahra-rentals-bookings'),
            'captureMode' => __('Charge immediately', 'wahra-rentals-bookings'),
            'authMode' => __('Stripe authorization (hold without charge)', 'wahra-rentals-bookings'),
            'balance' => __('Balance', 'wahra-rentals-bookings'),
            'balanceEnabled' => __('Balance due before pickup', 'wahra-rentals-bookings'),
            'balanceDueDays' => __('Days before pickup', 'wahra-rentals-bookings'),
            'allowCod' => __('Allow payment on pickup', 'wahra-rentals-bookings'),
            'paymentSummary' => __('Payment summary', 'wahra-rentals-bookings'),

            // Step 6
            'step6Title' => __('Photos', 'wahra-rentals-bookings'),
            'uploadImages' => __('Add photos', 'wahra-rentals-bookings'),
            'takePhoto' => __('Take photo', 'wahra-rentals-bookings'),
            'chooseFromGallery' => __('Choose from gallery', 'wahra-rentals-bookings'),
            'dragAndDrop' => __('Drag and drop images here', 'wahra-rentals-bookings'),
            'maxImages' => __('Maximum 10 images', 'wahra-rentals-bookings'),
            'imageCompressing' => __('Compressing...', 'wahra-rentals-bookings'),

            // Step 7
            'step7Title' => __('Publication', 'wahra-rentals-bookings'),
            'cancellationPolicy' => __('Cancellation policy', 'wahra-rentals-bookings'),
            'flexible' => __('Flexible', 'wahra-rentals-bookings'),
            'flexibleDesc' => __('Free cancellation up to 24h before', 'wahra-rentals-bookings'),
            'moderate' => __('Moderate', 'wahra-rentals-bookings'),
            'moderateDesc' => __('50% refund up to 72h before', 'wahra-rentals-bookings'),
            'strict' => __('Strict', 'wahra-rentals-bookings'),
            'strictDesc' => __('Non-refundable after confirmation', 'wahra-rentals-bookings'),
            'acceptTerms' => __('I accept the terms and conditions', 'wahra-rentals-bookings'),
            'offerSummary' => __('Offer summary', 'wahra-rentals-bookings'),
            'publishSuccess' => __('Your product has been published successfully!', 'wahra-rentals-bookings'),
        ];
    }

    /**
     * Add product rental fields in Dokan product edit
     *
     * @param mixed $post_or_product Post object or WC_Product
     * @param int|null $post_id Product ID (optional, derived from first arg if not provided)
     */
    public function add_product_rental_fields($post_or_product, $post_id = null): void {
        // Handle flexible argument passing from different Dokan versions
        if (is_null($post_id)) {
            // Dokan may pass WP_Post or WC_Product
            if ($post_or_product instanceof WP_Post) {
                $post_id = $post_or_product->ID;
            } elseif ($post_or_product instanceof WC_Product) {
                $post_id = $post_or_product->get_id();
            } elseif (is_numeric($post_or_product)) {
                $post_id = (int) $post_or_product;
            } else {
                // Try to get from global
                global $post;
                $post_id = $post ? $post->ID : 0;
            }
        }
        
        if (!$post_id) {
            return;
        }

        $rental_enabled = get_post_meta($post_id, '_wahrb_rental_enabled', true);
        $booking_mode = get_post_meta($post_id, '_wahrb_booking_mode', true) ?: 'day';
        $base_price = get_post_meta($post_id, '_wahrb_base_price', true);
        $security_deposit = get_post_meta($post_id, '_wahrb_security_deposit', true);
        $total_units = get_post_meta($post_id, '_wahrb_total_units', true) ?: 1;
        $min_duration = get_post_meta($post_id, '_wahrb_min_duration', true) ?: 1;
        $max_duration = get_post_meta($post_id, '_wahrb_max_duration', true) ?: 365;
        
        // Slot mode fields
        $slot_duration = get_post_meta($post_id, '_wahrb_slot_duration_minutes', true) ?: 60;
        $min_hours = get_post_meta($post_id, '_wahrb_min_duration_hours', true) ?: 1;
        $max_hours = get_post_meta($post_id, '_wahrb_max_duration_hours', true) ?: 8;
        $business_hours = get_post_meta($post_id, '_wahrb_business_hours', true) ?: ['start' => '09:00', 'end' => '18:00'];
        
        // Service mode fields
        $service_duration = get_post_meta($post_id, '_wahrb_service_duration_minutes', true) ?: 60;
        $capacity_per_slot = get_post_meta($post_id, '_wahrb_capacity_per_slot', true) ?: 1;
        ?>

        <div class="dokan-form-group wahrb-rental-fields">
            <h3><?php esc_html_e('Rental Configuration', 'wahra-rentals-bookings'); ?></h3>
            <?php wp_nonce_field('wahrb_save_rental_fields', '_wahrb_rental_nonce'); ?>

            <div class="dokan-form-group">
                <label class="dokan-checkbox-inline">
                    <input type="checkbox" name="_wahrb_rental_enabled" value="yes" <?php checked($rental_enabled, 'yes'); ?>>
                    <?php esc_html_e('Enable rental for this product', 'wahra-rentals-bookings'); ?>
                </label>
            </div>

            <!-- Wizard button always visible -->
            <div class="dokan-form-group">
                <a href="<?php echo esc_url(dokan_get_navigation_url('booking-wizard') . '?product_id=' . $post_id); ?>" class="dokan-btn dokan-btn-theme" id="wahrb-wizard-btn">
                    <i class="fas fa-magic"></i> <?php esc_html_e('Configure with wizard', 'wahra-rentals-bookings'); ?>
                </a>
                <p class="description"><?php esc_html_e('Use the interactive wizard to configure rental settings for this product.', 'wahra-rentals-bookings'); ?></p>
            </div>

            <div class="wahrb-rental-options" style="<?php echo esc_attr( $rental_enabled !== 'yes' ? 'display:none;' : '' ); ?>">
                <div class="dokan-form-group">
                    <label for="_wahrb_booking_mode"><?php esc_html_e('Booking mode', 'wahra-rentals-bookings'); ?></label>
                    <select name="_wahrb_booking_mode" id="_wahrb_booking_mode" class="dokan-form-control">
                        <?php if (WAHRB_Vendor_Permissions::is_mode_allowed('day')): ?>
                        <option value="day" <?php selected($booking_mode, 'day'); ?>><?php esc_html_e('Daily rental', 'wahra-rentals-bookings'); ?></option>
                        <?php endif; ?>
                        <?php if (WAHRB_Vendor_Permissions::is_mode_allowed('slot')): ?>
                        <option value="slot" <?php selected($booking_mode, 'slot'); ?>><?php esc_html_e('Time slot rental (hourly)', 'wahra-rentals-bookings'); ?></option>
                        <?php endif; ?>
                        <?php if (WAHRB_Vendor_Permissions::is_mode_allowed('service')): ?>
                        <option value="service" <?php selected($booking_mode, 'service'); ?>><?php esc_html_e('Service (appointment)', 'wahra-rentals-bookings'); ?></option>
                        <?php endif; ?>
                    </select>
                    <p class="description wahrb-mode-desc wahrb-mode-day" style="<?php echo esc_attr( $booking_mode !== 'day' ? 'display:none;' : '' ); ?>"><?php esc_html_e('Perfect for bikes, cars, equipment - charged per day.', 'wahra-rentals-bookings'); ?></p>
                    <p class="description wahrb-mode-desc wahrb-mode-slot" style="<?php echo esc_attr( $booking_mode !== 'slot' ? 'display:none;' : '' ); ?>"><?php esc_html_e('Perfect for meeting rooms, sports courts - charged per hour.', 'wahra-rentals-bookings'); ?></p>
                    <p class="description wahrb-mode-desc wahrb-mode-service" style="<?php echo esc_attr( $booking_mode !== 'service' ? 'display:none;' : '' ); ?>"><?php esc_html_e('Perfect for massages, consultations - fixed duration per session.', 'wahra-rentals-bookings'); ?></p>
                </div>

                <div class="dokan-form-group">
                    <label for="_wahrb_base_price">
                        <?php esc_html_e('Base price', 'wahra-rentals-bookings'); ?> (<?php echo esc_html(get_woocommerce_currency_symbol()); ?>)
                        <span class="wahrb-price-label wahrb-mode-day" style="<?php echo esc_attr( $booking_mode !== 'day' ? 'display:none;' : '' ); ?>"><?php esc_html_e('per day', 'wahra-rentals-bookings'); ?></span>
                        <span class="wahrb-price-label wahrb-mode-slot" style="<?php echo esc_attr( $booking_mode !== 'slot' ? 'display:none;' : '' ); ?>"><?php esc_html_e('per hour', 'wahra-rentals-bookings'); ?></span>
                        <span class="wahrb-price-label wahrb-mode-service" style="<?php echo esc_attr( $booking_mode !== 'service' ? 'display:none;' : '' ); ?>"><?php esc_html_e('per session', 'wahra-rentals-bookings'); ?></span>
                    </label>
                    <input type="number" step="0.01" min="0" name="_wahrb_base_price" id="_wahrb_base_price" class="dokan-form-control" value="<?php echo esc_attr($base_price); ?>">
                </div>

                <div class="dokan-form-group">
                    <label for="_wahrb_security_deposit"><?php esc_html_e('Security deposit', 'wahra-rentals-bookings'); ?> (<?php echo esc_html(get_woocommerce_currency_symbol()); ?>)</label>
                    <input type="number" step="0.01" min="0" name="_wahrb_security_deposit" id="_wahrb_security_deposit" class="dokan-form-control" value="<?php echo esc_attr($security_deposit); ?>">
                    <p class="description"><?php esc_html_e('Optional - security deposit amount', 'wahra-rentals-bookings'); ?></p>
                </div>

                <!-- DAY MODE FIELDS -->
                <div class="wahrb-day-fields" style="<?php echo esc_attr( $booking_mode !== 'day' ? 'display:none;' : '' ); ?>">
                    <div class="dokan-form-group">
                        <label for="_wahrb_total_units"><?php esc_html_e('Available units', 'wahra-rentals-bookings'); ?></label>
                        <input type="number" step="1" min="1" name="_wahrb_total_units" id="_wahrb_total_units" class="dokan-form-control" value="<?php echo esc_attr($total_units); ?>">
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_min_duration"><?php esc_html_e('Minimum duration (days)', 'wahra-rentals-bookings'); ?></label>
                            <input type="number" step="1" min="1" name="_wahrb_min_duration" id="_wahrb_min_duration" class="dokan-form-control" value="<?php echo esc_attr($min_duration); ?>">
                        </div>
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_max_duration"><?php esc_html_e('Maximum duration (days)', 'wahra-rentals-bookings'); ?></label>
                            <input type="number" step="1" min="1" name="_wahrb_max_duration" id="_wahrb_max_duration" class="dokan-form-control" value="<?php echo esc_attr($max_duration); ?>">
                        </div>
                    </div>
                </div>

                <!-- SLOT MODE FIELDS -->
                <div class="wahrb-slot-fields" style="<?php echo esc_attr( $booking_mode !== 'slot' ? 'display:none;' : '' ); ?>">
                    <?php
                    $can_customize_duration = WAHRB_Vendor_Permissions::can_customize_slot_duration();
                    $can_customize_hours = WAHRB_Vendor_Permissions::can_customize_business_hours();
                    $allowed_durations = WAHRB_Vendor_Permissions::get_allowed_slot_durations();
                    $duration_labels = [
                        30 => __('30 minutes', 'wahra-rentals-bookings'),
                        60 => __('1 hour', 'wahra-rentals-bookings'),
                        90 => __('1.5 hours', 'wahra-rentals-bookings'),
                        120 => __('2 hours', 'wahra-rentals-bookings'),
                        180 => __('3 hours', 'wahra-rentals-bookings'),
                        240 => __('4 hours', 'wahra-rentals-bookings'),
                    ];
                    ?>
                    <div class="dokan-form-group">
                        <label for="_wahrb_slot_duration_minutes"><?php esc_html_e('Slot duration', 'wahra-rentals-bookings'); ?></label>
                        <select name="_wahrb_slot_duration_minutes" id="_wahrb_slot_duration_minutes" class="dokan-form-control" <?php echo esc_attr( !$can_customize_duration ? 'disabled' : '' ); ?>>
                            <?php foreach ($allowed_durations as $duration): ?>
                                <option value="<?php echo esc_attr($duration); ?>" <?php selected($slot_duration, $duration); ?>>
                                    <?php 
                                    /* translators: %d: duration in minutes */
                                    echo esc_html($duration_labels[$duration] ?? sprintf(__('%d minutes', 'wahra-rentals-bookings'), $duration)); 
                                    ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (!$can_customize_duration): ?>
                            <input type="hidden" name="_wahrb_slot_duration_minutes" value="<?php echo esc_attr($slot_duration); ?>">
                            <p class="description"><?php esc_html_e('Slot duration is set by administrator.', 'wahra-rentals-bookings'); ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_min_duration_hours"><?php esc_html_e('Minimum hours', 'wahra-rentals-bookings'); ?></label>
                            <input type="number" step="1" min="1" name="_wahrb_min_duration_hours" id="_wahrb_min_duration_hours" class="dokan-form-control" value="<?php echo esc_attr($min_hours); ?>">
                        </div>
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_max_duration_hours"><?php esc_html_e('Maximum hours', 'wahra-rentals-bookings'); ?></label>
                            <input type="number" step="1" min="1" name="_wahrb_max_duration_hours" id="_wahrb_max_duration_hours" class="dokan-form-control" value="<?php echo esc_attr($max_hours); ?>">
                        </div>
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_business_hours_start"><?php esc_html_e('Business hours start', 'wahra-rentals-bookings'); ?></label>
                            <input type="time" name="_wahrb_business_hours_start" id="_wahrb_business_hours_start" class="dokan-form-control" value="<?php echo esc_attr($business_hours['start'] ?? '09:00'); ?>" <?php echo !$can_customize_hours ? 'readonly' : ''; ?>>
                            <?php if (!$can_customize_hours): ?>
                                <p class="description"><?php esc_html_e('Business hours are set by administrator.', 'wahra-rentals-bookings'); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="dokan-w6">
                        <div class="dokan-form-group">
                            <label for="_wahrb_business_hours_end"><?php esc_html_e('Business hours end', 'wahra-rentals-bookings'); ?></label>
                            <input type="time" name="_wahrb_business_hours_end" id="_wahrb_business_hours_end" class="dokan-form-control" value="<?php echo esc_attr($business_hours['end'] ?? '18:00'); ?>" <?php echo !$can_customize_hours ? 'readonly' : ''; ?>>
                        </div>
                    </div>
                </div>

                <!-- SERVICE MODE FIELDS -->
                <div class="wahrb-service-fields" style="<?php echo esc_attr( $booking_mode !== 'service' ? 'display:none;' : '' ); ?>">
                    <?php
                    $can_customize_service_duration = WAHRB_Vendor_Permissions::can_customize_service_duration();
                    $can_customize_capacity = WAHRB_Vendor_Permissions::can_customize_capacity();
                    $allowed_service_durations = WAHRB_Vendor_Permissions::get_allowed_service_durations();
                    $max_capacity = WAHRB_Vendor_Permissions::get_max_capacity();
                    $service_duration_labels = [
                        15 => __('15 minutes', 'wahra-rentals-bookings'),
                        30 => __('30 minutes', 'wahra-rentals-bookings'),
                        45 => __('45 minutes', 'wahra-rentals-bookings'),
                        60 => __('1 hour', 'wahra-rentals-bookings'),
                        90 => __('1.5 hours', 'wahra-rentals-bookings'),
                        120 => __('2 hours', 'wahra-rentals-bookings'),
                    ];
                    ?>
                    <div class="dokan-form-group">
                        <label for="_wahrb_service_duration_minutes"><?php esc_html_e('Session duration', 'wahra-rentals-bookings'); ?></label>
                        <select name="_wahrb_service_duration_minutes" id="_wahrb_service_duration_minutes" class="dokan-form-control" <?php echo esc_attr( !$can_customize_service_duration ? 'disabled' : '' ); ?>>
                            <?php foreach ($allowed_service_durations as $duration): ?>
                                <option value="<?php echo esc_attr($duration); ?>" <?php selected($service_duration, $duration); ?>>
                                    <?php 
                                    /* translators: %d: duration in minutes */
                                    echo esc_html($service_duration_labels[$duration] ?? sprintf(__('%d minutes', 'wahra-rentals-bookings'), $duration)); 
                                    ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (!$can_customize_service_duration): ?>
                            <input type="hidden" name="_wahrb_service_duration_minutes" value="<?php echo esc_attr($service_duration); ?>">
                            <p class="description"><?php esc_html_e('Session duration is set by administrator.', 'wahra-rentals-bookings'); ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="dokan-form-group">
                        <label for="_wahrb_capacity_per_slot"><?php esc_html_e('Capacity per time slot', 'wahra-rentals-bookings'); ?></label>
                        <input type="number" step="1" min="1" max="<?php echo esc_attr($max_capacity); ?>" name="_wahrb_capacity_per_slot" id="_wahrb_capacity_per_slot" class="dokan-form-control" value="<?php echo esc_attr(min($capacity_per_slot, $max_capacity)); ?>" <?php echo esc_attr( !$can_customize_capacity ? 'readonly' : '' ); ?>>
                        <?php if ($can_customize_capacity): ?>
                            <?php /* translators: %d: maximum allowed capacity */ ?>
                            <p class="description"><?php printf(esc_html__('Maximum number of clients per time slot (max: %d)', 'wahra-rentals-bookings'), absint($max_capacity)); ?></p>
                        <?php else: ?>
                            <p class="description"><?php esc_html_e('Capacity is set by administrator.', 'wahra-rentals-bookings'); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php
            // ── Form Template selector ──
            $form_builder_settings = get_option('wahrb_settings_form_builder', ['enabled' => false]);
            if (!empty($form_builder_settings['enabled'])) {
                $form_builder = WAHRB_Form_Builder::instance();
                $all_templates = $form_builder->get_templates(['is_active' => true]);
                $current_template_id = (int) get_post_meta($post_id, '_wahrb_form_template_id', true);
                ?>
                <div class="dokan-form-group">
                    <label for="_wahrb_form_template_id"><?php esc_html_e('Customer form', 'wahra-rentals-bookings'); ?></label>
                    <select name="_wahrb_form_template_id" id="_wahrb_form_template_id" class="dokan-form-control">
                        <option value="0" <?php selected($current_template_id, 0); ?>><?php esc_html_e('Auto (cascade resolution)', 'wahra-rentals-bookings'); ?></option>
                        <option value="-1" <?php selected($current_template_id, -1); ?>><?php esc_html_e('None (no customer form)', 'wahra-rentals-bookings'); ?></option>
                        <?php foreach ($all_templates as $tpl): ?>
                            <option value="<?php echo esc_attr($tpl['id']); ?>" <?php selected($current_template_id, (int) $tpl['id']); ?>>
                                <?php echo esc_html(sprintf('%s [%s]', $tpl['name'], ucfirst($tpl['scope'] ?? 'global'))); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description"><?php esc_html_e('Select which form template customers must fill when booking this product. "Auto" uses the cascade resolution (product → vendor → category → global).', 'wahra-rentals-bookings'); ?></p>
                </div>
            <?php } ?>
        </div>

        <?php
        // Enqueue dedicated rental fields JS (vanilla JS, no jQuery dependency)
        wp_enqueue_script(
            'wahrb-rental-fields',
            WAHRB_PLUGIN_URL . 'assets/js/wahrb-rental-fields.js',
            [],
            WAHRB_VERSION,
            true
        );
    }

    /**
     * Save product rental fields
     *
     * @param int $post_id Product ID
     * @param array|null $data Form data (optional)
     */
    public function save_product_rental_fields(int $post_id, $data = null): void {
        // Verify this is a valid save
        if (!$post_id || !isset($_POST['_wahrb_rental_enabled']) && !isset($_POST['_wahrb_booking_mode'])) {
            return;
        }

        // Verify nonce
        if (!isset($_POST['_wahrb_rental_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wahrb_rental_nonce'])), 'wahrb_save_rental_fields')) {
            return;
        }

        // Verify user capabilities
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Day mode fields
        $fields = [
            '_wahrb_rental_enabled' => isset($_POST['_wahrb_rental_enabled']) ? 'yes' : 'no',
            '_wahrb_booking_mode' => isset($_POST['_wahrb_booking_mode']) ? sanitize_text_field(wp_unslash($_POST['_wahrb_booking_mode'])) : 'day',
            '_wahrb_base_price' => isset($_POST['_wahrb_base_price']) ? wc_format_decimal(sanitize_text_field(wp_unslash($_POST['_wahrb_base_price']))) : '',
            '_wahrb_security_deposit' => isset($_POST['_wahrb_security_deposit']) ? wc_format_decimal(sanitize_text_field(wp_unslash($_POST['_wahrb_security_deposit']))) : '',
            '_wahrb_total_units' => isset($_POST['_wahrb_total_units']) ? absint(wp_unslash($_POST['_wahrb_total_units'])) : 1,
            '_wahrb_min_duration' => isset($_POST['_wahrb_min_duration']) ? absint(wp_unslash($_POST['_wahrb_min_duration'])) : 1,
            '_wahrb_max_duration' => isset($_POST['_wahrb_max_duration']) ? absint(wp_unslash($_POST['_wahrb_max_duration'])) : 365,
            // Slot mode fields
            '_wahrb_slot_duration_minutes' => isset($_POST['_wahrb_slot_duration_minutes']) ? absint(wp_unslash($_POST['_wahrb_slot_duration_minutes'])) : 60,
            '_wahrb_min_duration_hours' => isset($_POST['_wahrb_min_duration_hours']) ? absint(wp_unslash($_POST['_wahrb_min_duration_hours'])) : 1,
            '_wahrb_max_duration_hours' => isset($_POST['_wahrb_max_duration_hours']) ? absint(wp_unslash($_POST['_wahrb_max_duration_hours'])) : 8,
            // Service mode fields
            '_wahrb_service_duration_minutes' => isset($_POST['_wahrb_service_duration_minutes']) ? absint(wp_unslash($_POST['_wahrb_service_duration_minutes'])) : 60,
            '_wahrb_capacity_per_slot' => isset($_POST['_wahrb_capacity_per_slot']) ? absint(wp_unslash($_POST['_wahrb_capacity_per_slot'])) : 1,
            // Form template
            '_wahrb_form_template_id' => isset($_POST['_wahrb_form_template_id']) ? intval(wp_unslash($_POST['_wahrb_form_template_id'])) : 0,
        ];
        
        // Handle business hours (slot mode)
        if (isset($_POST['_wahrb_business_hours_start']) && isset($_POST['_wahrb_business_hours_end'])) {
            $business_hours = [
                'start' => sanitize_text_field(wp_unslash($_POST['_wahrb_business_hours_start'])),
                'end' => sanitize_text_field(wp_unslash($_POST['_wahrb_business_hours_end'])),
            ];
            update_post_meta($post_id, '_wahrb_business_hours', $business_hours);
        }

        foreach ($fields as $key => $value) {
            update_post_meta($post_id, $key, $value);
        }
    }

    /**
     * Enqueue scripts on Dokan pages
     */
    public function enqueue_scripts(): void {
        // FontAwesome for icons (local vendor files)
        wp_enqueue_style(
            'fontawesome',
            WAHRB_PLUGIN_URL . 'assets/vendor/fontawesome/css/all.min.css',
            [],
            '6.7.2'
        );

        // Rental fields toggle script on product edit/create pages
        if (dokan_is_seller_dashboard()) {
            wp_enqueue_script(
                'wahrb-rental-fields',
                WAHRB_PLUGIN_URL . 'assets/js/wahrb-rental-fields.js',
                [],
                WAHRB_VERSION,
                true
            );
        }

        // Wizard styles on booking-wizard page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
        if (dokan_is_seller_dashboard() && isset($_GET['path']) && strpos(sanitize_text_field(wp_unslash($_GET['path'])), 'booking-wizard') !== false) {
            wp_enqueue_style(
                'wahrb-wizard-php',
                WAHRB_PLUGIN_URL . 'assets/css/wizard-php.css',
                [],
                WAHRB_VERSION
            );
        }

        // Also enqueue on direct page access
        global $wp;
        if (is_page() && isset($wp->query_vars['booking-wizard'])) {
            wp_enqueue_style(
                'wahrb-wizard-php',
                WAHRB_PLUGIN_URL . 'assets/css/wizard-php.css',
                [],
                WAHRB_VERSION
            );
        }
    }

    /**
     * Add dashboard widget showing booking stats
     */
    public function add_dashboard_widget(): void {
        if (!dokan_is_seller_dashboard()) {
            return;
        }

        // Ensure vendor stylesheet is available for the widget
        if (!wp_style_is('wahrb-vendor-styles', 'enqueued')) {
            wp_enqueue_style(
                'wahrb-vendor-styles',
                WAHRB_PLUGIN_URL . 'assets/css/wahrb-vendor.css',
                [],
                WAHRB_VERSION
            );
        }

        $vendor_id = get_current_user_id();
        $stats = $this->get_vendor_stats($vendor_id);
        $total_active = $stats['pending'] + $stats['confirmed'] + $stats['active'];
        ?>
        <div class="dokan-panel dokan-panel-default wahrb-dw">
            <div class="wahrb-dw-header">
                <div class="wahrb-dw-header-left">
                    <span class="wahrb-dw-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                    </span>
                    <strong><?php esc_html_e('Bookings', 'wahra-rentals-bookings'); ?></strong>
                </div>
                <?php if ($total_active > 0) : ?>
                    <span class="wahrb-dw-badge"><?php echo esc_html($total_active); ?></span>
                <?php endif; ?>
            </div>
            <div class="wahrb-dw-body">
                <div class="wahrb-dw-stats">
                    <div class="wahrb-dw-stat">
                        <span class="wahrb-dw-stat-num wahrb-dw-c-warn"><?php echo esc_html($stats['pending']); ?></span>
                        <span class="wahrb-dw-stat-lbl"><?php esc_html_e('Pending', 'wahra-rentals-bookings'); ?></span>
                    </div>
                    <div class="wahrb-dw-stat">
                        <span class="wahrb-dw-stat-num wahrb-dw-c-ok"><?php echo esc_html($stats['confirmed']); ?></span>
                        <span class="wahrb-dw-stat-lbl"><?php esc_html_e('Confirmed', 'wahra-rentals-bookings'); ?></span>
                    </div>
                    <div class="wahrb-dw-stat">
                        <span class="wahrb-dw-stat-num wahrb-dw-c-info"><?php echo esc_html($stats['active']); ?></span>
                        <span class="wahrb-dw-stat-lbl"><?php esc_html_e('In progress', 'wahra-rentals-bookings'); ?></span>
                    </div>
                    <div class="wahrb-dw-stat wahrb-dw-stat-rev">
                        <span class="wahrb-dw-stat-num wahrb-dw-c-prim"><?php echo wp_kses_post(wc_price($stats['revenue_month'])); ?></span>
                        <span class="wahrb-dw-stat-lbl"><?php esc_html_e('This month', 'wahra-rentals-bookings'); ?></span>
                    </div>
                </div>
                <div class="wahrb-dw-actions">
                    <a href="<?php echo esc_url(dokan_get_navigation_url('wahra-rentals-bookings')); ?>" class="wahrb-dw-btn wahrb-dw-btn-prim">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        <?php esc_html_e('View bookings', 'wahra-rentals-bookings'); ?>
                    </a>
                    <a href="<?php echo esc_url(dokan_get_navigation_url('booking-wizard')); ?>" class="wahrb-dw-btn wahrb-dw-btn-sec">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                        <?php esc_html_e('New item to rent', 'wahra-rentals-bookings'); ?>
                    </a>
                </div>
            </div>
        </div>
        <?php
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS only, no user data
        $widget_css = '
.wahrb-dw{border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.04);margin-bottom:20px}
.wahrb-dw-header{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid #f1f5f9;background:#fafbfc}
.wahrb-dw-header-left{display:flex;align-items:center;gap:8px;font-size:15px;color:#1e293b}
.wahrb-dw-icon{display:flex;color:#f05025}
.wahrb-dw-badge{background:#f05025;color:#fff;font-size:11px;font-weight:700;min-width:22px;height:22px;border-radius:11px;display:inline-flex;align-items:center;justify-content:center;padding:0 7px}
.wahrb-dw-body{padding:16px 18px}
.wahrb-dw-stats{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;margin-bottom:16px}
.wahrb-dw-stat{display:flex;align-items:center;gap:10px;padding:10px 12px;background:#f8fafc;border-radius:8px;border:1px solid #f1f5f9;transition:border-color .15s}
.wahrb-dw-stat:hover{border-color:#e2e8f0}
.wahrb-dw-stat-rev{grid-column:1/-1;background:linear-gradient(135deg,#fff7ed 0%,#fef3c7 100%);border-color:#fde68a}
.wahrb-dw-stat-num{font-size:22px;font-weight:700;line-height:1.1}
.wahrb-dw-stat-rev .wahrb-dw-stat-num{font-size:18px}
.wahrb-dw-stat-lbl{font-size:12px;color:#64748b;line-height:1.2}
.wahrb-dw-c-warn{color:#d97706}
.wahrb-dw-c-ok{color:#059669}
.wahrb-dw-c-info{color:#0284c7}
.wahrb-dw-c-prim{color:#f05025}
.wahrb-dw-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.wahrb-dw-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:9px 12px;font-size:13px;font-weight:600;border-radius:8px;text-decoration:none;transition:all .15s;cursor:pointer;border:none;text-align:center;line-height:1.3}
.wahrb-dw-btn-prim{background:#f05025;color:#fff}
.wahrb-dw-btn-prim:hover{background:#dc4520;color:#fff;text-decoration:none}
.wahrb-dw-btn-sec{background:#fff;color:#334155;border:1px solid #e2e8f0}
.wahrb-dw-btn-sec:hover{background:#f8fafc;border-color:#cbd5e1;color:#334155;text-decoration:none}
@media(max-width:480px){.wahrb-dw-stats{grid-template-columns:1fr 1fr}.wahrb-dw-actions{grid-template-columns:1fr}}
';
        wp_add_inline_style('wahrb-vendor-styles', wp_strip_all_tags($widget_css));
    }

    /**
     * Get vendor booking stats
     *
     * @param int $vendor_id Vendor ID
     * @return array Stats
     */
    private function get_vendor_stats(int $vendor_id): array {
        global $wpdb;
        $table = $wpdb->prefix . 'wahrb_bookings';

        // Check if table exists
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
            return [
                'pending' => 0,
                'confirmed' => 0,
                'active' => 0,
                'revenue_month' => 0,
            ];
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $pending = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE vendor_id = %d AND status = 'pending' AND deleted_at IS NULL",
            $vendor_id
        ));

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $confirmed = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE vendor_id = %d AND status = 'confirmed' AND deleted_at IS NULL",
            $vendor_id
        ));

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $active = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE vendor_id = %d AND status IN ('checked_in') AND deleted_at IS NULL",
            $vendor_id
        ));

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $revenue_month = $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(SUM(JSON_EXTRACT(pricing_snapshot, '$.total')), 0) FROM {$table}
             WHERE vendor_id = %d
             AND status IN ('confirmed', 'checked_in', 'checked_out', 'completed')
             AND MONTH(created_at) = MONTH(CURRENT_DATE())
             AND YEAR(created_at) = YEAR(CURRENT_DATE())
             AND deleted_at IS NULL",
            $vendor_id
        ));

        return [
            'pending' => (int) $pending,
            'confirmed' => (int) $confirmed,
            'active' => (int) $active,
            'revenue_month' => (float) $revenue_month,
        ];
    }

    /**
     * Filter rental products in product listing
     *
     * @param array $args Query args
     * @return array Modified args
     */
    public function filter_rental_products(array $args): array {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Filter parameter
        if (isset($_GET['wahrb_filter']) && sanitize_text_field(wp_unslash($_GET['wahrb_filter'])) === 'rental') {
            $args['meta_query'][] = [
                'key' => '_wahrb_rental_enabled',
                'value' => 'yes',
            ];
        }

        return $args;
    }
}
