<?php
/**
 * Demo import for Herbal Products Shop.
 *
 * @package Herbal Products Shop
 */

add_action( 'wp_ajax_herbal_products_shop_run_demo_import', 'herbal_products_shop_run_demo_import' );

/**
 * Import demo products and categories.
 *
 * @return true|WP_Error
 */
function herbal_products_shop_import_demo_products_data() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return new WP_Error( 'woocommerce_not_active', 'WooCommerce not active' );
	}

	$herbal_products_shop_category_ids = herbal_products_shop_create_demo_categories();
	$herbal_products_shop_products     = herbal_products_shop_get_demo_products();

	if ( get_option( 'herbal_products_shop_demo_import_completed' ) ) {
		herbal_products_shop_assign_categories_to_demo_products( $herbal_products_shop_products, $herbal_products_shop_category_ids );
		return true;
	}

	foreach ( $herbal_products_shop_products as $herbal_products_shop_product ) {
		$herbal_products_shop_product_id = wp_insert_post(
			array(
				'post_title'   => $herbal_products_shop_product['title'],
				'post_content' => $herbal_products_shop_product['description'],
				'post_excerpt' => $herbal_products_shop_product['short_description'],
				'post_status'  => 'publish',
				'post_type'    => 'product',
			)
		);

		if ( is_wp_error( $herbal_products_shop_product_id ) ) {
			continue;
		}

		update_post_meta( $herbal_products_shop_product_id, '_regular_price', $herbal_products_shop_product['price'] );
		update_post_meta( $herbal_products_shop_product_id, '_price', $herbal_products_shop_product['price'] );

		if ( ! empty( $herbal_products_shop_category_ids ) ) {
			wp_set_object_terms(
				$herbal_products_shop_product_id,
				$herbal_products_shop_category_ids,
				'product_cat'
			);
		}

		if ( ! empty( $herbal_products_shop_product['image'] ) && file_exists( $herbal_products_shop_product['image'] ) ) {
			if ( ! function_exists( 'media_handle_sideload' ) ) {
				require_once ABSPATH . 'wp-admin/includes/media.php';
				require_once ABSPATH . 'wp-admin/includes/file.php';
				require_once ABSPATH . 'wp-admin/includes/image.php';
			}

			$herbal_products_shop_tmp_file = wp_tempnam( $herbal_products_shop_product['image'] );
			if ( $herbal_products_shop_tmp_file ) {
				copy( $herbal_products_shop_product['image'], $herbal_products_shop_tmp_file );
				$herbal_products_shop_file_array = array(
					'name'     => basename( $herbal_products_shop_product['image'] ),
					'tmp_name' => $herbal_products_shop_tmp_file,
				);

				$herbal_products_shop_attachment_id = media_handle_sideload( $herbal_products_shop_file_array, $herbal_products_shop_product_id );

				if ( is_wp_error( $herbal_products_shop_attachment_id ) ) {
					@unlink( $herbal_products_shop_tmp_file );
				} else {
					set_post_thumbnail( $herbal_products_shop_product_id, $herbal_products_shop_attachment_id );
				}
			}
		}
	}

	herbal_products_shop_assign_categories_to_demo_products( $herbal_products_shop_products, $herbal_products_shop_category_ids );

	update_option( 'herbal_products_shop_demo_import_completed', true );

	return true;
}

/**
 * Create demo product categories and return their IDs.
 *
 * @return array<int>
 */
function herbal_products_shop_create_demo_categories() {
	$herbal_products_shop_categories = array(
		array(
			'name' => 'Herbal Care',
			'slug' => 'herbal-care',
		),
		array(
			'name' => 'Skin Essentials',
			'slug' => 'skin-essentials',
		),
		array(
			'name' => 'Natural Oils',
			'slug' => 'natural-oils',
		),
		array(
			'name' => 'Wellness Kits',
			'slug' => 'wellness-kits',
		),
	);

	$herbal_products_shop_category_ids = array();

	foreach ( $herbal_products_shop_categories as $herbal_products_shop_cat ) {
		$herbal_products_shop_term = term_exists( $herbal_products_shop_cat['slug'], 'product_cat' );

		if ( ! $herbal_products_shop_term ) {
			$herbal_products_shop_term = wp_insert_term(
				$herbal_products_shop_cat['name'],
				'product_cat',
				array(
					'slug' => $herbal_products_shop_cat['slug'],
				)
			);
		}

		if ( is_wp_error( $herbal_products_shop_term ) ) {
			continue;
		}

		if ( is_array( $herbal_products_shop_term ) && isset( $herbal_products_shop_term['term_id'] ) ) {
			$herbal_products_shop_category_ids[] = (int) $herbal_products_shop_term['term_id'];
		} else {
			$herbal_products_shop_category_ids[] = (int) $herbal_products_shop_term;
		}
	}

	return $herbal_products_shop_category_ids;
}

