<?php
if (!defined('ABSPATH')) {
    exit;
}

class VS_Admin_Settings
{

    const OPTION_KEY = 'vs_settings';

    public static function init()
    {
        add_action('admin_post_vs_save_settings', [__CLASS__, 'save_settings']);
        add_action('wp_ajax_vs_save_settings', [__CLASS__, 'save_settings_ajax']);
    }

    public static function get_tabs()
    {
        return [
            'general' => ['label' => __('General', 'vendor-space'), 'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z'],
            'vendors' => ['label' => __('Vendors', 'vendor-space'), 'icon' => 'M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z'],
            'products' => ['label' => __('Products', 'vendor-space'), 'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4'],
            'commission' => ['label' => __('Commissions', 'vendor-space'), 'icon' => 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z'],
            'wallet' => ['label' => __('Wallet', 'vendor-space'), 'icon' => 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z'],
        ];
    }

    public static function get_default_settings()
    {
        return [
            'general' => [
                'marketplace_name' => get_option('blogname', get_bloginfo('name')),
                'marketplace_email' => get_option('admin_email', ''),
                'timezone_string' => get_option('timezone_string', 'UTC'),
                'site_language' => get_locale(),
                'currency' => 'DZD',
                'currency_position' => 'right',
            ],
            'vendors' => [
                'manual_vendor_approval' => 'yes',
                'allow_store_logo' => 'yes',
                'allow_store_banner' => 'yes',
                'vendor_can_create_coupons' => 'yes',
                'vendor_can_manage_taxes' => 'no',
                'vendor_can_chat_customers' => 'no',
                'vendor_can_export_csv' => 'yes',
                'vendor_can_import_csv' => 'yes',
            ],
            'products' => [
                'require_product_approval' => 'yes',
                'default_product_status' => 'pending',
                'allow_simple_products' => 'yes',
                'allow_variable_products' => 'yes',
                'allow_digital_products' => 'yes',
                'allow_product_video' => 'yes',
                'allow_product_faqs' => 'yes',
                'enable_sku' => 'yes',
                'auto_generate_sku' => 'no',
                'max_gallery_images' => 8,
            ],
            
            'commission' => [
                'commission_type' => 'percentage',
                'commission_value' => 10,
            ],
            'wallet' => [
                'enable_wallet' => 'yes',
                'enable_withdrawals' => 'yes',
                'min_withdrawal' => 50,
                'max_withdrawal' => 10000,
                'withdrawal_fee_type' => 'none',
                'withdrawal_fee_value' => 0,
                'withdrawal_approval' => 'yes',
            ],
            
           
           
        ];
    }

    public static function get_settings()
    {
        $saved = get_option(self::OPTION_KEY, []);
        $defaults = self::get_default_settings();
        if (!is_array($saved))
            $saved = [];
        return wp_parse_args($saved, $defaults);
    }

    public static function get_option($section, $key, $default = '')
    {
        $settings = self::get_settings();
        return $settings[$section][$key] ?? $default;
    }

    /**
     * Get commission rate as a float percentage.
     * Reads from woocommerce_vs_commission_rate in wp_options — the single source of truth
     * shared by VS_Admin_Settings, VS_Commission, and VS_Wallet.
     * Falls back to vs_settings value if the WooCommerce option hasn't been written yet.
     */
    public static function get_commission_rate()
    {
        $wc_rate = get_option('woocommerce_vs_commission_rate', null);
        if ($wc_rate !== null) {
            return (float) $wc_rate;
        }
        // First-run fallback: read from vs_settings and sync immediately
        $rate = (float) self::get_option('commission', 'commission_value', 10);
        update_option('woocommerce_vs_commission_rate', $rate);
        return $rate;
    }

    /**
     * Get commission type: 'percentage' | 'fixed' | 'hybrid'
     * Reads from woocommerce_vs_commission_type in wp_options — the single source of truth.
     */
    public static function get_commission_type()
    {
        $wc_type = get_option('woocommerce_vs_commission_type', null);
        if ($wc_type !== null) {
            return (string) $wc_type;
        }
        // First-run fallback
        $type = self::get_option('commission', 'commission_type', 'percentage');
        update_option('woocommerce_vs_commission_type', $type);
        return $type;
    }

    public static function update_option($section, $key, $value)
    {
        $settings = self::get_settings();
        if (!isset($settings[$section]) || !is_array($settings[$section])) {
            $settings[$section] = [];
        }
        $settings[$section][$key] = $value;
        update_option(self::OPTION_KEY, $settings);
    }

    public static function save_settings()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have permission to perform this action.', 'vendor-space'));
        }
        check_admin_referer('vs_save_settings_nonce');
        $saved = get_option(self::OPTION_KEY, []);
        if (!is_array($saved))
            $saved = [];
        $posted_settings = isset($_POST['vs_settings']) ? wp_unslash($_POST['vs_settings']) : [];
        if (is_array($posted_settings)) {
            foreach ($posted_settings as $tab => $tab_data) {
                $tab = sanitize_key($tab);
                if (!is_array($tab_data))
                    continue;
                $sanitized = self::sanitize_settings($tab, $tab_data);
                if (!isset($saved[$tab]) || !is_array($saved[$tab]))
                    $saved[$tab] = [];
                $saved[$tab] = array_merge($saved[$tab], $sanitized);
                self::sync_wp_core($tab, $sanitized);
            }
        }
        update_option(self::OPTION_KEY, $saved);
        $redirect = add_query_arg('vs_settings_saved', '1', wp_get_referer() ?: admin_url());
        wp_safe_redirect($redirect);
        exit;
    }

