<?php
/**
 * Admin functionality for Product Display
 *
 * @package Product_Display
 */

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

/**
 * Class PRODDISP_Admin
 *
 * This class handles the admin functionality of the Product Display plugin.
 */
class PRODDISP_Admin {
	/**
	 * The single instance of the class
	 */
	protected static $_instance = null;

	/**
	 * Main Instance
	 */
	public static function get_instance() {
		if ( is_null(self::$_instance) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Layout styles and modes
	 */
	public function __construct() {
		// Add menu items
		add_action('admin_menu', array( $this, 'add_menu_items' ));

		// Register AJAX handlers for React
		add_action('wp_ajax_proddisp_get_showcases', array( $this, 'ajax_get_showcases' ));
		add_action('wp_ajax_proddisp_save_showcase', array( $this, 'ajax_save_showcase' ));
		add_action('wp_ajax_proddisp_delete_showcase', array( $this, 'ajax_delete_showcase' ));
		add_action('wp_ajax_proddisp_bulk_delete_showcases', array( $this, 'ajax_bulk_delete_showcases' ));
		add_action('wp_ajax_proddisp_get_products', array( $this, 'ajax_get_products' ));
		add_action('wp_ajax_proddisp_get_products_by_ids', array( $this, 'ajax_get_products_by_ids' ));
		add_action('wp_ajax_proddisp_get_categories', array( $this, 'ajax_get_categories' ));
		add_action('wp_ajax_proddisp_get_tags', array( $this, 'ajax_get_tags' ));
		add_action('wp_ajax_proddisp_get_brands', array( $this, 'ajax_get_brands' ));
		add_action('wp_ajax_proddisp_get_attributes', array( $this, 'ajax_get_attributes' ));
		add_action('wp_ajax_proddisp_get_attribute_terms', array( $this, 'ajax_get_attribute_terms' ));
		add_action('wp_ajax_proddisp_get_shortcode_preview', array( $this, 'ajax_get_shortcode_preview' ));
		add_action('wp_ajax_proddisp_duplicate_showcase', array( $this, 'ajax_duplicate_showcase' ));
		add_action('wp_ajax_proddisp_export_showcases', array( $this, 'ajax_export_showcases' ));
		add_action('wp_ajax_proddisp_import_showcases', array( $this, 'ajax_import_showcases' ));
		add_action('wp_ajax_proddisp_get_preset_values', array( $this, 'ajax_get_preset_values' ));
		add_action('wp_ajax_proddisp_get_layout_defaults', array( $this, 'ajax_get_layout_defaults' ));
		add_action('wp_ajax_proddisp_get_custom_icons', array( $this, 'ajax_get_custom_icons' ));
		add_action('wp_ajax_proddisp_add_custom_icon', array( $this, 'ajax_add_custom_icon' ));
		add_action('wp_ajax_proddisp_remove_custom_icon', array( $this, 'ajax_remove_custom_icon' ));
		
		// Shop Integration AJAX handlers
		add_action('wp_ajax_proddisp_get_shop_integrations', array( $this, 'ajax_get_shop_integrations' ));
		add_action('wp_ajax_proddisp_save_shop_integration', array( $this, 'ajax_save_shop_integration' ));
		add_action('wp_ajax_proddisp_delete_shop_integration', array( $this, 'ajax_delete_shop_integration' ));
		add_action('wp_ajax_proddisp_get_shop_integration', array( $this, 'ajax_get_shop_integration' ));

		// Custom CSS AJAX handlers
		add_action('wp_ajax_proddisp_get_custom_css', array( $this, 'ajax_get_custom_css' ));
		add_action('wp_ajax_proddisp_save_custom_css', array( $this, 'ajax_save_custom_css' ));
	}



	/**
	 * Add menu items
	 */
	public function add_menu_items() {
		add_menu_page(
			__('Product Display', 'product-display'),
			__('Product Display', 'product-display'),
			'manage_options',
			'product-display',
			array( $this, 'render_main_page' ),
			PRODDISP_PLUGIN_URL . 'assets/logo/logo.png',
			58
		);

		// Add submenu for Choose Layout Type
		add_submenu_page(
			'product-display',
			__('Layout', 'product-display'),
			__('Layout', 'product-display'),
			'manage_options',
			'product-display&view=layout-selector&create=true&step=layout',
			array( $this, 'render_main_page' )
		);

		// Add submenu for Shop Integration
		add_submenu_page(
			'product-display',
			__('Shop Integration', 'product-display'),
			__('Shop Integration', 'product-display'),
			'manage_options',
			'product-display&view=shop-integration',
			array( $this, 'render_main_page' )
		);


		// Add submenu for Wishlist Settings
		add_submenu_page(
			'product-display',
			__('Wishlist', 'product-display'),
			__('Wishlist', 'product-display'),
			'manage_options',
			'product-display&view=wishlist',
			array( $this, 'render_main_page' )
		);

		// Add submenu for Get Started
		add_submenu_page(
			'product-display',
			__('Get Started', 'product-display'),
			__('Get Started', 'product-display'),
			'manage_options',
			'product-display&view=get-started',
			array( $this, 'render_main_page' )
		);

		
		// Add submenu for Recommendations
		add_submenu_page(
			'product-display',
			__('Recommendations', 'product-display'),
			__('Recommendations', 'product-display'),
			'manage_options',
			'product-display&view=recommendations',
			array( $this, 'render_main_page' )
		);

		// Add submenu for Custom CSS
		add_submenu_page(
			'product-display',
			__('Custom CSS', 'product-display'),
			__('Custom CSS', 'product-display'),
			'manage_options',
			'product-display&view=custom-css',
			array( $this, 'render_main_page' )
		);

		
	}


	/**
	 * Render the main admin page
	 */
	public function render_main_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have sufficient permissions to access this page', 'product-display' ),
			) );
			
		}

		// Get URL parameters
		$edit_id = isset( $_GET['edit'] ) ? sanitize_text_field( wp_unslash( $_GET['edit'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only URL param for page routing, no state change.
		$view    = isset( $_GET['view'] ) ? sanitize_text_field( wp_unslash( $_GET['view'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only URL param for page routing, no state change.
		$create  = isset( $_GET['create'] ) ? sanitize_text_field( wp_unslash( $_GET['create'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only URL param for page routing, no state change.

		// Determine initial view
		$initial_view = 'list';
		if ( ! empty($edit_id) ) {
			$initial_view = 'editor';
		} elseif ( ! empty($create) || $view === 'layout-selector' ) {
			$initial_view = 'layout-selector';
		} elseif ( $view === 'shortcode-generator' ) {
			$initial_view = 'shortcode-generator';
		} elseif ( $view === 'recommendations' ) {
			$initial_view = 'recommendations';
		} elseif ( $view === 'get-started' ) {
			$initial_view = 'get-started';
		} elseif ( $view === 'wishlist' ) {
			$initial_view = 'wishlist';
		} elseif ( $view === 'shop-integration' ) {
			$initial_view = 'shop-integration';
		} elseif ( $view === 'custom-css' ) {
			$initial_view = 'custom-css';
		}

		?>
		<div class="wrap">
			<div id="wcps-admin-styles" 
				 data-edit-id="<?php echo esc_attr($edit_id ?? ''); ?>" 
				 data-view="<?php echo esc_attr($initial_view ?? 'list'); ?>">
			</div>
		</div>
		<?php
	}

	// Get Started page is now handled by React component

	/**
	 * AJAX handler to get all showcases with pagination and search
	 */
	public function ajax_get_showcases() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get parameters
		$page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
		$per_page = isset($_POST['per_page']) ? max(1, intval($_POST['per_page'])) : 10;
		$search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';

		// Get saved showcases
		$showcases = get_option('proddisp_saved_showcases', array());

		// Filter by search if provided
		if ( ! empty($search) ) {
			$filtered_showcases = array();
			foreach ( $showcases as $id => $showcase ) {
				if ( stripos($showcase['name'], $search) !== false ) {
					$filtered_showcases[ $id ] = $showcase;
				}
			}
			$showcases = $filtered_showcases;
		}

		// Calculate pagination
		$total_items = count($showcases);
		$total_pages = ceil($total_items / $per_page);
		$offset = ( $page - 1 ) * $per_page;

		// Get current page items
		$current_showcases = array_slice($showcases, $offset, $per_page, true);

		// Format showcases for React
		$formatted_showcases = array();
		foreach ( $current_showcases as $id => $showcase ) {
			// Include all showcase data for editing, plus display fields
			$showcase_data = $showcase;
			$showcase_data['id'] = $id;
			$showcase_data['shortcode'] = '[product_display id="' . $id . '"]';

			// Ensure display fields exist
			if ( ! isset($showcase_data['name']) ) {
				$showcase_data['name'] = __('Product Showcase', 'product-display');
			}
			if ( ! isset($showcase_data['layout']) ) {
				$showcase_data['layout'] = 'grid';
			}
			if ( ! isset($showcase_data['created']) ) {
				$showcase_data['created'] = time();
			}

			$formatted_showcases[] = $showcase_data;
		}

		wp_send_json_success( array(
			'showcases' => $formatted_showcases,
			'pagination' => array(
				'current_page' => $page,
				'per_page' => $per_page,
				'total_items' => $total_items,
				'total_pages' => $total_pages,
			),
		) );
	}

	/**
	 * AJAX handler to save showcase data
	 */
	public function ajax_save_showcase() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get showcase data
		if ( ! isset($_POST['showcase_data']) ) {
			wp_send_json_error( array(
				'message' => __( 'No showcase data provided', 'product-display' ),
			) );
		}

		// Unslash and decode JSON data
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data is sanitized below via sanitize_showcase_data() after JSON decoding.
		$showcase_data = json_decode( wp_unslash( $_POST['showcase_data'] ), true );
		
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid showcase data format', 'product-display' ),
			) );
		}

		// Sanitize the decoded data
		$showcase_data = $this->sanitize_showcase_data( $showcase_data );

		// Get existing showcases
		$showcases = get_option('proddisp_saved_showcases', array());

		// Generate ID for new showcase or use existing
		if ( isset($showcase_data['id']) && ! empty($showcase_data['id']) ) {
			$showcase_id = intval( $showcase_data['id'] );
		} else {
			// Generate numeric ID like the old plugin
			$max_id = 0;
			foreach ( $showcases as $id => $data ) {
				if ( is_numeric($id) && intval($id) > $max_id ) {
					$max_id = intval($id);
				}
			}
			$showcase_id = $max_id + 1;
		}

		// Add timestamps
		if ( ! isset($showcases[ $showcase_id ]) ) {
			$showcase_data['created'] = time();
		}
		$showcase_data['updated'] = time();

		// Add the ID to the showcase data before saving
		$showcase_data['id'] = $showcase_id;

		// Save showcase
		$showcases[ $showcase_id ] = $showcase_data;
		update_option('proddisp_saved_showcases', $showcases);

		wp_send_json_success( array(
			'message' => __( 'Showcase saved successfully', 'product-display' ),
			'showcase_id' => $showcase_id,
		) );
	}

	/**
	 * Sanitize showcase data array
	 */
	private function sanitize_showcase_data( $data ) {
		if ( ! is_array( $data ) ) {
			return array();
		}

		$sanitized = array();

		// Integer fields
		$int_fields = array(
			'id', 'limit', 'columns', 'excerpt_length', 'pagination_per_page', 
			'slide_speed', 'created', 'updated', 'desc_size', 'border_width',
			'border_radius', 'button_border_radius', 'product_content_padding'
		);
		foreach ( $int_fields as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$sanitized[ $field ] = absint( $data[ $field ] );
			}
		}

		// Text fields (basic text)
		$text_fields = array(
			'name', 'layout', 'proddisp_layout_mode', 'product_source', 'attribute',
			'orderby', 'order', 'image_size', 'action_position', 'custom_class',
			'addtocart_display_mode', 'compare_display_mode', 'quickview_display_mode',
			'wishlist_display_mode', 'addtocart_icon', 'compare_icon', 'quickview_icon',
			'wishlist_icon', 'text_align', 'border_style', 'image_aspect_ratio',
			'product_badge_font_weight', 'product_badge_text_align', 'product_badge_text_transform',
			'button_animation', 'product_flex', 'product_content_direction', 'box_shadow',
			'image_hover_effect', 'hover_effect', 'shortcode'
		);
		foreach ( $text_fields as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$sanitized[ $field ] = sanitize_text_field( $data[ $field ] );
			}
		}

		// Yes/No boolean fields
		$yes_no_fields = array(
			'show_title', 'show_price', 'show_rating', 'show_description',
			'show_addtocart', 'show_compare', 'show_quickview', 'show_wishlist',
			'enable_ajax', 'enable_filters', 'enable_pagination',
			'autoplay', 'arrows', 'dots'
		);
		foreach ( $yes_no_fields as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$value = sanitize_text_field( $data[ $field ] );
				$sanitized[ $field ] = in_array( $value, array( 'yes', 'no' ), true ) ? $value : 'no';
			}
		}

		// Array fields (IDs)
		$array_fields = array( 'products', 'category', 'tag', 'brand', 'attribute_terms' );
		foreach ( $array_fields as $field ) {
			if ( isset( $data[ $field ] ) && is_array( $data[ $field ] ) ) {
				$sanitized[ $field ] = array_map( 'absint', $data[ $field ] );
			} else {
				$sanitized[ $field ] = array();
			}
		}

		// Color fields (hex, rgb, rgba, hsl, hsla)
		$color_fields = array(
			'container_background', 'product_background', 'product_title',
			'product_title_hover_color', 'description_color', 'price_delete_color',
			'price_color', 'star_color', 'product_badge_background',
			'product_badge_font_color', 'button_bg_color', 'button_text_color',
			'button_hover_bg', 'button_hover_text_color', 'product_content_background',
			'border_color'
		);
		foreach ( $color_fields as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$sanitized[ $field ] = $this->sanitize_color_field( $data[ $field ] );
			}
		}

		// CSS size/dimension fields (can include px, %, em, rem, auto, etc.)
		$css_fields = array(
			'container_padding', 'container_margin', 'grid_gap', 'grid_width',
			'title_size', 'price_size', 'star_size', 'product_badge_font_size',
			'button_font_size', 'button_padding', 'button_margin', 'product_image_width',
			'product_image_height', 'image_border_radius', 'product_badge_border_radius',
			'product_badge_padding', 'product_badge_margin', 'product_content_margin',
			'product_width', 'title_weight', 'price_weight', 'hover_transition'
		);
		foreach ( $css_fields as $field ) {
			if ( isset( $data[ $field ] ) ) {
				$sanitized[ $field ] = $this->sanitize_css_field( $data[ $field ] );
			}
		}

		// CSS border fields (includes width and style)
		if ( isset( $data['button_border'] ) ) {
			$sanitized['button_border'] = $this->sanitize_css_field( $data['button_border'] );
		}
		if ( isset( $data['button_hover_border'] ) ) {
			$sanitized['button_hover_border'] = $this->sanitize_css_field( $data['button_hover_border'] );
		}

		// Gradient/complex background field
		if ( isset( $data['caption_hover_bg'] ) ) {
			$sanitized['caption_hover_bg'] = $this->sanitize_css_field( $data['caption_hover_bg'] );
		}

		return $sanitized;
	}

	/**
	 * Sanitize color field (supports hex, rgb, rgba, hsl, hsla)
	 */
	private function sanitize_color_field( $value ) {
		$value = sanitize_text_field( $value );
		
		// Allow hex colors (#fff, #ffffff, #ffffff00)
		if ( preg_match( '/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/', $value ) ) {
			return $value;
		}
		
		// Allow rgb/rgba values
		if ( preg_match( '/^rgba?\s*\([^)]+\)$/i', $value ) ) {
			return $value;
		}
		
		// Allow hsl/hsla values
		if ( preg_match( '/^hsla?\s*\([^)]+\)$/i', $value ) ) {
			return $value;
		}
		
		// Allow CSS color keywords (transparent, inherit, currentColor, etc.)
		if ( preg_match( '/^(transparent|inherit|initial|unset|currentColor)$/i', $value ) ) {
			return strtolower( $value );
		}
		
		return sanitize_text_field( $value );
	}

	/**
	 * Sanitize CSS field (supports sizes, borders, gradients, etc.)
	 */
	private function sanitize_css_field( $value ) {
		$value = sanitize_text_field( $value );
		
		// Allow CSS units: px, em, rem, %, vw, vh, auto, etc.
		if ( preg_match( '/^[\d.]+\s*(px|em|rem|%|vw|vh|vmin|vmax|ch|ex)?$/i', $value ) ) {
			return $value;
		}
		
		// Allow 'auto', 'inherit', 'initial', 'unset', 'none'
		if ( preg_match( '/^(auto|inherit|initial|unset|none)$/i', $value ) ) {
			return strtolower( $value );
		}
		
		// Allow complex CSS values (gradients, borders, box-shadow, etc.)
		// For gradients: linear-gradient, radial-gradient
		if ( preg_match( '/^(linear|radial|conic)-gradient\s*\([^)]+\)$/i', $value ) ) {
			return $value;
		}
		
		// Allow border syntax (1px solid #ddd)
		if ( preg_match( '/^[\d.]+\s*(px|em|rem)?\s+(solid|dashed|dotted|double|groove|ridge|inset|outset|none|hidden)\s+.+$/i', $value ) ) {
			return $value;
		}
		
		// Allow space-separated values (padding, margin, etc.)
		if ( preg_match( '/^([\d.]+\s*(px|em|rem|%)?(\s+|$))+$/i', $value ) ) {
			return $value;
		}
		
		// For numeric values without units (like font-weight)
		if ( is_numeric( $value ) ) {
			return $value;
		}
		
		return sanitize_text_field( $value );
	}

	/**
	 * AJAX handler to delete a single showcase
	 */
	public function ajax_delete_showcase() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get showcase ID
		if ( ! isset($_POST['showcase_id']) || empty($_POST['showcase_id']) ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid showcase ID', 'product-display' ),
			) );
		}

		$showcase_id = sanitize_text_field(wp_unslash($_POST['showcase_id']));

		// Get existing showcases
		$showcases = get_option('proddisp_saved_showcases', array());

		// Check if showcase exists
		if ( ! isset($showcases[ $showcase_id ]) ) {
			wp_send_json_error( array(
				'message' => __( 'Showcase not found', 'product-display' ),
			) );
		}

		// Remove showcase
		unset($showcases[ $showcase_id ]);

		// Update option
		update_option('proddisp_saved_showcases', $showcases);

		// Clean up custom CSS for this showcase
		$all_css = get_option( 'proddisp_custom_css', array() );
		if ( isset( $all_css[ $showcase_id ] ) ) {
			unset( $all_css[ $showcase_id ] );
			update_option( 'proddisp_custom_css', $all_css );
		}

		wp_send_json_success( array(
			'message' => __( 'Showcase deleted successfully', 'product-display' ),
		) );
	}

	/**
	 * AJAX handler to bulk delete showcases
	 */
	public function ajax_bulk_delete_showcases() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get showcase IDs
		if ( ! isset($_POST['showcase_ids']) || ! is_array($_POST['showcase_ids']) || empty($_POST['showcase_ids']) ) {
			wp_send_json_error( array(
				'message' => __( 'No showcases selected', 'product-display' ),
			) );
		}

		$showcase_ids = array_map('sanitize_text_field', wp_unslash($_POST['showcase_ids']));

		// Get existing showcases
		$showcases = get_option('proddisp_saved_showcases', array());
		$deleted_count = 0;

		// Remove selected showcases
		foreach ( $showcase_ids as $id ) {
			if ( isset($showcases[ $id ]) ) {
				unset($showcases[ $id ]);
				$deleted_count++;
			}
		}

		// Update option
		update_option('proddisp_saved_showcases', $showcases);

		// Clean up custom CSS for deleted showcases
		$all_css = get_option( 'proddisp_custom_css', array() );
		$css_changed = false;
		foreach ( $showcase_ids as $id ) {
			if ( isset( $all_css[ $id ] ) ) {
				unset( $all_css[ $id ] );
				$css_changed = true;
			}
		}
		if ( $css_changed ) {
			update_option( 'proddisp_custom_css', $all_css );
		}

		wp_send_json_success( array(
			'message' => sprintf(__( '%d showcases deleted successfully', 'product-display' ), $deleted_count),
			'deleted_count' => $deleted_count,
		) );
	}

	/**
	 * AJAX handler to duplicate a showcase
	 */
	public function ajax_duplicate_showcase() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get showcase ID
		if ( ! isset($_POST['showcase_id']) || empty($_POST['showcase_id']) ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid showcase ID', 'product-display' ),
			) );
		}

		$showcase_id = sanitize_text_field(wp_unslash($_POST['showcase_id']));

		// Get existing showcases
		$showcases = get_option('proddisp_saved_showcases', array());

		// Check if showcase exists
		if ( ! isset($showcases[ $showcase_id ]) ) {
			wp_send_json_error( array(
				'message' => __( 'Showcase not found', 'product-display' ),
			) );
		}

		// Get the original showcase data
		$original_showcase = $showcases[ $showcase_id ];

		// Generate new numeric ID (consistent with save method)
		$max_id = 0;
		foreach ( $showcases as $id => $data ) {
			if ( is_numeric($id) && intval($id) > $max_id ) {
				$max_id = intval($id);
			}
		}
		$new_id = $max_id + 1;

		// Create duplicate with modified name, new ID, and new timestamp
		$duplicate_showcase = $original_showcase;
		$original_name = isset($original_showcase['name']) ? $original_showcase['name'] : 'Untitled Showcase';
		$duplicate_showcase['id'] = $new_id;
		$duplicate_showcase['name'] = $original_name . ' (Copy)';
		$duplicate_showcase['created'] = time();
		$duplicate_showcase['updated'] = time();

		// Save the duplicate
		$showcases[ $new_id ] = $duplicate_showcase;
		update_option('proddisp_saved_showcases', $showcases);

		// Prepare response data
		$response_showcase = array(
			'id' => $new_id,
			'name' => $duplicate_showcase['name'],
			'layout' => isset($duplicate_showcase['layout']) ? $duplicate_showcase['layout'] : 'grid',
			'created' => $duplicate_showcase['created'],
		);

		wp_send_json_success( array(
			'message' => __( 'Showcase duplicated successfully', 'product-display' ),
			'showcase' => $response_showcase,
		) );
	}

	/**
	 * AJAX handler to export showcases (all or selected IDs).
	 */
	public function ajax_export_showcases() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied', 'product-display' ) ) );
		}
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed', 'product-display' ) ) );
		}
		if ( ! PRODDISP_Loader::is_pro_active() ) {
			wp_send_json_error( array( 'message' => __( 'Pro version required', 'product-display' ), 'pro_required' => true ) );
		}

		$showcases = get_option( 'proddisp_saved_showcases', array() );

		// Filter by specific IDs if provided
		if ( ! empty( $_POST['ids'] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON-decoded array values are cast to int via array_map( 'intval', ... ) below.
			$ids_raw = json_decode( wp_unslash( $_POST['ids'] ), true );
			if ( is_array( $ids_raw ) ) {
				$ids = array_map( 'intval', $ids_raw );
				$showcases = array_filter(
					$showcases,
					function( $key ) use ( $ids ) {         // ← key passed correctly
						return in_array( (int) $key, $ids, true );
					},
					ARRAY_FILTER_USE_KEY
				);
			}
		}

		$export = array_values( $showcases );

		// Include per-item summary for the response (mirrors import details format)
		$details = array_map( function( $item ) {
			return array(
				'id'   => $item['id'] ?? null,
				'name' => $item['name'] ?? 'Untitled',
			);
		}, $export );

		wp_send_json_success( array(
			'showcases' => $export,
			'count'     => count( $export ),
			'details'   => $details,           // ← per-item detail, matches import response
		) );
	}

	/**
	 * AJAX handler to import showcases from JSON (Pro only).
	 */
	public function ajax_import_showcases() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied', 'product-display' ) ) );
		}
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed', 'product-display' ) ) );
		}
		if ( ! PRODDISP_Loader::is_pro_active() ) {
			wp_send_json_error( array( 'message' => __( 'Pro version required', 'product-display' ), 'pro_required' => true ) );
		}

		if ( ! isset( $_POST['showcases'] ) ) {
			wp_send_json_error( array( 'message' => __( 'No data provided', 'product-display' ) ) );
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON-decoded array items are sanitized individually via sanitize_showcase_data() in the foreach loop below.
		$raw = json_decode( wp_unslash( $_POST['showcases'] ), true );
		if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $raw ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid JSON data', 'product-display' ) ) );
		}

		$showcases = get_option( 'proddisp_saved_showcases', array() );
		$max_id    = empty( $showcases ) ? 0 : max( array_map( 'intval', array_keys( $showcases ) ) );
		$imported  = 0;
		$details   = array();

		foreach ( $raw as $item ) {
			if ( ! is_array( $item ) ) continue;
			$max_id++;
			$item = $this->sanitize_showcase_data( $item );
			$name            = isset( $item['name'] ) ? $item['name'] . ' (Imported)' : 'Imported Layout';
			$item['id']      = $max_id;
			$item['name']    = $name;
			$item['created'] = time();
			$item['updated'] = time();
			$showcases[ $max_id ] = $item;
			$details[] = array( 'id' => $max_id, 'name' => $name );
			$imported++;
		}

		update_option( 'proddisp_saved_showcases', $showcases );

		wp_send_json_success( array(
			'message'  => sprintf( __( '%d layout(s) imported successfully', 'product-display' ), $imported ),
			'imported' => $imported,
			'details'  => $details,
		) );
	}

	/**
	 * AJAX handler to get preset values for a layout mode
	 */
	public function ajax_get_preset_values() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get layout mode
		if ( ! isset($_POST['layout_mode']) || empty($_POST['layout_mode']) ) {
			wp_send_json_error( array(
				'message' => __( 'Layout mode is required', 'product-display' ),
			) );
		}

		$layout_mode = sanitize_text_field(wp_unslash($_POST['layout_mode']));

		// Get default values
		$defaults = $this->get_default_values_from_json();

		// Get preset values for the specific layout mode
		$preset_values = $this->get_preset_values_from_json($layout_mode);

		// Merge defaults with preset values (preset values override defaults)
		$merged_values = array_merge($defaults, $preset_values);

		wp_send_json_success( array(
			'preset_values' => $merged_values,
			'layout_mode' => $layout_mode,
		) );
	}

	/**
	 * AJAX handler to get WooCommerce products
	 */
	public function ajax_get_products() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get parameters
		$search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
		$page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
		$per_page = isset($_POST['per_page']) ? max(1, min(50, intval($_POST['per_page']))) : 20;

		// Query products
		$args = array(
			'post_type' => 'product',
			'post_status' => 'publish',
			'posts_per_page' => $per_page,
			'paged' => $page,
		);

		if ( ! empty($search) ) {
			$args['s'] = $search;
		}

		$query = new WP_Query($args);
		$products = array();

		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$product = wc_get_product(get_the_ID());

				if ( $product ) {
					$products[] = array(
						'id' => $product->get_id(),
						'name' => $product->get_name(),
						'price' => $product->get_price_html(),
						'image' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
						'sku' => $product->get_sku(),
						'status' => $product->get_status(),
					);
				}
			}
			wp_reset_postdata();
		}

		wp_send_json_success( array(
			'products' => $products,
			'pagination' => array(
				'current_page' => $page,
				'per_page' => $per_page,
				'total_items' => $query->found_posts,
				'total_pages' => $query->max_num_pages,
			),
		) );
	}

	/**
	 * AJAX handler to get products by specific IDs
	 */
	public function ajax_get_products_by_ids() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get product IDs
		$product_ids = isset($_POST['product_ids']) ? sanitize_text_field(wp_unslash($_POST['product_ids'])) : '';

		if ( empty($product_ids) ) {
			wp_send_json_success( array( 'products' => array() ) );
		}

		// Convert comma-separated string to array of integers
		$ids = array_map('intval', explode(',', $product_ids));
		$ids = array_filter($ids); // Remove any invalid IDs

		$products = array();

		foreach ( $ids as $product_id ) {
			$product = wc_get_product($product_id);

			if ( $product && $product->get_status() === 'publish' ) {
				$products[] = array(
					'id' => $product->get_id(),
					'name' => $product->get_name(),
					'price' => $product->get_price_html(),
					'image' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail'),
					'sku' => $product->get_sku(),
					'status' => $product->get_status(),
				);
			}
		}

		wp_send_json_success( array( 'products' => $products ) );
	}

	/**
	 * AJAX handler to get product categories
	 */
	public function ajax_get_categories() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get categories
		$categories = get_terms( array(
			'taxonomy' => 'product_cat',
			'hide_empty' => true,
		) );

		$formatted_categories = array();
		if ( ! is_wp_error($categories) ) {
			foreach ( $categories as $category ) {
				$formatted_categories[] = array(
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'count' => $category->count,
				);
			}
		}

		wp_send_json_success( array(
			'categories' => $formatted_categories,
		) );
	}

	/**
	 * AJAX handler to get product tags
	 */
	public function ajax_get_tags() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get tags
		$tags = get_terms( array(
			'taxonomy' => 'product_tag',
			'hide_empty' => true,
		) );

		$formatted_tags = array();
		if ( ! is_wp_error($tags) ) {
			foreach ( $tags as $tag ) {
				$formatted_tags[] = array(
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
					'count' => $tag->count,
				);
			}
		}

		wp_send_json_success( array(
			'tags' => $formatted_tags,
		) );
	}

	/**
	 * AJAX handler to get product brands
	 */
	public function ajax_get_brands() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get brands (assuming brands are stored as a custom taxonomy 'product_brand')
		$brands = get_terms( array(
			'taxonomy' => 'product_brand',
			'hide_empty' => true,
		) );

		$formatted_brands = array();
		if ( ! is_wp_error($brands) ) {
			foreach ( $brands as $brand ) {
				$formatted_brands[] = array(
					'id' => $brand->term_id,
					'name' => $brand->name,
					'slug' => $brand->slug,
					'count' => $brand->count,
				);
			}
		}

		wp_send_json_success( array(
			'brands' => $formatted_brands,
		) );
	}

	/**
	 * AJAX handler to get product attributes
	 */
	public function ajax_get_attributes() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get product attributes
		$attributes = wc_get_attribute_taxonomies();
		$formatted_attributes = array();

		foreach ( $attributes as $attribute ) {
			$formatted_attributes[] = array(
				'id' => $attribute->attribute_id,
				'name' => $attribute->attribute_label,
				'slug' => $attribute->attribute_name,
				'type' => $attribute->attribute_type,
			);
		}

		wp_send_json_success( array(
			'attributes' => $formatted_attributes,
		) );
	}

	/**
	 * AJAX handler to get attribute terms
	 */
	public function ajax_get_attribute_terms() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get attribute slug
		if ( ! isset($_POST['attribute']) || empty($_POST['attribute']) ) {
			wp_send_json_error( array(
				'message' => __( 'Attribute not specified', 'product-display' ),
			) );
		}

		$attribute_slug = sanitize_text_field(wp_unslash($_POST['attribute']));
		$taxonomy = 'pa_' . $attribute_slug;

		// Get terms
		$terms = get_terms( array(
			'taxonomy' => $taxonomy,
			'hide_empty' => true,
		) );

		$formatted_terms = array();
		if ( ! is_wp_error($terms) ) {
			foreach ( $terms as $term ) {
				$formatted_terms[] = array(
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'count' => $term->count,
				);
			}
		}

		wp_send_json_success( array(
			'terms' => $formatted_terms,
		) );
	}

	/**
	 * AJAX handler to get shortcode preview
	 */
	public function ajax_get_shortcode_preview() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get showcase data (React sends 'data', not 'settings')
		$data_key = isset($_POST['data']) ? 'data' : 'settings';
		if ( ! isset($_POST[ $data_key ]) ) {
			wp_send_json_error( array(
				'message' => __( 'No showcase data provided', 'product-display' ),
			) );
		}

		// $showcase_data = json_decode(stripslashes($_POST[ $data_key ]), true);
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data is sanitized below via sanitize_showcase_data() after JSON decoding.
		$showcase_data = json_decode( wp_unslash( $_POST[ $data_key ] ), true );
		
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid showcase data format', 'product-display' ),
			) );
		}

		// Sanitize the decoded data
		$showcase_data = $this->sanitize_showcase_data( $showcase_data );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid showcase data format', 'product-display' ),
			) );
		}

		// Convert React showcase data to shortcode attributes
		$atts = $this->convert_showcase_data_to_shortcode_atts($showcase_data);

		// Generate preview using shortcode
		if ( class_exists('PRODDISP_Shortcode') ) {
			$shortcode = PRODDISP_Shortcode::get_instance();
			$preview_html = $shortcode->render_shortcode($atts);
		} else {
			// Fallback if shortcode class doesn't exist
			$preview_html = $this->generate_basic_preview($showcase_data);
		}

		wp_send_json_success( array(
			'html' => $preview_html,
		) );
	}

	/**
	 * Convert React showcase data to shortcode attributes
	 */
	private function convert_showcase_data_to_shortcode_atts( $showcase_data ) {
		// Get default values
		$defaults = $this->get_default_values_from_json();

		// Convert React data format to shortcode attributes
		$atts = array();

		// Basic layout settings
		$atts['layout'] = isset($showcase_data['layout']) ? $showcase_data['layout'] : 'grid';
		$atts['proddisp_layout_mode'] = isset($showcase_data['proddisp_layout_mode']) ? $showcase_data['proddisp_layout_mode'] : 'basic-grid';
		$atts['product_source'] = isset($showcase_data['product_source']) ? $showcase_data['product_source'] : 'manual';

		// Handle products based on source
		switch ( $atts['product_source'] ) {
			case 'manual':
			case 'specific':
				// React sends 'products' array
				if ( isset($showcase_data['products']) && ! empty($showcase_data['products']) ) {
					$atts['products'] = is_array($showcase_data['products'])
						? implode(',', $showcase_data['products'])
						: $showcase_data['products'];
				}
				break;
			case 'category':
				// React sends 'category' array
				if ( isset($showcase_data['category']) && ! empty($showcase_data['category']) ) {
					$atts['category'] = is_array($showcase_data['category'])
						? implode(',', $showcase_data['category'])
						: $showcase_data['category'];
				}
				break;
			case 'tag':
				// React sends 'tag' array
				if ( isset($showcase_data['tag']) && ! empty($showcase_data['tag']) ) {
					$atts['tag'] = is_array($showcase_data['tag'])
						? implode(',', $showcase_data['tag'])
						: $showcase_data['tag'];
				}
				break;
			case 'brand':
				// React sends 'brand' array
				if ( isset($showcase_data['brand']) && ! empty($showcase_data['brand']) ) {
					$atts['brand'] = is_array($showcase_data['brand'])
						? implode(',', $showcase_data['brand'])
						: $showcase_data['brand'];
				}
				break;
			case 'attribute':
				$atts['attribute'] = isset($showcase_data['attribute']) ? $showcase_data['attribute'] : '';
				if ( isset($showcase_data['attribute_terms']) && ! empty($showcase_data['attribute_terms']) ) {
					$atts['attribute_terms'] = is_array($showcase_data['attribute_terms'])
						? implode(',', $showcase_data['attribute_terms'])
						: $showcase_data['attribute_terms'];
				}
				break;
		}

		// Basic display settings
		$atts['limit'] = isset($showcase_data['limit']) ? intval($showcase_data['limit']) : $defaults['limit'];
		$atts['columns'] = isset($showcase_data['columns']) ? intval($showcase_data['columns']) : $defaults['columns'];
		$atts['orderby'] = isset($showcase_data['orderby']) ? $showcase_data['orderby'] : $defaults['orderby'];
		$atts['order'] = isset($showcase_data['order']) ? $showcase_data['order'] : $defaults['order'];

		// Display elements
		$atts['show_title'] = isset($showcase_data['show_title']) ? $showcase_data['show_title'] : $defaults['show_title'];
		$atts['show_price'] = isset($showcase_data['show_price']) ? $showcase_data['show_price'] : $defaults['show_price'];
		$atts['show_rating'] = isset($showcase_data['show_rating']) ? $showcase_data['show_rating'] : $defaults['show_rating'];
		$atts['show_description'] = isset($showcase_data['show_description']) ? $showcase_data['show_description'] : $defaults['show_description'];
		$atts['excerpt_length'] = isset($showcase_data['excerpt_length']) ? intval($showcase_data['excerpt_length']) : $defaults['excerpt_length'];

		// Action buttons
		$atts['show_addtocart'] = isset($showcase_data['show_addtocart']) ? $showcase_data['show_addtocart'] : $defaults['show_addtocart'];
		$atts['show_compare'] = isset($showcase_data['show_compare']) ? $showcase_data['show_compare'] : $defaults['show_compare'];
		$atts['show_quickview'] = isset($showcase_data['show_quickview']) ? $showcase_data['show_quickview'] : $defaults['show_quickview'];
		$atts['show_wishlist'] = isset($showcase_data['show_wishlist']) ? $showcase_data['show_wishlist'] : $defaults['show_wishlist'];

		// Action button display modes
		if ( isset($showcase_data['addtocart_display_mode']) ) {
			$atts['addtocart_display_mode'] = $showcase_data['addtocart_display_mode'];
		}
		if ( isset($showcase_data['compare_display_mode']) ) {
			$atts['compare_display_mode'] = $showcase_data['compare_display_mode'];
		}
		if ( isset($showcase_data['quickview_display_mode']) ) {
			$atts['quickview_display_mode'] = $showcase_data['quickview_display_mode'];
		}
		if ( isset($showcase_data['wishlist_display_mode']) ) {
			$atts['wishlist_display_mode'] = $showcase_data['wishlist_display_mode'];
		}

		// Action button icons
		if ( isset($showcase_data['addtocart_icon']) ) {
			$atts['addtocart_icon'] = $showcase_data['addtocart_icon'];
		}
		if ( isset($showcase_data['compare_icon']) ) {
			$atts['compare_icon'] = $showcase_data['compare_icon'];
		}
		if ( isset($showcase_data['quickview_icon']) ) {
			$atts['quickview_icon'] = $showcase_data['quickview_icon'];
		}
		if ( isset($showcase_data['wishlist_icon']) ) {
			$atts['wishlist_icon'] = $showcase_data['wishlist_icon'];
		}

		// Action position
		if ( isset($showcase_data['action_position']) ) {
			$atts['action_position'] = $showcase_data['action_position'];
		}

		// Style settings - map React data to shortcode attributes
		// Container styles
		if ( isset($showcase_data['container_background']) ) {
			$atts['container_background'] = $showcase_data['container_background'];
		}
		if ( isset($showcase_data['container_padding']) ) {
			$atts['container_padding'] = $showcase_data['container_padding'];
		}
		if ( isset($showcase_data['container_margin']) ) {
			$atts['container_margin'] = $showcase_data['container_margin'];
		}

		// Grid styles
		if ( isset($showcase_data['grid_gap']) ) {
			$atts['grid_gap'] = $showcase_data['grid_gap'];
		}
		if ( isset($showcase_data['grid_width']) ) {
			$atts['grid_width'] = $showcase_data['grid_width'];
		}

		// Product styles
		if ( isset($showcase_data['product_background']) ) {
			$atts['product_background'] = $showcase_data['product_background'];
		}
		if ( isset($showcase_data['product_content_padding']) ) {
			$atts['product_content_padding'] = $showcase_data['product_content_padding'];
		}
		if ( isset($showcase_data['product_title']) ) {
			$atts['product_title'] = $showcase_data['product_title'];
		}
		if ( isset($showcase_data['product_title_hover_color']) ) {
			$atts['product_title_hover_color'] = $showcase_data['product_title_hover_color'];
		}
		if ( isset($showcase_data['title_size']) ) {
			$atts['title_size'] = $showcase_data['title_size'];
		}
		if ( isset($showcase_data['title_weight']) ) {
			$atts['title_weight'] = $showcase_data['title_weight'];
		}
		if ( isset($showcase_data['description_color']) ) {
			$atts['description_color'] = $showcase_data['description_color'];
		}
		if ( isset($showcase_data['desc_size']) ) {
			$atts['desc_size'] = $showcase_data['desc_size'];
		}
		if ( isset($showcase_data['price_delete_color']) ) {
			$atts['price_delete_color'] = $showcase_data['price_delete_color'];
		}
		if ( isset($showcase_data['price_color']) ) {
			$atts['price_color'] = $showcase_data['price_color'];
		}
		if ( isset($showcase_data['price_size']) ) {
			$atts['price_size'] = $showcase_data['price_size'];
		}
		if ( isset($showcase_data['price_weight']) ) {
			$atts['price_weight'] = $showcase_data['price_weight'];
		}
		if ( isset($showcase_data['star_size']) ) {
			$atts['star_size'] = $showcase_data['star_size'];
		}
		if ( isset($showcase_data['star_color']) ) {
			$atts['star_color'] = $showcase_data['star_color'];
		}
		if ( isset($showcase_data['text_align']) ) {
			$atts['text_align'] = $showcase_data['text_align'];
		}

		// Border styles
		if ( isset($showcase_data['border_radius']) ) {
			$atts['border_radius'] = $showcase_data['border_radius'];
		}
		if ( isset($showcase_data['border_style']) ) {
			$atts['border_style'] = $showcase_data['border_style'];
		}
		if ( isset($showcase_data['border_width']) ) {
			$atts['border_width'] = $showcase_data['border_width'];
		}
		if ( isset($showcase_data['border_color']) ) {
			$atts['border_color'] = $showcase_data['border_color'];
		}

		// Image styles
		if ( isset($showcase_data['product_image_width']) ) {
			$atts['product_image_width'] = $showcase_data['product_image_width'];
		}
		if ( isset($showcase_data['product_image_height']) ) {
			$atts['product_image_height'] = $showcase_data['product_image_height'];
		}
		if ( isset($showcase_data['image_aspect_ratio']) ) {
			$atts['image_aspect_ratio'] = $showcase_data['image_aspect_ratio'];
		}
		if ( isset($showcase_data['image_border_radius']) ) {
			$atts['image_border_radius'] = $showcase_data['image_border_radius'];
		}

		// Badge styles
		if ( isset($showcase_data['product_badge_background']) ) {
			$atts['product_badge_background'] = $showcase_data['product_badge_background'];
		}
		if ( isset($showcase_data['product_badge_font_color']) ) {
			$atts['product_badge_font_color'] = $showcase_data['product_badge_font_color'];
		}
		if ( isset($showcase_data['product_badge_font_size']) ) {
			$atts['product_badge_font_size'] = $showcase_data['product_badge_font_size'];
		}
		if ( isset($showcase_data['product_badge_font_weight']) ) {
			$atts['product_badge_font_weight'] = $showcase_data['product_badge_font_weight'];
		}
		if ( isset($showcase_data['product_badge_text_align']) ) {
			$atts['product_badge_text_align'] = $showcase_data['product_badge_text_align'];
		}
		if ( isset($showcase_data['product_badge_text_transform']) ) {
			$atts['product_badge_text_transform'] = $showcase_data['product_badge_text_transform'];
		}
		if ( isset($showcase_data['product_badge_border_radius']) ) {
			$atts['product_badge_border_radius'] = $showcase_data['product_badge_border_radius'];
		}
		if ( isset($showcase_data['product_badge_padding']) ) {
			$atts['product_badge_padding'] = $showcase_data['product_badge_padding'];
		}
		if ( isset($showcase_data['product_badge_margin']) ) {
			$atts['product_badge_margin'] = $showcase_data['product_badge_margin'];
		}

		// Button styles
		if ( isset($showcase_data['button_border_radius']) ) {
			$atts['button_border_radius'] = $showcase_data['button_border_radius'];
		}
		if ( isset($showcase_data['button_bg_color']) ) {
			$atts['button_bg_color'] = $showcase_data['button_bg_color'];
		}
		if ( isset($showcase_data['button_text_color']) ) {
			$atts['button_text_color'] = $showcase_data['button_text_color'];
		}
		if ( isset($showcase_data['button_hover_bg']) ) {
			$atts['button_hover_bg'] = $showcase_data['button_hover_bg'];
		}
		if ( isset($showcase_data['button_hover_text_color']) ) {
			$atts['button_hover_text_color'] = $showcase_data['button_hover_text_color'];
		}
		if ( isset($showcase_data['button_font_size']) ) {
			$atts['button_font_size'] = $showcase_data['button_font_size'];
		}
		if ( isset($showcase_data['button_padding']) ) {
			$atts['button_padding'] = $showcase_data['button_padding'];
		}
		if ( isset($showcase_data['button_margin']) ) {
			$atts['button_margin'] = $showcase_data['button_margin'];
		}
		if ( isset($showcase_data['button_border']) ) {
			$atts['button_border'] = $showcase_data['button_border'];
		}
		if ( isset($showcase_data['button_hover_border']) ) {
			$atts['button_hover_border'] = $showcase_data['button_hover_border'];
		}
		if ( isset($showcase_data['button_animation']) ) {
			$atts['button_animation'] = $showcase_data['button_animation'];
		}

		// Product layout styles
		if ( isset($showcase_data['product_width']) ) {
			$atts['product_width'] = $showcase_data['product_width'];
		}
		if ( isset($showcase_data['product_flex']) ) {
			$atts['product_flex'] = $showcase_data['product_flex'];
		}
		if ( isset($showcase_data['product_content_background']) ) {
			$atts['product_content_background'] = $showcase_data['product_content_background'];
		}
		if ( isset($showcase_data['product_content_margin']) ) {
			$atts['product_content_margin'] = $showcase_data['product_content_margin'];
		}
		if ( isset($showcase_data['product_content_direction']) ) {
			$atts['product_content_direction'] = $showcase_data['product_content_direction'];
		}

		// Effects styles
		if ( isset($showcase_data['box_shadow']) ) {
			$atts['box_shadow'] = $showcase_data['box_shadow'];
		}
		if ( isset($showcase_data['image_hover_effect']) ) {
			$atts['image_hover_effect'] = $showcase_data['image_hover_effect'];
		}
		if ( isset($showcase_data['hover_effect']) ) {
			$atts['hover_effect'] = $showcase_data['hover_effect'];
		}
		if ( isset($showcase_data['hover_transition']) ) {
			$atts['hover_transition'] = $showcase_data['hover_transition'];
		}
		if ( isset($showcase_data['caption_hover_bg']) ) {
			$atts['caption_hover_bg'] = $showcase_data['caption_hover_bg'];
		}

		// AJAX settings
		if ( isset($showcase_data['enable_ajax']) ) {
			$atts['enable_ajax'] = $showcase_data['enable_ajax'];
		}
		if ( isset($showcase_data['enable_filters']) ) {
			$atts['enable_filters'] = $showcase_data['enable_filters'];
		}
		if ( isset($showcase_data['enable_pagination']) ) {
			$atts['enable_pagination'] = $showcase_data['enable_pagination'];
		}
		if ( isset($showcase_data['pagination_per_page']) ) {
			$atts['pagination_per_page'] = $showcase_data['pagination_per_page'];
		}

		// Custom CSS class
		if ( isset($showcase_data['custom_class']) && ! empty($showcase_data['custom_class']) ) {
			$atts['custom_class'] = $showcase_data['custom_class'];
		}

		// Add more attributes as needed...
		return $atts;
	}

	/**
	 * Generate basic preview when shortcode class is not available
	 */
	private function generate_basic_preview( $showcase_data ) {
		$preview_html = '<div class="proddisp-basic-preview" style="padding: 20px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">';
		$preview_html .= '<h4 style="margin-top: 0;">Preview</h4>';
		$preview_html .= '<p><strong>Layout:</strong> ' . esc_html($showcase_data['layout'] ?? 'Grid') . '</p>';
		$preview_html .= '<p><strong>Mode:</strong> ' . esc_html($showcase_data['proddisp_layout_mode'] ?? 'basic-grid') . '</p>';
		$preview_html .= '<p><strong>Product Source:</strong> ' . esc_html($showcase_data['product_source'] ?? 'manual') . '</p>';

		// Show product count based on source
		$product_count = 0;
		switch ( $showcase_data['product_source'] ?? 'manual' ) {
			case 'manual':
				$product_count = count($showcase_data['product_ids'] ?? []);
				break;
			case 'category':
				$product_count = count($showcase_data['category_ids'] ?? []);
				break;
			case 'tag':
				$product_count = count($showcase_data['tag_ids'] ?? []);
				break;
		}

		$preview_html .= '<p><strong>Selected Items:</strong> ' . $product_count . '</p>';
		$preview_html .= '<p style="color: #666; font-style: italic;">Full preview will be available when products are selected and shortcode system is integrated.</p>';
		$preview_html .= '</div>';

		return $preview_html;
	}

	/**
	 * Get default values from JSON file
	 */
	private function get_default_values_from_json() {
		$json_file = PRODDISP_PLUGIN_DIR . 'inc/admin/style-presets-defaults.json';

		if ( ! file_exists($json_file) ) {
			return array();
		}

		$json_content = file_get_contents($json_file);
		$data = json_decode($json_content, true);

		if ( json_last_error() !== JSON_ERROR_NONE || ! isset($data['default']) ) {
			return array();
		}

		return $data['default'];
	}

	/**
	 * Get preset values for specific layout mode
	 */
	private function get_preset_values_from_json( $layout_mode ) {
		$json_file = PRODDISP_PLUGIN_DIR . 'inc/admin/style-presets-defaults.json';

		if ( ! file_exists($json_file) ) {
			return array();
		}

		$json_content = file_get_contents($json_file);
		$data = json_decode($json_content, true);

		if ( json_last_error() !== JSON_ERROR_NONE || ! isset($data['presets'][ $layout_mode ]) ) {
			return array();
		}

		return $data['presets'][ $layout_mode ];
	}

	/**
	 * AJAX handler to get layout defaults for a specific layout and mode
	 */
	public function ajax_get_layout_defaults() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get layout and mode
		if ( ! isset($_POST['layout']) || ! isset($_POST['mode']) ) {
			wp_send_json_error( array(
				'message' => __( 'Layout and mode are required', 'product-display' ),
			) );
		}

		$layout = sanitize_text_field(wp_unslash($_POST['layout']));
		$mode = sanitize_text_field(wp_unslash($_POST['mode']));

		// Get default values
		$defaults = $this->get_default_values_from_json();

		// Get preset values for the specific layout mode
		$preset_values = $this->get_preset_values_from_json($mode);

		// Merge defaults with preset values (preset values override defaults)
		$merged_values = array_merge($defaults, $preset_values);

		wp_send_json_success( array(
			'defaults' => $merged_values,
			'layout' => $layout,
			'mode' => $mode,
		) );
	}


	/**
	 * AJAX handler to get custom icons
	 */
	public function ajax_get_custom_icons() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get custom icons from database
		$custom_icons = get_option('proddisp_custom_icons', array());

		wp_send_json_success( array(
			'icons' => $custom_icons,
		) );
	}

	/**
	 * AJAX handler to add custom icon
	 */
	public function ajax_add_custom_icon() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get icon data
		if ( ! isset($_POST['icon_class']) || ! isset($_POST['icon_name']) ) {
			wp_send_json_error( array(
				'message' => __( 'Icon class and name are required', 'product-display' ),
			) );
		}

		$icon_class = sanitize_text_field(wp_unslash($_POST['icon_class']));
		$icon_name = sanitize_text_field(wp_unslash($_POST['icon_name']));

		// Validate FontAwesome class format
		if ( ! preg_match('/^(fas|far|fab|fal|fad|fat)\s+fa-[\w-]+$/', $icon_class) ) {
			wp_send_json_error( array(
				'message' => __( 'Invalid FontAwesome class format', 'product-display' ),
			) );
		}

		// Get existing custom icons
		$custom_icons = get_option('proddisp_custom_icons', array());

		// Check if icon already exists
		foreach ( $custom_icons as $existing_icon ) {
			if ( $existing_icon['icon_class'] === $icon_class ) {
				wp_send_json_error( array(
					'message' => __( 'This icon already exists', 'product-display' ),
				) );
			}
		}

		// Add new icon
		$new_icon = array(
			'icon_class' => $icon_class,
			'icon_name' => $icon_name,
			'created' => time(),
		);

		$custom_icons[] = $new_icon;

		// Save to database
		update_option('proddisp_custom_icons', $custom_icons);

		wp_send_json_success( array(
			'message' => __( 'Custom icon added successfully', 'product-display' ),
			'icon' => $new_icon,
		) );
	}

	/**
	 * AJAX handler to remove custom icon
	 */
	public function ajax_remove_custom_icon() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		// Get icon class
		if ( ! isset($_POST['icon_class']) || empty($_POST['icon_class']) ) {
			wp_send_json_error( array(
				'message' => __( 'Icon class is required', 'product-display' ),
			) );
		}

		$icon_class = sanitize_text_field(wp_unslash($_POST['icon_class']));

		// Get existing custom icons
		$custom_icons = get_option('proddisp_custom_icons', array());

		// Find and remove the icon
		$found = false;
		foreach ( $custom_icons as $key => $icon ) {
			if ( $icon['icon_class'] === $icon_class ) {
				unset($custom_icons[ $key ]);
				$found = true;
				break;
			}
		}

		if ( ! $found ) {
			wp_send_json_error( array(
				'message' => __( 'Icon not found', 'product-display' ),
			) );
		}

		// Re-index array and save to database
		$custom_icons = array_values($custom_icons);
		update_option('proddisp_custom_icons', $custom_icons);

		wp_send_json_success( array(
			'message' => __( 'Custom icon removed successfully', 'product-display' ),
		) );
	}

	/**
	 * AJAX handler to get shop integrations
	 */
	public function ajax_get_shop_integrations() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		$shop_integration = PRODDISP_Shop_Integration::get_instance();
		$integrations = $shop_integration->get_integrations();
		$available_positions = $shop_integration->get_available_positions();

		wp_send_json_success( array(
			'integrations' => $integrations,
			'available_positions' => $available_positions,
		) );
	}

	/**
	 * AJAX handler to save shop integration
	 */
	public function ajax_save_shop_integration() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		$integration_data = array(
			'title'           => sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) ),
			'layout_id'       => sanitize_text_field( wp_unslash( $_POST['layout_id'] ?? '' ) ),
			'position'        => sanitize_text_field( wp_unslash( $_POST['position'] ?? '' ) ),
			'enabled'         => ! empty( $_POST['enabled'] ),
			'custom_class'    => sanitize_html_class( wp_unslash( $_POST['custom_class'] ?? '' ) ),
			'page_conditions' => array(),
		);

		// Process page conditions
		if ( ! empty( $_POST['page_conditions'] ) && is_array( $_POST['page_conditions'] ) ) {
			foreach ( wp_unslash( $_POST['page_conditions'] ) as $condition ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each item sanitized via sanitize_text_field() below.
				$integration_data['page_conditions'][] = array(
					'type' => sanitize_text_field( $condition ),
				);
			}
		}

		$shop_integration = PRODDISP_Shop_Integration::get_instance();

		$integration_id = sanitize_text_field( wp_unslash( $_POST['integration_id'] ?? '' ) );
		
		if ( empty($integration_id) ) {
			// Add new integration
			$result = $shop_integration->add_integration($integration_data);
		} else {
			// Update existing integration
			$result = $shop_integration->update_integration($integration_id, $integration_data);
		}

		if ( $result ) {
			wp_send_json_success(array(
				'message' => __('Integration saved successfully!', 'product-display')
			));
		} else {
			wp_send_json_error(array(
				'message' => __('Failed to save integration', 'product-display')
			));
		}
	}

	/**
	 * AJAX handler to delete shop integration
	 */
	public function ajax_delete_shop_integration() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		$integration_id = sanitize_text_field( wp_unslash( $_POST['integration_id'] ?? '' ) );

		if ( empty($integration_id) ) {
			wp_send_json_error(array(
				'message' => __('Invalid integration ID', 'product-display')
			));
		}

		$shop_integration = PRODDISP_Shop_Integration::get_instance();
		$result = $shop_integration->delete_integration($integration_id);

		if ( $result ) {
			wp_send_json_success(array(
				'message' => __('Integration deleted successfully!', 'product-display')
			));
		} else {
			wp_send_json_error(array(
				'message' => __('Failed to delete integration', 'product-display')
			));
		}
	}

	/**
	 * AJAX handler to get single shop integration
	 */
	public function ajax_get_shop_integration() {
		// Check permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array(
				'message' => __( 'You do not have permission to perform this action', 'product-display' ),
			) );
		}

		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array(
				'message' => __( 'Security check failed', 'product-display' ),
			) );
		}

		$integration_id = sanitize_text_field( wp_unslash( $_POST['integration_id'] ?? '' ) );
		
		if ( empty($integration_id) ) {
			wp_send_json_error(array(
				'message' => __('Invalid integration ID', 'product-display')
			));
		}

		$shop_integration = PRODDISP_Shop_Integration::get_instance();
		$integrations = $shop_integration->get_integrations();

		foreach ( $integrations as $integration ) {
			if ( $integration['id'] === $integration_id ) {
				wp_send_json_success($integration);
			}
		}

		wp_send_json_error(array(
			'message' => __('Integration not found', 'product-display')
		));
	}

	/**
	 * AJAX handler to get saved custom CSS for a showcase.
	 */
	public function ajax_get_custom_css() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied', 'product-display' ) ) );
		}

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed', 'product-display' ) ) );
		}

		$showcase_id = isset( $_POST['showcase_id'] ) ? absint( wp_unslash( $_POST['showcase_id'] ) ) : 0;

		if ( ! $showcase_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid showcase ID', 'product-display' ) ) );
		}

		$all_css = get_option( 'proddisp_custom_css', array() );
		$css     = isset( $all_css[ $showcase_id ] ) ? $all_css[ $showcase_id ] : '';

		wp_send_json_success( array( 'css' => $css ) );
	}

	/**
	 * AJAX handler to save custom CSS for a showcase.
	 */
	public function ajax_save_custom_css() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied', 'product-display' ) ) );
		}

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed', 'product-display' ) ) );
		}

		$showcase_id = isset( $_POST['showcase_id'] ) ? absint( wp_unslash( $_POST['showcase_id'] ) ) : 0;

		if ( ! $showcase_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid showcase ID', 'product-display' ) ) );
		}

		// Strip only literal HTML tags from the CSS, leaving all valid CSS syntax intact.
		// wp_strip_all_tags() is too aggressive and corrupts selectors/values.
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- CSS is stored as plain text and output via wp_add_inline_style(); not echoed directly.
		$raw_css = isset( $_POST['css'] ) ? wp_unslash( $_POST['css'] ) : '';
		$css     = preg_replace( '/<[^>]*>/', '', $raw_css );

		$all_css = get_option( 'proddisp_custom_css', array() );

		if ( '' === $css ) {
			unset( $all_css[ $showcase_id ] );
		} else {
			$all_css[ $showcase_id ] = $css;
		}

		update_option( 'proddisp_custom_css', $all_css );

		wp_send_json_success( array( 'message' => __( 'Custom CSS saved', 'product-display' ) ) );
	}
}

// Initialize admin class
PRODDISP_Admin::get_instance();
