<?php
/**
 * MenuX Free — Import / Export
 * @package MenuX
 */

if ( ! defined( 'ABSPATH' ) ) exit;

/* ─────────────────────────────────────────────────────────────────────────────
 * EXPORT
 * ───────────────────────────────────────────────────────────────────────────*/

add_action( 'wp_ajax_menux_export_config', 'menux_ajax_export_config' );
function menux_ajax_export_config() {
	if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
	check_ajax_referer( 'menux_export_config_nonce', 'nonce' );

	$config = array(
		'version'          => '9.0',
		'menu_items'       => get_option( 'menux_menu_items', array() ),
		'style'            => get_option( 'menux_style', array() ),
		'logo'             => get_option( 'menux_logo', array() ),
		'accessibility'    => get_option( Menux_Accessibility::OPTION_KEY, array() ),
		'wp_nav_replacements' => get_option( 'menux_wp_nav_replacements', array() ),
		'footer'           => get_option( 'menux_footer', array() ),
		'footer_style'     => get_option( 'menux_footer_style', array() ),
	);

	wp_send_json_success( $config );
}

/* ─────────────────────────────────────────────────────────────────────────────
 * IMPORT
 * ───────────────────────────────────────────────────────────────────────────*/

add_action( 'wp_ajax_menux_import_config', 'menux_ajax_import_config' );
function menux_ajax_import_config() {
	if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
	check_ajax_referer( 'menux_import_config_nonce', 'nonce' );

	$raw = isset( $_POST['config'] ) ? base64_decode( wp_unslash( $_POST['config'] ) ) : '';
	if ( empty( $raw ) ) {
		wp_send_json_error( 'No data received.' );
	}

	$config = json_decode( $raw, true );
	if ( ! is_array( $config ) ) {
		wp_send_json_error( 'Invalid JSON file.' );
	}

	/* ── menu_items ── */
	if ( isset( $config['menu_items'] ) && is_array( $config['menu_items'] ) ) {
		$valid_vis = array_merge(
			array( 'all', 'logged_in', 'logged_out', 'auth', 'non-auth' ),
			array_keys( wp_roles()->roles )
		);

		$sanitized = array();
		foreach ( $config['menu_items'] as $item ) {
			if ( ! is_array( $item ) ) continue;
			$s = menux_import_sanitize_item( $item, $valid_vis );
			if ( $s !== null ) {
				$sanitized[] = $s;
			}
		}
		update_option( 'menux_menu_items', $sanitized );
	}

	/* ── style ── */
	if ( isset( $config['style'] ) && is_array( $config['style'] ) ) {
		update_option( 'menux_style', menux_import_sanitize_style( $config['style'] ) );
		delete_transient( 'menux_gfont_loaded' );
	}

	/* ── logo ── */
	if ( isset( $config['logo'] ) && is_array( $config['logo'] ) && class_exists( 'Menux_Logo' ) ) {
		Menux_Logo::save( $config['logo'] );
	}

	/* ── accessibility ── */
	if ( isset( $config['accessibility'] ) && is_array( $config['accessibility'] ) && class_exists( 'Menux_Accessibility' ) ) {
		Menux_Accessibility::save( $config['accessibility'] );
	}

	/* ── WP Nav Integration ── */
	if ( isset( $config['wp_nav_replacements'] ) && is_array( $config['wp_nav_replacements'] ) ) {
		$saved = array();
		foreach ( $config['wp_nav_replacements'] as $theme_loc => $menux_loc ) {
			$theme_loc = sanitize_key( $theme_loc );
			$menux_loc = sanitize_key( $menux_loc );
			if ( $theme_loc && $menux_loc ) {
				$saved[ $theme_loc ] = $menux_loc;
			}
		}
		update_option( 'menux_wp_nav_replacements', $saved );
	}

	/* ── footer (content + style) ── */
	if ( isset( $config['footer'] ) && is_array( $config['footer'] ) && function_exists( 'menux_footer_sanitize_content' ) ) {
		update_option( 'menux_footer', menux_footer_sanitize_content( $config['footer'] ) );
	}
	if ( isset( $config['footer_style'] ) && is_array( $config['footer_style'] ) && function_exists( 'menux_footer_sanitize_style' ) ) {
		update_option( 'menux_footer_style', menux_footer_sanitize_style( $config['footer_style'] ) );
	}

	wp_send_json_success( array(
		'message'     => 'Configuration imported successfully.',
		'items_count' => count( get_option( 'menux_menu_items', array() ) ),
	) );
}

