<?php
/**
 * Demo import for Jewelry Market.
 *
 * @package Jewelry Market
 */

add_action( 'wp_ajax_jewelry_market_run_demo_import', 'jewelry_market_run_demo_import' );

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

	$jewelry_market_category_ids = jewelry_market_create_demo_categories();
	$jewelry_market_products     = jewelry_market_get_demo_products();

	if ( get_option( 'jewelry_market_demo_import_completed' ) ) {
		jewelry_market_assign_categories_to_demo_products( $jewelry_market_products, $jewelry_market_category_ids );
		return true;
	}

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

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

		update_post_meta( $jewelry_market_product_id, '_regular_price', $jewelry_market_product['price'] );
		update_post_meta( $jewelry_market_product_id, '_price', $jewelry_market_product['price'] );

		if ( ! empty( $jewelry_market_category_ids ) ) {
			wp_set_object_terms(
				$jewelry_market_product_id,
				$jewelry_market_category_ids,
				'product_cat'
			);
		}

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

			$jewelry_market_tmp_file = wp_tempnam( $jewelry_market_product['image'] );
			if ( $jewelry_market_tmp_file ) {
				copy( $jewelry_market_product['image'], $jewelry_market_tmp_file );
				$jewelry_market_file_array = array(
					'name'     => basename( $jewelry_market_product['image'] ),
					'tmp_name' => $jewelry_market_tmp_file,
				);

				$jewelry_market_attachment_id = media_handle_sideload( $jewelry_market_file_array, $jewelry_market_product_id );

				if ( is_wp_error( $jewelry_market_attachment_id ) ) {
					@unlink( $jewelry_market_tmp_file );
				} else {
					set_post_thumbnail( $jewelry_market_product_id, $jewelry_market_attachment_id );
				}
			}
		}
	}

	jewelry_market_assign_categories_to_demo_products( $jewelry_market_products, $jewelry_market_category_ids );

	update_option( 'jewelry_market_demo_import_completed', true );

	return true;
}

/**
 * Create demo product categories and return their IDs.
 *
 * @return array<int>
 */
function jewelry_market_create_demo_categories() {
	$jewelry_market_categories = array(
		array(
			'name' => 'Eternal Diamond Collection',
			'slug' => 'eternal-diamond-collection',
		),
		array(
			'name' => 'Bridal Radiance',
			'slug' => 'bridal-radiance',
		),
		array(
			'name' => 'Modern Minimal',
			'slug' => 'modern-minimal',
		),
		array(
			'name' => 'Golden Heritage',
			'slug' => 'golden-heritage',
		),
	);

	$jewelry_market_category_ids = array();

	foreach ( $jewelry_market_categories as $jewelry_market_cat ) {
		$jewelry_market_term = term_exists( $jewelry_market_cat['slug'], 'product_cat' );

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

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

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

	return $jewelry_market_category_ids;
}

/**
 * Get demo product definitions.
 *
 * @return array<int, array<string, string>>
 */
function jewelry_market_get_demo_products() {
	return array(
		array(
			'title'             => 'Traditional Gold Bangle Set',
			'price'             => '24.99',
			'image'             => get_template_directory() . '/assets/images/service01.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'             => 'Gold Temple Necklace',
			'price'             => '29.99',
			'image'             => get_template_directory() . '/assets/images/service02.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'             => 'Antique Gold Earrings',
			'price'             => '14.99',
			'image'             => get_template_directory() . '/assets/images/service03.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'             => 'Minimal Chain Necklace',
			'price'             => '34.99',
			'image'             => get_template_directory() . '/assets/images/service04.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'             => 'Minimal Silver Ring',
			'price'             => '19.99',
			'image'             => get_template_directory() . '/assets/images/service03.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.',
		),
		array(
			'title'             => 'Minimalist Silver Pendant',
			'price'             => '14.99',
			'image'             => get_template_directory() . '/assets/images/service04.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.',
		),
		array(
			'title'             => 'Bridal Gold Ring',
			'price'             => '15.99',
			'image'             => get_template_directory() . '/assets/images/service02.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.',
		),
		array(
			'title'             => 'Bridal Gold Earrings',
			'price'             => '17.99',
			'image'             => get_template_directory() . '/assets/images/service01.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.',
		),
		array(
			'title'             => 'Bridal Gold Necklace Set',
			'price'             => '68.99',
			'image'             => get_template_directory() . '/assets/images/service02.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.',
		),
		array(
			'title'             => 'Diamond Solitaire Ring',
			'price'             => '75.99',
			'image'             => get_template_directory() . '/assets/images/service01.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.',
		),
		array(
			'title'             => 'Diamond Necklace',
			'price'             => '33.99',
			'image'             => get_template_directory() . '/assets/images/service02.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.',
		),
		array(
			'title'             => 'Diamond Earrings',
			'price'             => '23.99',
			'image'             => get_template_directory() . '/assets/images/service04.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>> $jewelry_market_products Demo products.
 * @param array<int>                        $jewelry_market_category_ids Demo category IDs.
 */
function jewelry_market_assign_categories_to_demo_products( $jewelry_market_products, $jewelry_market_category_ids ) {
	if ( empty( $jewelry_market_category_ids ) ) {
		return;
	}

	foreach ( $jewelry_market_products as $jewelry_market_product ) {
		if ( empty( $jewelry_market_product['title'] ) ) {
			continue;
		}

		$jewelry_market_product_slug = sanitize_title( $jewelry_market_product['title'] );
		$jewelry_market_existing_product = get_page_by_path( $jewelry_market_product_slug, OBJECT, 'product' );

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

/**
 * Import demo products for Jewelry Market.
 */
function jewelry_market_run_demo_import() {
	check_ajax_referer( 'jewelry_market_demo_nonce', 'nonce' );

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

	$result = jewelry_market_import_demo_products_data();

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

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

	wp_send_json_success( 'Demo data processed successfully' );
}