/**
 * Get demo product definitions.
 *
 * @return array<int, array<string, string>>
 */
function herbal_products_shop_get_demo_products() {
	return array(
		array(
			'title'             => 'Racing Turbo Car',
			'price'             => '24.99',
			'image'             => get_template_directory() . '/assets/images/product01.png',
			'short_description' => 'Speed toy car with sturdy body and bright finish.',
			'description'       => 'A fun racing car toy built for active play, with smooth wheels and child-friendly materials.',
		),
		array(
			'title'             => 'Color Brick Builder Set',
			'price'             => '29.99',
			'image'             => get_template_directory() . '/assets/images/product02.png',
			'short_description' => 'Creative block set for imagination and motor skills.',
			'description'       => 'This building block kit helps kids create towers, houses, and shapes while improving hand-eye coordination.',
		),
		array(
			'title'             => 'Junior Puzzle Board',
			'price'             => '14.99',
			'image'             => get_template_directory() . '/assets/images/product03.png',
			'short_description' => 'Colorful puzzle board designed for early learners.',
			'description'       => 'A beginner-friendly puzzle that encourages problem solving and pattern matching through play.',
		),
		array(
			'title'             => 'Adventure Play Tent',
			'price'             => '34.99',
			'image'             => get_template_directory() . '/assets/images/product04.png',
			'short_description' => 'Foldable indoor tent for pretend adventures.',
			'description'       => 'Easy to set up and store, this play tent creates a cozy space for games, stories, and imagination.',
		),
		array(
			'title'             => 'Mini Sports Ball Pack',
			'price'             => '19.99',
			'image'             => get_template_directory() . '/assets/images/product05.png',
			'short_description' => 'Soft toy ball set for safe indoor and outdoor play.',
			'description'       => 'A pack of lightweight balls perfect for throwing, catching, and improving active movement skills.',
		),
	);
}

/**
 * Ensure all demo products are assigned to demo categories.
 *
 * @param array<int, array<string, string>> $herbal_products_shop_products Demo products.
 * @param array<int>                        $herbal_products_shop_category_ids Demo category IDs.
 */
function herbal_products_shop_assign_categories_to_demo_products( $herbal_products_shop_products, $herbal_products_shop_category_ids ) {
	if ( empty( $herbal_products_shop_category_ids ) ) {
		return;
	}

	foreach ( $herbal_products_shop_products as $herbal_products_shop_product ) {
		if ( empty( $herbal_products_shop_product['title'] ) ) {
			continue;
		}

		$herbal_products_shop_product_slug = sanitize_title( $herbal_products_shop_product['title'] );
		$herbal_products_shop_existing_product = get_page_by_path( $herbal_products_shop_product_slug, OBJECT, 'product' );

		if ( $herbal_products_shop_existing_product && ! empty( $herbal_products_shop_existing_product->ID ) ) {
			wp_set_object_terms(
				(int) $herbal_products_shop_existing_product->ID,
				$herbal_products_shop_category_ids,
				'product_cat'
			);
		}
	}
}

/**
 * Import demo products for Herbal Products Shop.
 */
function herbal_products_shop_run_demo_import() {
	check_ajax_referer( 'herbal_products_shop_demo_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Permission denied' );
	}

	$result = herbal_products_shop_import_demo_products_data();

	if ( is_wp_error( $result ) ) {
		wp_send_json_error( $result->get_error_message() );
	}

	if ( get_option( 'herbal_products_shop_demo_import_completed' ) ) {
		wp_send_json_success( 'Demo imported successfully' );
	}

	wp_send_json_success( 'Demo data processed successfully' );
}