/* ─────────────────────────────────────────────────────────────────────────────
 * Sanitisation helpers (import)
 * ───────────────────────────────────────────────────────────────────────────*/

/**
 * Sanitises one menu item from import data.
 *
 * @param array $item      Raw item from imported JSON.
 * @param array $valid_vis Allowed visibility values.
 * @return array|null Sanitised item, or null to skip.
 */
function menux_import_sanitize_item( array $item, array $valid_vis ) {
	$type = sanitize_text_field( $item['type'] ?? '' );
	if ( ! in_array( $type, array( 'page', 'custom' ), true ) ) {
		return null;
	}

	$vis = sanitize_text_field( $item['visibility'] ?? 'all' );
	if ( ! in_array( $vis, $valid_vis, true ) ) {
		$vis = 'all';
	}

	$s = array(
		'type'            => $type,
		'icon'            => sanitize_text_field( $item['icon']            ?? '' ),
		'visibility'      => $vis,
		'item_key'        => sanitize_key( $item['item_key']               ?? '' ),
		'target'          => in_array( $item['target'] ?? '', array( '', '_blank' ), true ) ? ( $item['target'] ?? '' ) : '',
		'badge'           => sanitize_text_field( $item['badge']           ?? '' ),
		'badge_bg'        => ! empty( $item['badge_bg'] )    ? ( sanitize_hex_color( $item['badge_bg'] )    ?: '' ) : '',
		'badge_color'     => ! empty( $item['badge_color'] ) ? ( sanitize_hex_color( $item['badge_color'] ) ?: '' ) : '',
		'notif_dot'       => ( ( $item['notif_dot'] ?? '0' ) === '1' ) ? '1' : '0',
		'menu_location'   => sanitize_key( $item['menu_location'] ?? 'primary' ),
		// Scheduling & conditions
		'schedule_start'  => sanitize_text_field( $item['schedule_start']  ?? '' ),
		'schedule_end'    => sanitize_text_field( $item['schedule_end']    ?? '' ),
		'cond_roles'      => sanitize_text_field( $item['cond_roles']      ?? '' ),
		'cond_devices'    => sanitize_text_field( $item['cond_devices']    ?? '' ),
		'cond_pages'      => sanitize_text_field( $item['cond_pages']      ?? '' ),
		'cond_time_from'  => sanitize_text_field( $item['cond_time_from']  ?? '' ),
		'cond_time_to'    => sanitize_text_field( $item['cond_time_to']    ?? '' ),
		'cond_utm'        => sanitize_text_field( $item['cond_utm']        ?? '' ),
		// Mega menu — mega_columns / mega_style already decoded arrays in DB; re-sanitise via JSON round-trip
		'mega_menu'       => ( ( $item['mega_menu'] ?? '0' ) === '1' ) ? '1' : '0',
		'mega_full_width' => ( ( $item['mega_full_width'] ?? '1' ) !== '0' ) ? '1' : '0',
		'mega_columns'    => class_exists( 'Menux_MegaMenu' )
			? Menux_MegaMenu::sanitize_columns( wp_json_encode( $item['mega_columns'] ?? array() ) )
			: array(),
		'mega_style'      => class_exists( 'Menux_MegaMenu' )
			? Menux_MegaMenu::sanitize_style( wp_json_encode( $item['mega_style'] ?? array() ) )
			: array(),
		// Children (submenus)
		'children'        => array(),
	);

	// Language labels
	foreach ( $item as $k => $v ) {
		if ( preg_match( '/^lang_[a-zA-Z0-9_]+$/', $k ) ) {
			$s[ $k ] = sanitize_text_field( $v );
		}
	}

	if ( $type === 'page' ) {
		$s['id'] = absint( $item['id'] ?? 0 );
		if ( empty( $s['item_key'] ) ) {
			$s['item_key'] = 'page_' . $s['id'];
		}
	} else {
		$s['url'] = esc_url_raw( $item['url'] ?? '' );
		if ( empty( $s['url'] ) ) {
			return null;
		}
		if ( empty( $s['item_key'] ) ) {
			$s['item_key'] = 'custom_' . md5( $s['url'] );
		}
	}

	// Children — up to 3 levels deep, same structure (no mega on children)
	if ( ! empty( $item['children'] ) && is_array( $item['children'] ) ) {
		foreach ( $item['children'] as $child ) {
			if ( ! is_array( $child ) ) continue;
			$ch = menux_import_sanitize_child( $child );
			if ( $ch !== null ) {
				$s['children'][] = $ch;
			}
		}
	}

	return $s;
}

