<?php
/**
 * Demo import for Kids Toys Store.
 *
 * @package Kids Toys Store
 */

add_action( 'wp_ajax_kids_toys_store_run_demo_import', 'kids_toys_store_run_demo_import' );

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

	$kids_toys_store_category_ids = kids_toys_store_create_demo_categories();
	$kids_toys_store_products     = kids_toys_store_get_demo_products();

	if ( get_option( 'kids_toys_store_demo_import_completed' ) ) {
		kids_toys_store_assign_categories_to_demo_products( $kids_toys_store_products, $kids_toys_store_category_ids );
		return true;
	}

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

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

		update_post_meta( $kids_toys_store_product_id, '_regular_price', $kids_toys_store_product['price'] );
		update_post_meta( $kids_toys_store_product_id, '_price', $kids_toys_store_product['price'] );

		if ( ! empty( $kids_toys_store_category_ids ) ) {
			wp_set_object_terms(
				$kids_toys_store_product_id,
				$kids_toys_store_category_ids,
				'product_cat'
			);
		}

		if ( ! empty( $kids_toys_store_product['image'] ) && file_exists( $kids_toys_store_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';
			}

			$kids_toys_store_tmp_file = wp_tempnam( $kids_toys_store_product['image'] );
			if ( $kids_toys_store_tmp_file ) {
				copy( $kids_toys_store_product['image'], $kids_toys_store_tmp_file );
				$kids_toys_store_file_array = array(
					'name'     => basename( $kids_toys_store_product['image'] ),
					'tmp_name' => $kids_toys_store_tmp_file,
				);

				$kids_toys_store_attachment_id = media_handle_sideload( $kids_toys_store_file_array, $kids_toys_store_product_id );

				if ( is_wp_error( $kids_toys_store_attachment_id ) ) {
					@unlink( $kids_toys_store_tmp_file );
				} else {
					set_post_thumbnail( $kids_toys_store_product_id, $kids_toys_store_attachment_id );
				}
			}
		}
	}

	kids_toys_store_assign_categories_to_demo_products( $kids_toys_store_products, $kids_toys_store_category_ids );

	update_option( 'kids_toys_store_demo_import_completed', true );

	return true;
}

/**
 * Create demo product categories and return their IDs.
 *
 * @return array<int>
 */
function kids_toys_store_create_demo_categories() {
	$kids_toys_store_categories = array(
		array(
			'name' => 'Action Figures',
			'slug' => 'action-figures',
		),
		array(
			'name' => 'Building Blocks',
			'slug' => 'building-blocks',
		),
		array(
			'name' => 'Learning Toys',
			'slug' => 'learning-toys',
		),
		array(
			'name' => 'Outdoor Toys',
			'slug' => 'outdoor-toys',
		),
	);

	$kids_toys_store_category_ids = array();

	foreach ( $kids_toys_store_categories as $kids_toys_store_cat ) {
		$kids_toys_store_term = term_exists( $kids_toys_store_cat['slug'], 'product_cat' );

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

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

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

	return $kids_toys_store_category_ids;
}

/**
 * Get demo product definitions.
 *
 * @return array<int, array<string, string>>
 */
function kids_toys_store_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>> $kids_toys_store_products Demo products.
 * @param array<int>                        $kids_toys_store_category_ids Demo category IDs.
 */
function kids_toys_store_assign_categories_to_demo_products( $kids_toys_store_products, $kids_toys_store_category_ids ) {
	if ( empty( $kids_toys_store_category_ids ) ) {
		return;
	}

	foreach ( $kids_toys_store_products as $kids_toys_store_product ) {
		if ( empty( $kids_toys_store_product['title'] ) ) {
			continue;
		}

		$kids_toys_store_product_slug = sanitize_title( $kids_toys_store_product['title'] );
		$kids_toys_store_existing_product = get_page_by_path( $kids_toys_store_product_slug, OBJECT, 'product' );

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

/**
 * Import demo products for Kids Toys Store.
 */
function kids_toys_store_run_demo_import() {
	check_ajax_referer( 'kids_toys_store_demo_nonce', 'nonce' );

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

	$result = kids_toys_store_import_demo_products_data();

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

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

	wp_send_json_success( 'Demo data processed successfully' );
}