    public static function save_settings_ajax()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'vendor-space')]);
        }
        check_ajax_referer('vs_settings_ajax_nonce', 'nonce');
        $settings = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : [];
        $tab = isset($_POST['tab']) ? sanitize_key($_POST['tab']) : '';
        if (empty($tab) || !is_array($settings)) {
            wp_send_json_error(['message' => __('Invalid settings data.', 'vendor-space')]);
        }
        if (!in_array($tab, array_keys(self::get_tabs()), true)) {
            wp_send_json_error(['message' => __('Invalid tab.', 'vendor-space')]);
        }
        $saved = get_option(self::OPTION_KEY, []);
        if (!is_array($saved))
            $saved = [];
        $sanitized = self::sanitize_settings($tab, $settings);
        if (!isset($saved[$tab]) || !is_array($saved[$tab]))
            $saved[$tab] = [];
        $saved[$tab] = array_merge($saved[$tab], $sanitized);
        self::sync_wp_core($tab, $sanitized);
        update_option(self::OPTION_KEY, $saved);
        wp_send_json_success(['message' => __('Settings saved successfully.', 'vendor-space')]);
    }

    private static function sync_wp_core($tab, $sanitized)
    {
        if ($tab === 'general') {
            if (isset($sanitized['marketplace_name']))
                update_option('blogname', $sanitized['marketplace_name']);
            if (isset($sanitized['marketplace_email']))
                update_option('admin_email', $sanitized['marketplace_email']);
            if (isset($sanitized['timezone_string'])) {
                update_option('timezone_string', $sanitized['timezone_string']);
                update_option('gmt_offset', 0);
            }
            if (isset($sanitized['site_language']))
                update_option('WPLANG', $sanitized['site_language']);
        }

        // Sync commission — write to woocommerce_vs_commission_rate (single source of truth)
        if ($tab === 'commission') {
            $value = isset($sanitized['commission_value']) ? (float) $sanitized['commission_value'] : self::get_commission_rate();
            $type  = isset($sanitized['commission_type'])  ? $sanitized['commission_type']           : self::get_commission_type();

            // ── Single source of truth in wp_options ──────────────────────────────
            update_option('woocommerce_vs_commission_rate', $value);
            update_option('woocommerce_vs_commission_type', $type);
            // Fixed-fee companion used by hybrid mode
            update_option('woocommerce_vs_commission_fixed', $type === 'hybrid' ? $value : 0);
        }
    }

    public static function sanitize_settings($tab, $data)
    {
        $clean = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $clean[sanitize_key($key)] = array_map('sanitize_text_field', $value);
                continue;
            }
            $key = sanitize_key($key);
            switch ($key) {
                case 'marketplace_email':
                    $clean[$key] = sanitize_email($value);
                    break;
                case 'commission_value':
                case 'min_withdrawal':
                case 'max_withdrawal':
                case 'withdrawal_fee_value':
                case 'max_login_attempts':
                case 'session_timeout':
                case 'max_gallery_images':
                case 'hold_days':
                    $clean[$key] = is_numeric($value) ? $value + 0 : 0;
                    break;
                case 'timezone_string':
                    $clean[$key] = in_array($value, timezone_identifiers_list(), true) ? $value : 'UTC';
                    break;
                case 'stripe_public_key':
                case 'stripe_secret_key':
                    $clean[$key] = trim(sanitize_text_field($value));
                    break;
                default:
                    $clean[$key] = sanitize_text_field($value);
                    break;
            }
        }
        return $clean;
    }

    public static function render_front_settings_tab()
    {
        if (!current_user_can('manage_options')) {
            return '<div class="vs-alert vs-alert-error">' . esc_html__('Access denied.', 'vendor-space') . '</div>';
        }
        ob_start();
        echo '<div class="vs-tab" id="tab-admin-settings" style="display:none;">';
        self::render(true);
        echo '</div>';
        return ob_get_clean();
    }

    /* =========================================================
       RENDER – main entry point
    ========================================================= */
    public static function render($is_frontend = false)
    {
        if (!current_user_can('manage_options')) {
            echo '<div class="vs-alert vs-alert-error">' . esc_html__('Access denied.', 'vendor-space') . '</div>';
            return;
        }
        $tabs = self::get_tabs();
        $settings = self::get_settings();
        $ajax_nonce = wp_create_nonce('vs_settings_ajax_nonce');
        ?>
        <div class="vss-wrap" id="vs-settings-app" data-ajax-url="<?php echo esc_url(admin_url('admin-ajax.php')); ?>"
            data-nonce="<?php echo esc_attr($ajax_nonce); ?>">

            <style>
                /* ── Reset & base ───────────────────────────────── */
                .vss-wrap * {
                    box-sizing: border-box;
                    margin: 0;
                    padding: 0
                }

                .vss-wrap {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    color: #0f172a;
                    padding: 24px 0
                }

                /* ── Layout ─────────────────────────────────────── */
                .vss-layout {
                    display: flex;
                    gap: 24px;
                    align-items: flex-start
                }

                .vss-sidebar {
                    width: 220px;
                    flex-shrink: 0;
                    position: sticky;
                    top: 32px
                }

                .vss-content {
                    flex: 1;
                    min-width: 0
                }

                /* ── Sidebar nav ────────────────────────────────── */
                .vss-nav {
                    background: #fff;
                    border: 1px solid #e8edf3;
                    border-radius: 14px;
                    padding: 10px;
                    box-shadow: 0 4px 12px rgba(15, 23, 42, .05);
                }

                /* Item */
                .vss-nav-item {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    padding: 10px 14px;
                    border-radius: 10px;
                    text-decoration: none;
                    color: #475569;
                    font-size: 13.5px;
                    font-weight: 500;
                    border: none;
                    background: #fff;
                    width: 100%;
                    cursor: pointer;
                    transition: all .2s ease;
                    margin-bottom: 4px;
                    position: relative;
                }

                /* Icon */
                .vss-nav-item svg {
                    width: 15px;
                    height: 15px;
                    flex-shrink: 0;
                    stroke: currentColor;
                    fill: none;
                    stroke-width: 1.7;
                    stroke-linecap: round;
                    stroke-linejoin: round;
                    transition: all .2s ease;
                }

                /* Hover */
                .vss-nav-item:hover {
                    background: #f1f5f9;
                    color: #0f172a;
                    transform: translateX(3px);
                }

                /* 🔥 Active */
                .vss-nav-item.active {
                    background: linear-gradient(135deg, #3b82f6 0%, #000 100%);
                    color: #fff;
                    box-shadow: 0 6px 16px rgba(37, 99, 235, .35);
                }

                /* Icon active */
                .vss-nav-item.active svg {
                    stroke: #fff;
                }

                /* ✨ خط جانبي (indicator) */
                .vss-nav-item.active::before {
                    content: "";
                    position: absolute;
                    left: -10px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 4px;
                    height: 60%;
                    background: #2563eb;
                    border-radius: 4px;
                }

                /* 🔥 Focus (accessibility) */
                .vss-nav-item:focus {
                    outline: none;
                    box-shadow: 0 0 0 2px rgba(59, 130, 246, .3);
                }

                /* ── Panel card ─────────────────────────────────── */
                .vss-panel {
                    display: none
                }

                .vss-panel.active {
                    display: block
                }

                .vss-card {
                    background: #fff;
                    border: 1px solid #e8edf3;
                    border-radius: 14px;
                    box-shadow: 0 1px 4px rgba(15, 23, 42, .06);
                    overflow: hidden;
                    margin-bottom: 16px
                }

                .vss-card-head {
                    padding: 18px 22px;
                    border-bottom: 1px solid #f1f5f9;
                    display: flex;
                    align-items: center;
                    gap: 12px
                }

                .vss-card-icon {
                    width: 36px;
                    height: 36px;
                    border-radius: 9px;
                    background: #eff6ff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex-shrink: 0
                }

                .vss-card-icon svg {
                    width: 16px;
                    height: 16px;
                    stroke: #2563eb;
                    fill: none;
                    stroke-width: 1.8;
                    stroke-linecap: round;
                    stroke-linejoin: round
                }

                .vss-card-title {
                    font-size: 15px;
                    font-weight: 600;
                    color: #0f172a
                }

                .vss-card-desc {
                    font-size: 12.5px;
                    color: #94a3b8;
                    margin-top: 2px
                }

                .vss-card-body {
                    padding: 0
                }

                /* ── Field row ──────────────────────────────────── */
                .vss-field {
                    display: flex;
                    align-items: center;
                    padding: 14px 22px;
                    border-bottom: 1px solid #f8fafc;
                    gap: 16px;
                    transition: background .12s
                }

                .vss-field:last-child {
                    border-bottom: none
                }

                .vss-field:hover {
                    background: #fafbfc
                }

                .vss-field-label {
                    flex: 0 0 240px;
                    display: flex;
                    flex-direction: column;
                    gap: 3px
                }

                .vss-field-label strong {
                    font-size: 13.5px;
                    font-weight: 500;
                    color: #1e293b
                }

                .vss-field-label span {
                    font-size: 12px;
                    color: #94a3b8
                }

                .vss-field-control {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    justify-content: flex-end
                }

                /* ── Text / number input ────────────────────────── */
                .vss-input {
                    height: 36px;
                    padding: 0 12px;
                    border: 1.5px solid #e2e8f0;
                    border-radius: 8px;
                    font-size: 13.5px;
                    color: #1e293b;
                    background: #fff;
                    transition: border-color .15s, box-shadow .15s;
                    width: 200px
                }

                .vss-input:focus {
                    outline: none;
                    border-color: #3b82f6;
                    box-shadow: 0 0 0 3px rgba(59, 130, 246, .12)
                }

                .vss-input[type=number] {
                    width: 110px
                }

                .vss-input-wide {
                    width: 280px
                }

                /* ── Select ─────────────────────────────────────── */
                .vss-select {
                    height: 36px;
                    padding: 0 32px 0 12px;
                    border: 1.5px solid #e2e8f0;
                    border-radius: 8px;
                    font-size: 13.5px;
                    color: #1e293b;
                    background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='%2394a3b8' d='M4.5 6l3.5 4 3.5-4'/%3E%3C/svg%3E") no-repeat right 10px center;
                    background-size: 16px;
                    -webkit-appearance: none;
                    appearance: none;
                    cursor: pointer;
                    transition: border-color .15s, box-shadow .15s;
                    width: 200px
                }

                .vss-select:focus {
                    outline: none;
                    border-color: #3b82f6;
                    box-shadow: 0 0 0 3px rgba(59, 130, 246, .12)
                }

                .vss-select-wide {
                    width: 280px
                }

                /* ── Toggle switch ──────────────────────────────── */
                .vss-toggle {
                    position: relative;
                    display: inline-flex;
                    align-items: center;
                    cursor: pointer;
                    gap: 8px
                }

                .vss-toggle input {
                    opacity: 0;
                    width: 0;
                    height: 0;
                    position: absolute
                }

                .vss-toggle-track {
                    width: 42px;
                    height: 24px;
                    background: #e2e8f0;
                    border-radius: 100px;
                    transition: background .2s;
                    position: relative;
                    flex-shrink: 0
                }

                .vss-toggle-thumb {
                    position: absolute;
                    top: 3px;
                    left: 3px;
                    width: 18px;
                    height: 18px;
                    background: #fff;
                    border-radius: 50%;
                    box-shadow: 0 1px 4px rgba(0, 0, 0, .18);
                    transition: left .2s, box-shadow .2s
                }

                .vss-toggle input:checked+.vss-toggle-track {
                    background: #2563eb
                }

                .vss-toggle input:checked+.vss-toggle-track .vss-toggle-thumb {
                    left: 21px;
                    box-shadow: 0 1px 4px rgba(37, 99, 235, .35)
                }

                .vss-toggle-label {
                    font-size: 13px;
                    color: #64748b;
                    font-weight: 500;
                    min-width: 28px
                }

                /* ── Badge-group (Yes/No pill select) ───────────── */
                .vss-pill-group {
                    display: inline-flex;
                    border: 1.5px solid #e2e8f0;
                    border-radius: 8px;
                    overflow: hidden
                }

                .vss-pill-group label {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    padding: 5px 14px;
                    font-size: 13px;
                    font-weight: 500;
                    cursor: pointer;
                    color: #64748b;
                    background: #fff;
                    transition: background .15s, color .15s;
                    line-height: 1
                }

                .vss-pill-group label:not(:last-child) {
                    border-right: 1.5px solid #e2e8f0
                }

                .vss-pill-group input {
                    display: none
                }

                .vss-pill-group input:checked+span {
                    background: #2563eb;
                    color: #fff
                }

                .vss-pill-group label:has(input:checked) {
                    background: #2563eb;
                    color: #fff
                }

                /* ── Save button ────────────────────────────────── */
                .vss-actions {
                    padding: 16px 22px;
                    background: #f8fafc;
                    border-top: 1px solid #f1f5f9;
                    display: flex;
                    align-items: center;
                    gap: 14px;
                    border-radius: 0 0 14px 14px
                }

                .vss-save-btn {
                    display: inline-flex;
                    align-items: center;
                    gap: 7px;
                    height: 38px;
                    padding: 0 20px;
                    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
                    color: #fff;
                    border: none;
                    border-radius: 9px;
                    font-size: 13.5px;
                    font-weight: 600;
                    cursor: pointer;
                    box-shadow: 0 2px 8px rgba(37, 99, 235, .28);
                    transition: opacity .15s, transform .12s
                }

                .vss-save-btn:hover {
                    opacity: .92
                }

                .vss-save-btn:active {
                    transform: scale(.98)
                }

                .vss-save-btn:disabled {
                    opacity: .55;
                    cursor: not-allowed;
                    transform: none
                }

                .vss-save-btn svg {
                    width: 14px;
                    height: 14px;
                    stroke: #fff;
                    fill: none;
                    stroke-width: 2.2;
                    stroke-linecap: round;
                    stroke-linejoin: round
                }

                .vss-status {
                    font-size: 13px
                }

                .vss-status.saving {
                    color: #64748b
                }

                .vss-status.success {
                    color: #16a34a;
                    font-weight: 600
                }

                .vss-status.error {
                    color: #dc2626;
                    font-weight: 600
                }

                /* ── Section divider ────────────────────────────── */
                .vss-section-label {
                    padding: 10px 22px 6px;
                    font-size: 11px;
                    font-weight: 600;
                    letter-spacing: .06em;
                    color: #94a3b8;
                    text-transform: uppercase;
                    background: #fafbfc;
                    border-bottom: 1px solid #f1f5f9
                }

                /* ── Number badge (for numeric fields in cards) ─── */
                .vss-num-badge {
                    display: inline-flex;
                    align-items: center;
                    gap: 4px;
                    background: #f1f5f9;
                    border: 1.5px solid #e2e8f0;
                    border-radius: 8px;
                    padding: 3px 6px
                }

                .vss-num-badge button {
                    width: 24px;
                    height: 24px;
                    border: none;
                    background: #fff;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 15px;
                    color: #64748b;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    box-shadow: 0 1px 3px rgba(0, 0, 0, .08);
                    transition: background .12s
                }

                .vss-num-badge button:hover {
                    background: #eff6ff;
                    color: #2563eb
                }

                .vss-num-badge input {
                    width: 54px;
                    text-align: center;
                    border: none;
                    background: transparent;
                    font-size: 13.5px;
                    font-weight: 600;
                    color: #0f172a
                }

                .vss-num-badge input:focus {
                    outline: none
                }

                /* ── Payment method cards ───────────────────────── */
                .vss-method-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
                    gap: 10px;
                    padding: 16px 22px
                }

                .vss-method-card {
                    border: 2px solid #e2e8f0;
                    border-radius: 11px;
                    padding: 14px;
                    cursor: pointer;
                    transition: border-color .15s, background .15s;
                    background: #fff;
                    position: relative
                }

                .vss-method-card:has(input:checked) {
                    border-color: #3b82f6;
                    background: #eff6ff
                }

                .vss-method-card input {
                    position: absolute;
                    opacity: 0;
                    width: 0;
                    height: 0
                }

                .vss-method-card-icon {
                    font-size: 22px;
                    margin-bottom: 8px
                }

                .vss-method-card-name {
                    font-size: 13px;
                    font-weight: 600;
                    color: #1e293b
                }

                .vss-method-card-sub {
                    font-size: 11.5px;
                    color: #94a3b8;
                    margin-top: 2px
                }

                .vss-method-check {
                    position: absolute;
                    top: 9px;
                    right: 9px;
                    width: 18px;
                    height: 18px;
                    border-radius: 50%;
                    background: #e2e8f0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: background .15s
                }

                .vss-method-card:has(input:checked) .vss-method-check {
                    background: #2563eb
                }

                .vss-method-check::after {
                    content: '';
                    width: 5px;
                    height: 8px;
                    border: 2px solid #fff;
                    border-top: none;
                    border-left: none;
                    transform: rotate(45deg);
                    display: block;
                    margin-top: -2px
                }

                /* ── Commission type selector ───────────────────── */
                .vss-type-grid {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    gap: 10px;
                    padding: 16px 22px
                }

                .vss-type-card {
                    border: 2px solid #e2e8f0;
                    border-radius: 11px;
                    padding: 12px 14px;
                    cursor: pointer;
                    transition: border-color .15s, background .15s;
                    position: relative
                }

                .vss-type-card:has(input:checked) {
                    border-color: #3b82f6;
                    background: #eff6ff
                }

                .vss-type-card input {
                    position: absolute;
                    opacity: 0;
                    width: 0;
                    height: 0
                }

                .vss-type-card-name {
                    font-size: 13px;
                    font-weight: 600;
                    color: #1e293b;
                    margin-bottom: 2px
                }

                .vss-type-card-desc {
                    font-size: 11.5px;
                    color: #94a3b8
                }

                /* ── Responsive ─────────────────────────────────── */
                @media(max-width:900px) {
                    .vss-layout {
                        flex-direction: column
                    }

                    .vss-sidebar {
                        width: 100%;
                        position: static
                    }

                    .vss-nav {
                        display: flex;
                        gap: 4px;
                        overflow-x: auto;
                        padding: 6px;
                        flex-wrap: nowrap;
                        scrollbar-width: thin
                    }

                    .vss-nav-item {
                        flex-shrink: 0;
                        padding: 8px 12px;
                        font-size: 12.5px;
                        margin-bottom: 0
                    }

                    .vss-nav-item span {
                        white-space: nowrap
                    }

                    .vss-field {
                        flex-direction: column;
                        align-items: flex-start
                    }

                    .vss-field-label {
                        flex: none
                    }

                    .vss-field-control {
                        justify-content: flex-start
                    }
                }

                @media(max-width:560px) {
                    .vss-field {
                        padding: 12px 14px
                    }

                    .vss-card-head {
                        padding: 14px 14px
                    }

                    .vss-actions {
                        padding: 12px 14px
                    }

                    .vss-section-label {
                        padding: 8px 14px 4px
                    }

                    .vss-method-grid {
                        grid-template-columns: repeat(2, 1fr);
                        padding: 12px 14px
                    }

                    .vss-type-grid {
                        grid-template-columns: 1fr;
                        padding: 12px 14px
                    }
                }
            </style>

            <div class="vss-layout">

                <!-- Sidebar -->
                <div class="vss-sidebar">
                    <nav class="vss-nav">
                        <?php foreach ($tabs as $key => $tab): ?>
                            <button class="vss-nav-item" data-tab="<?php echo esc_attr($key); ?>" type="button">
                                <svg viewBox="0 0 24 24">
                                    <path d="<?php echo esc_attr($tab['icon']); ?>" />
                                </svg>
                                <span><?php echo esc_html($tab['label']); ?></span>
                            </button>
                        <?php endforeach; ?>
                    </nav>
                </div>

                <!-- Panels -->
                <div class="vss-content">
                    <?php foreach ($tabs as $tab_key => $tab_data): ?>
                        <div class="vss-panel" id="vss-panel-<?php echo esc_attr($tab_key); ?>">
                            <form class="vss-form" data-tab="<?php echo esc_attr($tab_key); ?>" method="post"
                                action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                                <input type="hidden" name="action" value="vs_save_settings">
                                <?php wp_nonce_field('vs_save_settings_nonce'); ?>

                                <?php
                                switch ($tab_key) {
                                    case 'general':
                                        self::render_general_tab($settings);
                                        break;
                                    case 'vendors':
                                        self::render_vendors_tab($settings);
                                        break;
                                    case 'products':
                                        self::render_products_tab($settings);
                                        break;
                                 
                                    case 'commission':
                                        self::render_commission_tab($settings);
                                        break;
                                    case 'wallet':
                                        self::render_wallet_tab($settings);
                                        break;
                                   
                                    
                                  
                                 
                                }
                                ?>

                                <div class="vss-actions">
                                    <button type="submit" class="vss-save-btn">
                                        <svg viewBox="0 0 24 24">
                                            <path d="M5 13l4 4L19 7" />
                                        </svg>
                                        <?php esc_html_e('Save Settings', 'vendor-space'); ?>
                                    </button>
                                    <span class="vss-status" aria-live="polite"></span>
                                </div>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div><!-- .vss-content -->

            </div><!-- .vss-layout -->

            <script>
                (function () {
                    const app = document.getElementById('vs-settings-app');
                    if (!app) return;
                    const ajaxUrl = app.dataset.ajaxUrl;
                    const nonce = app.dataset.nonce;
                    const btns = app.querySelectorAll('.vss-nav-item');
                    const panels = app.querySelectorAll('.vss-panel');

                    function activate(name, pushHash) {
                        btns.forEach(b => b.classList.toggle('active', b.dataset.tab === name));
                        panels.forEach(p => p.classList.toggle('active', p.id === 'vss-panel-' + name));
                        if (pushHash) history.replaceState(null, '', '#' + name);
                    }

                    btns.forEach(b => b.addEventListener('click', () => activate(b.dataset.tab, true)));

                    const hash = location.hash.slice(1);
                    activate((hash && app.querySelector('#vss-panel-' + hash)) ? hash : 'general', false);

                    window.addEventListener('hashchange', () => {
                        const h = location.hash.slice(1);
                        if (app.querySelector('#vss-panel-' + h)) activate(h, false);
                    });

                    /* AJAX save */
                    app.querySelectorAll('.vss-form').forEach(form => {
                        form.addEventListener('submit', function (e) {
                            e.preventDefault();
                            const tab = form.dataset.tab;
                            const status = form.querySelector('.vss-status');
                            const btn = form.querySelector('.vss-save-btn');

                            status.className = 'vss-status saving';
                            status.textContent = '<?php echo esc_js(__('Saving…', 'vendor-space')); ?>';
                            btn.disabled = true;

                            const body = new FormData();
                            body.append('action', 'vs_save_settings');
                            body.append('nonce', nonce);
                            body.append('tab', tab);

                            /* Collect all named inputs in this form */
                            const fd = new FormData(form);
                            for (const [k, v] of fd.entries()) {
                                const m = k.match(/^vs_settings\[[^\]]+\]\[([^\]]+)\]$/);
                                if (m) body.append('settings[' + m[1] + ']', v);
                            }

                            fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body })
                                .then(r => r.json())
                                .then(d => {
                                    if (d && d.success) {
                                        status.className = 'vss-status success';
                                        status.textContent = d.data?.message || '<?php echo esc_js(__('Saved!', 'vendor-space')); ?>';
                                    } else {
                                        status.className = 'vss-status error';
                                        status.textContent = d?.data?.message || '<?php echo esc_js(__('Failed to save.', 'vendor-space')); ?>';
                                    }
                                })
                                .catch(() => { status.className = 'vss-status error'; status.textContent = '<?php echo esc_js(__('Error occurred.', 'vendor-space')); ?>'; })
                                .finally(() => { btn.disabled = false; setTimeout(() => { status.textContent = ''; status.className = 'vss-status'; }, 4000); });
                        });
                    });

                    /* Stepper buttons */
                    app.querySelectorAll('.vss-num-badge').forEach(badge => {
                        const input = badge.querySelector('input');
                        badge.querySelector('[data-action=dec]')?.addEventListener('click', () => { input.value = Math.max(0, +input.value - 1); });
                        badge.querySelector('[data-action=inc]')?.addEventListener('click', () => { input.value = +input.value + 1; });
                    });
                })();
            </script>
        </div>
        <?php
    }

    /* =========================================================
       HELPERS
    ========================================================= */

    /** Toggle switch (yes/no stored as string) */
    private static function field_toggle($name, $value, $label, $desc = '')
    {
        $checked = ($value === 'yes' || $value === true || $value === 1);
        ?>
        <div class="vss-field">
            <div class="vss-field-label">
                <strong><?php echo esc_html($label); ?></strong>
                <?php if ($desc): ?><span><?php echo esc_html($desc); ?></span><?php endif; ?>
            </div>
            <div class="vss-field-control">
                <label class="vss-toggle">
                    <input type="hidden" name="<?php echo esc_attr($name); ?>" value="no">
                    <input type="checkbox" name="<?php echo esc_attr($name); ?>" value="yes" <?php checked($checked); ?>
                        onchange="this.previousElementSibling.value = this.checked ? 'yes' : 'no'">
                    <div class="vss-toggle-track">
                        <div class="vss-toggle-thumb"></div>
                    </div>
                </label>
            </div>
        </div>
        <?php
    }

    /** Text / email / number input */
    private static function field_text($name, $value, $label, $type = 'text', $desc = '', $wide = false)
    {
        if ($type === 'number') {
            ?>
            <div class="vss-field">
                <div class="vss-field-label">
                    <strong><?php echo esc_html($label); ?></strong>
                    <?php if ($desc): ?><span><?php echo esc_html($desc); ?></span><?php endif; ?>
                </div>
                <div class="vss-field-control">
                    <div class="vss-num-badge">
                        <button type="button" data-action="dec">&#8722;</button>
                        <input type="number" name="<?php echo esc_attr($name); ?>" value="<?php echo esc_attr($value); ?>" min="0">
                        <button type="button" data-action="inc">&#43;</button>
                    </div>
                </div>
            </div>
            <?php
        } else {
            ?>
            <div class="vss-field">
                <div class="vss-field-label">
                    <strong><?php echo esc_html($label); ?></strong>
                    <?php if ($desc): ?><span><?php echo esc_html($desc); ?></span><?php endif; ?>
                </div>
                <div class="vss-field-control">
                    <input type="<?php echo esc_attr($type); ?>" name="<?php echo esc_attr($name); ?>"
                        value="<?php echo esc_attr($value); ?>" class="vss-input<?php echo $wide ? ' vss-input-wide' : ''; ?>">
                </div>
            </div>
            <?php
        }
    }

    /** Select dropdown */
    private static function field_select($name, $value, $label, $options = [], $desc = '', $wide = false)
    {
        ?>
        <div class="vss-field">
            <div class="vss-field-label">
                <strong><?php echo esc_html($label); ?></strong>
                <?php if ($desc): ?><span><?php echo esc_html($desc); ?></span><?php endif; ?>
            </div>
            <div class="vss-field-control">
                <select name="<?php echo esc_attr($name); ?>" class="vss-select<?php echo $wide ? ' vss-select-wide' : ''; ?>">
                    <?php foreach ($options as $k => $v): ?>
                        <option value="<?php echo esc_attr($k); ?>" <?php selected($value, $k); ?>>
                            <?php echo esc_html($v); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <?php
    }

    /** Card wrapper open */
    private static function card_open($title, $desc = '', $icon_path = '')
    {
        if (!$icon_path) {
            $icon_path = 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z';
        }
        echo '<div class="vss-card"><div class="vss-card-head">';
        echo '<div class="vss-card-icon"><svg viewBox="0 0 24 24"><path d="' . esc_attr($icon_path) . '"/></svg></div>';
        echo '<div><div class="vss-card-title">' . esc_html($title) . '</div>';
        if ($desc)
            echo '<div class="vss-card-desc">' . esc_html($desc) . '</div>';
        echo '</div></div><div class="vss-card-body">';
    }

    private static function card_close()
    {
        echo '</div></div>';
    }

    private static function section_label($text)
    {
        echo '<div class="vss-section-label">' . esc_html($text) . '</div>';
    }

    /* =========================================================
       TAB RENDERERS
    ========================================================= */

    public static function render_general_tab($settings)
    {
        $g = $settings['general'];
        $timezones = timezone_identifiers_list();
        $languages = [
            'en_US' => __('English (United States)', 'vendor-space'),
            'fr_FR' => __('French (France)', 'vendor-space'),
            'ar' => __('Arabic', 'vendor-space'),
        ];
        $currencies = function_exists('get_woocommerce_currencies') ? get_woocommerce_currencies() : [
            'DZD' => __('Algerian Dinar', 'vendor-space'),
            'USD' => __('US Dollar', 'vendor-space'),
            'EUR' => __('Euro', 'vendor-space'),
        ];
        $currency_opts = [];
        foreach ($currencies as $code => $name)
            $currency_opts[$code] = "$name ($code)";

        self::card_open(__('Site Identity', 'vendor-space'), __('Basic WordPress site configuration.', 'vendor-space'), 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6');
        self::field_text('vs_settings[general][marketplace_name]', $g['marketplace_name'], __('Site Title', 'vendor-space'), 'text', __('Synced with WordPress blogname'), true);
        self::field_text('vs_settings[general][marketplace_email]', $g['marketplace_email'], __('Admin Email', 'vendor-space'), 'email', __('Synced with WordPress admin_email'), true);
        self::field_select('vs_settings[general][timezone_string]', $g['timezone_string'], __('Timezone', 'vendor-space'), array_combine($timezones, $timezones), '', true);
        self::field_select('vs_settings[general][site_language]', $g['site_language'], __('Site Language', 'vendor-space'), $languages);
        self::card_close();

        self::card_open(__('Currency', 'vendor-space'), __('Marketplace currency settings.', 'vendor-space'), 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z');
        self::field_select('vs_settings[general][currency]', $g['currency'], __('Currency', 'vendor-space'), $currency_opts, '', true);

        self::card_close();
    }

    public static function render_vendors_tab($settings)
    {
        $v = $settings['vendors'];

        self::card_open(__('Vendor Onboarding', 'vendor-space'), __('Registration and approval settings.', 'vendor-space'), 'M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z');
        self::field_toggle('vs_settings[vendors][manual_vendor_approval]', $v['manual_vendor_approval'], __('Manual Approval', 'vendor-space'), __('Require admin approval before vendors go live'));
        self::card_close();

        self::card_open(__('Vendor Capabilities', 'vendor-space'), __('What vendors are allowed to do.', 'vendor-space'), 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z');


    if ( class_exists('VS_Modules') && VS_Modules::is_active('export_import') ) {

    self::field_toggle(
        'vs_settings[vendors][vendor_can_export_csv]',
        $v['vendor_can_export_csv'],
        __('Export Files as CSV', 'vendor-space')
    );

    self::field_toggle(
        'vs_settings[vendors][vendor_can_import_csv]',
        $v['vendor_can_import_csv'],
        __('Import Files via CSV', 'vendor-space')
    );

    }
    self::card_close();
    }

    public static function render_products_tab($settings)
    {
        $p = $settings['products'];

        self::card_open(__('Product Approval', 'vendor-space'), __('Review and publish rules.', 'vendor-space'), 'M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z');
        self::field_toggle('vs_settings[products][require_product_approval]', $p['require_product_approval'], __('Require Approval', 'vendor-space'), __('New products need admin review before going live'));
       
        self::field_text('vs_settings[products][max_gallery_images]', $p['max_gallery_images'], __('Max Gallery Images', 'vendor-space'), 'number', __('Per product listing'));
        self::card_close();

        self::card_open(__('Allowed Product Types', 'vendor-space'), __('Which product types vendors can create.', 'vendor-space'), 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4');
        self::field_toggle('vs_settings[products][allow_simple_products]', $p['allow_simple_products'], __('Simple Products', 'vendor-space'));
        self::field_toggle('vs_settings[products][allow_variable_products]', $p['allow_variable_products'], __('Variable Products', 'vendor-space'));
        self::field_toggle('vs_settings[products][allow_digital_products]', $p['allow_digital_products'], __('Digital / Downloadable', 'vendor-space'));


        self::card_close();

        self::card_open(__('SKU Settings', 'vendor-space'), '', 'M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z');
        self::field_toggle('vs_settings[products][enable_sku]', $p['enable_sku'], __('Enable SKU', 'vendor-space'));
        self::field_toggle('vs_settings[products][auto_generate_sku]', $p['auto_generate_sku'], __('Auto-Generate SKU', 'vendor-space'), __('Automatically create SKU if vendor leaves it blank'));
        self::card_close();
    }

   
    public static function render_commission_tab($settings)
    {
        $c = $settings['commission'];

        self::card_open(__('Commission Structure', 'vendor-space'), __('How the marketplace earns.', 'vendor-space'), 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z');
        ?>
        <div class="vss-type-grid">
            <?php
            $types = [
                'percentage' => [__('Percentage', 'vendor-space'), __('e.g. 10% per sale', 'vendor-space')],
                'fixed' => [__('Fixed Amount', 'vendor-space'), __('e.g. 5 DZD flat', 'vendor-space')],
                'hybrid' => [__('Hybrid', 'vendor-space'), __('% + fixed combined', 'vendor-space')],
            ];
            foreach ($types as $k => $labels): ?>
                <label class="vss-type-card">
                    <input type="radio" name="vs_settings[commission][commission_type]" value="<?php echo esc_attr($k); ?>" <?php checked($c['commission_type'], $k); ?>>
                    <div class="vss-type-card-name"><?php echo esc_html($labels[0]); ?></div>
                    <div class="vss-type-card-desc"><?php echo esc_html($labels[1]); ?></div>
                </label>
            <?php endforeach; ?>
        </div>
        <?php
        self::field_text('vs_settings[commission][commission_value]', $c['commission_value'], __('Commission Value', 'vendor-space'), 'number', __('% or fixed amount depending on type above'));
        self::card_close();
    }

    public static function render_wallet_tab($settings)
    {
        $w = $settings['wallet'];
        self::card_open(__('Wallet & Withdrawals', 'vendor-space'), __('Vendor balance and payout controls.', 'vendor-space'), 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z');
        self::field_toggle('vs_settings[wallet][enable_wallet]', $w['enable_wallet'], __('Enable Wallet', 'vendor-space'));
        self::field_toggle('vs_settings[wallet][enable_withdrawals]', $w['enable_withdrawals'], __('Enable Withdrawals', 'vendor-space'));
        self::field_toggle('vs_settings[wallet][withdrawal_approval]', $w['withdrawal_approval'], __('Require Withdrawal Approval', 'vendor-space'));
        self::field_text('vs_settings[wallet][min_withdrawal]', $w['min_withdrawal'], __('Minimum Withdrawal', 'vendor-space'), 'number', __('Minimum amount a vendor can request'));
        self::field_text('vs_settings[wallet][max_withdrawal]', $w['max_withdrawal'], __('Maximum Withdrawal', 'vendor-space'), 'number', __('Per request cap, 0 = no limit'));
        self::field_select('vs_settings[wallet][withdrawal_fee_type]', $w['withdrawal_fee_type'], __('Fee Type', 'vendor-space'), [
            'none' => __('No Fee', 'vendor-space'),
            'percentage' => __('Percentage (%)', 'vendor-space'),
            'fixed' => __('Fixed Amount', 'vendor-space'),
        ]);
        self::field_text('vs_settings[wallet][withdrawal_fee_value]', $w['withdrawal_fee_value'], __('Fee Value', 'vendor-space'), 'number');
        self::card_close();
    }

   

  
   

   

   
}