/**
 * Sanitises a child (submenu) item from import data.
 *
 * @param array $child Raw child item.
 * @return array|null Sanitised child, or null to skip.
 */
function menux_import_sanitize_child( array $child ) {
	$type = sanitize_text_field( $child['type'] ?? 'custom' );
	if ( ! in_array( $type, array( 'page', 'custom' ), true ) ) {
		$type = 'custom';
	}

	$ch = array(
		'type'     => $type,
		'icon'     => sanitize_text_field( $child['icon']   ?? '' ),
		'target'   => in_array( $child['target'] ?? '', array( '', '_blank' ), true ) ? ( $child['target'] ?? '' ) : '',
		'children' => array(),
	);

	foreach ( $child as $k => $v ) {
		if ( preg_match( '/^lang_[a-zA-Z0-9_]+$/', $k ) ) {
			$ch[ $k ] = sanitize_text_field( $v );
		}
	}

	if ( $type === 'page' ) {
		$ch['id'] = absint( $child['id'] ?? 0 );
	} else {
		$ch['url'] = esc_url_raw( $child['url'] ?? '' );
		if ( empty( $ch['url'] ) ) {
			return null;
		}
	}

	// Third level (grandchildren) — no recursion beyond this
	if ( ! empty( $child['children'] ) && is_array( $child['children'] ) ) {
		foreach ( $child['children'] as $gc ) {
			if ( ! is_array( $gc ) ) continue;
			$gch = array(
				'type'   => in_array( $gc['type'] ?? 'custom', array( 'page', 'custom' ), true ) ? sanitize_text_field( $gc['type'] ) : 'custom',
				'icon'   => sanitize_text_field( $gc['icon']   ?? '' ),
				'target' => in_array( $gc['target'] ?? '', array( '', '_blank' ), true ) ? ( $gc['target'] ?? '' ) : '',
			);
			foreach ( $gc as $k => $v ) {
				if ( preg_match( '/^lang_[a-zA-Z0-9_]+$/', $k ) ) {
					$gch[ $k ] = sanitize_text_field( $v );
				}
			}
			if ( $gch['type'] === 'page' ) {
				$gch['id'] = absint( $gc['id'] ?? 0 );
			} else {
				$gch['url'] = esc_url_raw( $gc['url'] ?? '' );
				if ( empty( $gch['url'] ) ) continue;
			}
			$ch['children'][] = $gch;
		}
	}

	return $ch;
}

/**
 * Sanitises the style array from import data, mirroring the full set of keys
 * saved by admin-page.php so nothing is silently dropped on import.
 *
 * @param array $rs Raw style array from imported JSON.
 * @return array Sanitised style array.
 */
