<?php
/**
 * Astra Child Theme functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Astra Child
 * @since 1.0.0
 */

/**
 * Define Constants
 */
define( 'CHILD_THEME_ASTRA_CHILD_VERSION', '1.0.0' );

/**
 * Enqueue styles
 */
function child_enqueue_styles() {
	wp_enqueue_style(
		'astra-child-theme-css',
		get_stylesheet_directory_uri() . '/style.css',
		array( 'astra-theme-css' ),
		CHILD_THEME_ASTRA_CHILD_VERSION,
		'all'
	);
}
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );

/**
 * WooCommerce CSV Importer: add "Slug" mapping option and map CSV column "post_name"
 * so you can control product URLs during import.
 *
 * CSV column name recommended: post_name
 * Example value: yonder-751-straw-bottle
 */
add_filter( 'woocommerce_csv_product_import_mapping_options', function( $options ) {
	// Add a visible option in the importer dropdown.
	$options['post_name'] = 'Slug';
	return $options;
} );

add_filter( 'woocommerce_csv_product_import_mapping_default_columns', function( $columns ) {
	// Auto-detect CSV header "post_name" and map it to WP's post_name (slug).
	$columns['post_name'] = 'post_name';
	return $columns;
} );

/**
 * Ensure the imported value actually gets saved into the product slug (post_name).
 * Some WooCommerce versions treat unknown columns as meta; this forces it into post_name.
 */
add_filter( 'woocommerce_product_import_pre_insert_product_object', function( $product, $data ) {

	// $data contains parsed CSV row. Try both keys in case you name the column differently.
	$maybe_slug = '';
	if ( ! empty( $data['post_name'] ) ) {
		$maybe_slug = $data['post_name'];
	} elseif ( ! empty( $data['slug'] ) ) {
		$maybe_slug = $data['slug'];
	}

	if ( $maybe_slug ) {
		$maybe_slug = sanitize_title( $maybe_slug );
		if ( $maybe_slug ) {
			$product->set_slug( $maybe_slug );
		}
	}

	return $product;
}, 10, 2 );