function menux_import_sanitize_style( array $rs ) {
	$ss = array();

	/* — Solid colours — */
	$color_keys = array(
		'container_bg', 'container_border',
		'link_color', 'link_hover_color', 'link_hover_bg',
		'link_active_color', 'link_active_border', 'link_active_bg',
		'hamburger_color', 'hamburger_bg', 'sticky_bg',
		'submenu_bg', 'submenu_border', 'submenu_link_color',
		'last_item_color', 'last_item_hover_color', 'last_item_bg',
		'close_btn_color', 'close_btn_bg',
		'mobile_link_color', 'mobile_link_hover_color', 'mobile_link_active_color',
		'mobile_overlay_bg',
		'mega_bg', 'mega_link_color', 'mega_heading_color', 'mega_accent_color',
		'mega_link_hover_color', 'mega_desc_color', 'mega_divider_color',
		'search_icon_color',
	);
	foreach ( $color_keys as $k ) {
		$ss[ $k ] = ! empty( $rs[ $k ] ) ? ( sanitize_hex_color( $rs[ $k ] ) ?: '' ) : '';
	}

	/* — Gradients (CSS strings — strip tags + CSS injection chars) — */
	foreach ( array( 'container_bg_gradient', 'link_hover_bg_gradient', 'link_active_bg_gradient', 'mega_bg_gradient' ) as $k ) {
		$ss[ $k ] = isset( $rs[ $k ] ) ? str_replace( array( ';', '{', '}' ), '', wp_strip_all_tags( $rs[ $k ] ) ) : '';
	}

	/* — Typography — */
	$ss['font_size']              = isset( $rs['font_size'] )              && $rs['font_size'] !== ''              ? intval( $rs['font_size'] )                    : '';
	$ss['font_weight']            = isset( $rs['font_weight'] )            && $rs['font_weight'] !== ''            ? sanitize_text_field( $rs['font_weight'] )     : '';
	$ss['google_font']            = isset( $rs['google_font'] )                                                    ? sanitize_text_field( $rs['google_font'] )     : '';
	$ss['font_family']            = isset( $rs['font_family'] )                                                    ? sanitize_text_field( $rs['font_family'] )     : '';
	$ss['letter_spacing']         = isset( $rs['letter_spacing'] )         && is_numeric( $rs['letter_spacing'] ) ? floatval( $rs['letter_spacing'] )             : '';
	$ss['text_transform']         = in_array( $rs['text_transform']         ?? 'none', array( 'none', 'uppercase', 'lowercase', 'capitalize' ), true ) ? $rs['text_transform']         : 'none';
	$ss['link_transition']        = isset( $rs['link_transition'] )        && is_numeric( $rs['link_transition'] ) ? floatval( $rs['link_transition'] )           : '0.3';
	$ss['link_active_font_weight']= isset( $rs['link_active_font_weight'] )                                        ? sanitize_text_field( $rs['link_active_font_weight'] ) : '';

	/* — Spacing / Layout — */
	$ss['gap']                    = isset( $rs['gap'] )                    && $rs['gap'] !== ''                    ? intval( $rs['gap'] )                          : '20';
	$ss['padding_x']              = isset( $rs['padding_x'] )              && $rs['padding_x'] !== ''              ? intval( $rs['padding_x'] )                   : '0';
	$ss['padding_y']              = isset( $rs['padding_y'] )              && $rs['padding_y'] !== ''              ? intval( $rs['padding_y'] )                   : '0';
	$ss['link_border_radius']     = isset( $rs['link_border_radius'] )     && $rs['link_border_radius'] !== ''     ? intval( $rs['link_border_radius'] )          : '';
	$ss['container_border_radius']= isset( $rs['container_border_radius'] ) && $rs['container_border_radius'] !== '' ? intval( $rs['container_border_radius'] )   : '';
	$ss['nav_justify']            = in_array( $rs['nav_justify']            ?? 'flex-end', array( 'flex-start', 'center', 'flex-end', 'space-between', 'space-evenly' ), true ) ? $rs['nav_justify']  : 'flex-end';
	$ss['push_last_item']         = isset( $rs['push_last_item'] )         ? ( $rs['push_last_item'] === '1' ? '1' : '0' ) : '0';

	/* — Animations — */
	$ss['link_animation']         = in_array( $rs['link_animation']     ?? 'none', array( 'none', 'pulse', 'shake', 'bounce', 'glow', 'lift', 'scale', 'underline' ), true ) ? $rs['link_animation']   : 'none';
	$ss['entrance_animation']     = in_array( $rs['entrance_animation'] ?? 'none', array( 'none', 'fadeIn', 'slideDown', 'slideUp', 'slideLeft', 'slideRight', 'zoomIn', 'flipX' ), true ) ? $rs['entrance_animation'] : 'none';
	$ss['entrance_duration']      = isset( $rs['entrance_duration'] ) && is_numeric( $rs['entrance_duration'] ) ? round( floatval( $rs['entrance_duration'] ), 2 ) : '0.5';
	$ss['entrance_delay']         = isset( $rs['entrance_delay'] )    && is_numeric( $rs['entrance_delay'] )    ? round( floatval( $rs['entrance_delay'] ),    2 ) : '0';
	$ss['entrance_stagger']       = isset( $rs['entrance_stagger'] )  && is_numeric( $rs['entrance_stagger'] )  ? round( floatval( $rs['entrance_stagger'] ),  3 ) : '0';

	/* — Mobile — */
	$ss['mobile_breakpoint']      = isset( $rs['mobile_breakpoint'] )      && $rs['mobile_breakpoint'] !== ''      ? intval( $rs['mobile_breakpoint'] )           : '768';
	$ss['mobile_breakpoint_mode'] = in_array( $rs['mobile_breakpoint_mode'] ?? 'manual', array( 'manual', 'auto' ), true ) ? $rs['mobile_breakpoint_mode']        : 'manual';
	$ss['hamburger_style']        = isset( $rs['hamburger_style'] )                                                ? sanitize_text_field( $rs['hamburger_style'] ) : 'classic';
	$ss['hamburger_align']        = isset( $rs['hamburger_align'] )                                                ? sanitize_text_field( $rs['hamburger_align'] ) : 'flex-end';
	$ss['mobile_menu_pad']        = isset( $rs['mobile_menu_pad'] )                                                ? intval( $rs['mobile_menu_pad'] )             : '0';
	$ss['mobile_menu_shadow']     = isset( $rs['mobile_menu_shadow'] )    ? ( $rs['mobile_menu_shadow'] === '1' ? '1' : '0' ) : '0';
	$ss['mobile_open_style']      = in_array( $rs['mobile_open_style']     ?? 'dropdown', array( 'dropdown', 'fullscreen', 'drawer-left', 'drawer-right' ), true ) ? $rs['mobile_open_style']  : 'dropdown';
	$ss['mobile_overlay_opacity'] = isset( $rs['mobile_overlay_opacity'] ) && is_numeric( $rs['mobile_overlay_opacity'] ) ? min( 1, max( 0, floatval( $rs['mobile_overlay_opacity'] ) ) ) : '0.9';
	$ss['mobile_overlay_blur']    = isset( $rs['mobile_overlay_blur'] )                                            ? intval( $rs['mobile_overlay_blur'] )         : '0';
	$ss['mobile_fullscreen_align']= in_array( $rs['mobile_fullscreen_align'] ?? 'center', array( 'center', 'flex-start', 'flex-end' ), true ) ? $rs['mobile_fullscreen_align'] : 'center';
	$ss['mobile_drawer_width']    = isset( $rs['mobile_drawer_width'] )                                            ? intval( $rs['mobile_drawer_width'] )         : '280';
	$ss['mobile_open_animation']  = in_array( $rs['mobile_open_animation']  ?? 'fade',   array( 'fade', 'slide', 'scale' ), true ) ? $rs['mobile_open_animation'] : 'fade';
	$ss['mobile_accordion']       = isset( $rs['mobile_accordion'] ) ? ( $rs['mobile_accordion'] === '1' ? '1' : '0' ) : '0';

	/* — Sticky — */
	$ss['sticky']                 = isset( $rs['sticky'] )              ? ( $rs['sticky']        === '1' ? '1' : '0' ) : '0';
	$ss['sticky_mirror']          = isset( $rs['sticky_mirror'] )       ? ( $rs['sticky_mirror'] === '1' ? '1' : '0' ) : '0';
	$ss['sticky_shadow']          = isset( $rs['sticky_shadow'] )       ? ( $rs['sticky_shadow'] === '1' ? '1' : '0' ) : '0';
	$ss['sticky_z_index']         = isset( $rs['sticky_z_index'] )                                                    ? intval( $rs['sticky_z_index'] )            : '9999';
	$ss['sticky_justify']         = in_array( $rs['sticky_justify']      ?? 'flex-start', array( 'flex-start', 'center', 'flex-end', 'space-between' ), true ) ? $rs['sticky_justify']    : 'flex-start';
	$ss['sticky_align_items']     = in_array( $rs['sticky_align_items']  ?? 'center',     array( 'flex-start', 'center', 'flex-end' ),                   true ) ? $rs['sticky_align_items'] : 'center';
	$ss['sticky_padding_x']       = isset( $rs['sticky_padding_x'] )    && $rs['sticky_padding_x'] !== '' ? intval( $rs['sticky_padding_x'] ) : '';
	$ss['sticky_padding_y']       = isset( $rs['sticky_padding_y'] )    && $rs['sticky_padding_y'] !== '' ? intval( $rs['sticky_padding_y'] ) : '';
	$ss['sticky_transition']      = isset( $rs['sticky_transition'] )   && is_numeric( $rs['sticky_transition'] ) ? max( 0, min( 2, round( floatval( $rs['sticky_transition'] ), 2 ) ) ) : '0.3';
	$ss['sticky_shrink']          = isset( $rs['sticky_shrink'] )       ? ( $rs['sticky_shrink'] === '1' ? '1' : '0' ) : '0';

	/* — Scroll progress bar — */
	$ss['progress_bar_enabled']   = isset( $rs['progress_bar_enabled'] ) ? ( $rs['progress_bar_enabled'] === '1' ? '1' : '0' ) : '0';
	$ss['progress_bar_color']     = ! empty( $rs['progress_bar_color'] ) ? ( sanitize_hex_color( $rs['progress_bar_color'] ) ?: '#667eea' ) : '#667eea';
	$ss['progress_bar_height']    = isset( $rs['progress_bar_height'] )  && $rs['progress_bar_height'] !== '' ? max( 1, min( 10, intval( $rs['progress_bar_height'] ) ) ) : '3';
	$ss['progress_bar_position']  = in_array( $rs['progress_bar_position'] ?? 'bottom', array( 'bottom', 'top' ), true ) ? ( $rs['progress_bar_position'] ?? 'bottom' ) : 'bottom';
	$ss['scroll_spy']             = isset( $rs['scroll_spy'] ) ? ( $rs['scroll_spy'] === '1' ? '1' : '0' ) : '0';
	$ss['scroll_spy_offset']      = isset( $rs['scroll_spy_offset'] ) && is_numeric( $rs['scroll_spy_offset'] ) ? max( 0, min( 500, intval( $rs['scroll_spy_offset'] ) ) ) : 80;
	$ss['scroll_spy_smooth']      = isset( $rs['scroll_spy_smooth'] ) ? ( $rs['scroll_spy_smooth'] === '1' ? '1' : '0' ) : '1';

	/* — Dark mode — */
	$ss['dark_mode']              = in_array( $rs['dark_mode'] ?? 'light', array( 'light', 'dark', 'auto' ), true ) ? $rs['dark_mode'] : 'light';

	/* — Dropdown indicator — */
	$ss['dropdown_indicator']        = in_array( $rs['dropdown_indicator'] ?? 'triangle', array( 'triangle', 'chevron', 'dot', 'none' ), true ) ? $rs['dropdown_indicator'] : 'triangle';
	$ss['dropdown_indicator_color']  = ! empty( $rs['dropdown_indicator_color'] ) ? ( sanitize_hex_color( $rs['dropdown_indicator_color'] ) ?: '' ) : '';
	$ss['dropdown_indicator_size']   = isset( $rs['dropdown_indicator_size'] ) && is_numeric( $rs['dropdown_indicator_size'] ) ? max( 6, min( 24, intval( $rs['dropdown_indicator_size'] ) ) ) : 10;
	$ss['dropdown_indicator_rotate'] = isset( $rs['dropdown_indicator_rotate'] ) ? ( $rs['dropdown_indicator_rotate'] === '1' ? '1' : '0' ) : '1';

	/* — Submenu — */
	$ss['submenu_shadow']         = isset( $rs['submenu_shadow'] )    ? ( $rs['submenu_shadow']    === '1' ? '1' : '0' ) : '0';
	$ss['submenu_animation']      = in_array( $rs['submenu_animation'] ?? 'fade', array( 'fade', 'slide', 'none' ), true ) ? $rs['submenu_animation'] : 'fade';

	/* — Mega Menu appearance — */
	$ss['mega_padding_y']         = isset( $rs['mega_padding_y'] )    && is_numeric( $rs['mega_padding_y'] )    ? intval( $rs['mega_padding_y'] )    : 24;
	$ss['mega_padding_x']         = isset( $rs['mega_padding_x'] )    && is_numeric( $rs['mega_padding_x'] )    ? intval( $rs['mega_padding_x'] )    : 32;
	$ss['mega_max_width']         = isset( $rs['mega_max_width'] )    && is_numeric( $rs['mega_max_width'] )    ? intval( $rs['mega_max_width'] )    : 0;
	$ss['mega_col_gap']           = isset( $rs['mega_col_gap'] )      && is_numeric( $rs['mega_col_gap'] )      ? intval( $rs['mega_col_gap'] )      : 16;
	$ss['mega_border_radius']     = isset( $rs['mega_border_radius'] ) && is_numeric( $rs['mega_border_radius'] ) ? intval( $rs['mega_border_radius'] ) : 14;
	$ss['mega_font_size']         = isset( $rs['mega_font_size'] )    && is_numeric( $rs['mega_font_size'] )    ? intval( $rs['mega_font_size'] )    : 0;
	$ss['mega_mobile_disable']    = isset( $rs['mega_mobile_disable'] ) ? ( $rs['mega_mobile_disable'] === '1' ? '1' : '0' ) : '0';
	$ss['mega_mobile_layout']     = in_array( $rs['mega_mobile_layout'] ?? '', array( 'list', 'grid2', 'hide' ), true ) ? $rs['mega_mobile_layout'] : '';
	$ss['mega_divider_style']     = in_array( $rs['mega_divider_style'] ?? 'solid', array( 'solid', 'dashed', 'dotted' ), true ) ? ( $rs['mega_divider_style'] ?? 'solid' ) : 'solid';
	$ss['mega_open_duration']     = isset( $rs['mega_open_duration'] ) && is_numeric( $rs['mega_open_duration'] ) ? max( 0, min( 800, (int) $rs['mega_open_duration'] ) ) : 200;

	/* — Search — */
	$ss['search_enabled']         = isset( $rs['search_enabled'] )  ? ( $rs['search_enabled']  === '1' ? '1' : '0' ) : '0';
	$ss['search_position']        = in_array( $rs['search_position'] ?? 'right', array( 'left', 'right' ), true ) ? $rs['search_position'] : 'right';
	$ss['search_icon_color']      = ! empty( $rs['search_icon_color'] ) ? ( sanitize_hex_color( $rs['search_icon_color'] ) ?: '' ) : '';

	/* — WooCommerce cart — */
	$ss['woo_cart_enabled']    = isset( $rs['woo_cart_enabled'] )    ? ( $rs['woo_cart_enabled']    === '1' ? '1' : '0' ) : '0';
	$ss['woo_cart_position']   = in_array( $rs['woo_cart_position'] ?? 'right', array( 'left', 'right' ), true )            ? $rs['woo_cart_position'] : 'right';
	$ss['woo_cart_icon']       = in_array( $rs['woo_cart_icon']     ?? 'cart',  array( 'cart', 'bag', 'basket' ), true )    ? $rs['woo_cart_icon']     : 'cart';
	$ss['woo_cart_show_count'] = isset( $rs['woo_cart_show_count'] ) ? ( $rs['woo_cart_show_count'] === '1' ? '1' : '0' ) : '0';
	$ss['woo_cart_show_total'] = isset( $rs['woo_cart_show_total'] ) ? ( $rs['woo_cart_show_total'] === '1' ? '1' : '0' ) : '0';
	$ss['woo_cart_minicart']   = in_array( $rs['woo_cart_minicart'] ?? 'hover', array( 'hover', 'click', 'off' ), true )    ? $rs['woo_cart_minicart'] : 'hover';
	$ss['woo_cart_hide_empty'] = isset( $rs['woo_cart_hide_empty'] ) ? ( $rs['woo_cart_hide_empty'] === '1' ? '1' : '0' ) : '0';
	$ss['woo_cart_icon_color'] = ! empty( $rs['woo_cart_icon_color'] ) ? ( sanitize_hex_color( $rs['woo_cart_icon_color'] ) ?: '' ) : '';
	$ss['woo_cart_badge_bg']   = ! empty( $rs['woo_cart_badge_bg'] )   ? ( sanitize_hex_color( $rs['woo_cart_badge_bg'] ) ?: '#ef4444' ) : '#ef4444';

	/* — Announcement bar — */
	$ss['announcement_enabled']      = isset( $rs['announcement_enabled'] ) ? ( $rs['announcement_enabled'] === '1' ? '1' : '0' ) : '0';
	$ss['announcement_text']         = isset( $rs['announcement_text'] )    ? sanitize_text_field( $rs['announcement_text'] ) : '';
	$ss['announcement_link']         = isset( $rs['announcement_link'] )    ? esc_url_raw( $rs['announcement_link'] ) : '';
	$ss['announcement_link_target']  = ( isset( $rs['announcement_link_target'] ) && $rs['announcement_link_target'] === '_blank' ) ? '_blank' : '_self';
	$ss['announcement_bg']           = ! empty( $rs['announcement_bg'] )         ? ( sanitize_hex_color( $rs['announcement_bg'] ) ?: '#667eea' ) : '#667eea';
	$ss['announcement_text_color']   = ! empty( $rs['announcement_text_color'] ) ? ( sanitize_hex_color( $rs['announcement_text_color'] ) ?: '#ffffff' ) : '#ffffff';
	$ss['announcement_position']     = in_array( $rs['announcement_position'] ?? 'above', array( 'above', 'below' ), true ) ? ( $rs['announcement_position'] ?? 'above' ) : 'above';
	$ss['announcement_dismissible']  = isset( $rs['announcement_dismissible'] ) ? ( $rs['announcement_dismissible'] === '1' ? '1' : '0' ) : '0';
	$ss['announcement_dismiss_days'] = isset( $rs['announcement_dismiss_days'] ) && is_numeric( $rs['announcement_dismiss_days'] ) ? max( 1, min( 365, intval( $rs['announcement_dismiss_days'] ) ) ) : 7;
	$ss['announcement_font_size']    = isset( $rs['announcement_font_size'] )    && is_numeric( $rs['announcement_font_size'] )    ? max( 10, min( 24,  intval( $rs['announcement_font_size'] ) ) )    : 14;
	$ss['announcement_padding_y']    = isset( $rs['announcement_padding_y'] )    && is_numeric( $rs['announcement_padding_y'] )    ? max( 4,  min( 32,  intval( $rs['announcement_padding_y'] ) ) )    : 10;
	$ss['announcement_countdown_enabled'] = isset( $rs['announcement_countdown_enabled'] ) ? ( $rs['announcement_countdown_enabled'] === '1' ? '1' : '0' ) : '0';
	$cd_date_imp = sanitize_text_field( $rs['announcement_countdown_date'] ?? '' );
	$ss['announcement_countdown_date']    = ( $cd_date_imp !== '' && strtotime( $cd_date_imp ) !== false ) ? $cd_date_imp : '';
	$ss['announcement_countdown_label']   = sanitize_text_field( $rs['announcement_countdown_label']   ?? 'Ends in:' );
	$ss['announcement_countdown_expired'] = sanitize_text_field( $rs['announcement_countdown_expired'] ?? '' );

	return $ss;
}
