<?php
/**
 * Demo import for Chocolate House.
 *
 * @package Chocolate House
 */

add_action( 'wp_ajax_chocolate_house_run_demo_import', 'chocolate_house_run_demo_import' );

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

	$chocolate_house_category_ids = chocolate_house_create_demo_categories();
	$chocolate_house_products     = chocolate_house_get_demo_products();

	if ( get_option( 'chocolate_house_demo_import_completed' ) ) {
		chocolate_house_assign_categories_to_demo_products( $chocolate_house_products, $chocolate_house_category_ids );
		return true;
	}

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

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

		update_post_meta( $chocolate_house_product_id, '_regular_price', $chocolate_house_product['price'] );
		update_post_meta( $chocolate_house_product_id, '_price', $chocolate_house_product['price'] );

		if ( ! empty( $chocolate_house_category_ids ) ) {
			wp_set_object_terms(
				$chocolate_house_product_id,
				$chocolate_house_category_ids,
				'product_cat'
			);
		}

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

			$chocolate_house_tmp_file = wp_tempnam( $chocolate_house_product['image'] );
			if ( $chocolate_house_tmp_file ) {
				copy( $chocolate_house_product['image'], $chocolate_house_tmp_file );
				$chocolate_house_file_array = array(
					'name'     => basename( $chocolate_house_product['image'] ),
					'tmp_name' => $chocolate_house_tmp_file,
				);

				$chocolate_house_attachment_id = media_handle_sideload( $chocolate_house_file_array, $chocolate_house_product_id );

				if ( is_wp_error( $chocolate_house_attachment_id ) ) {
					@unlink( $chocolate_house_tmp_file );
				} else {
					set_post_thumbnail( $chocolate_house_product_id, $chocolate_house_attachment_id );
				}
			}
		}
	}

	chocolate_house_assign_categories_to_demo_products( $chocolate_house_products, $chocolate_house_category_ids );

	update_option( 'chocolate_house_demo_import_completed', true );

	return true;
}

/**
 * Create demo product categories and return their IDs.
 *
 * @return array<int>
 */
function chocolate_house_create_demo_categories() {
	$chocolate_house_categories = array(
		array(
			'name' => 'Chocolate Bars',
			'slug' => 'chocolate-bars',
		),
		array(
			'name' => 'Truffles',
			'slug' => 'truffles',
		),
		array(
			'name' => 'Gift Boxes',
			'slug' => 'gift-boxes',
		),
		array(
			'name' => 'Dark Collection',
			'slug' => 'dark-collection',
		),
	);

	$chocolate_house_category_ids = array();

	foreach ( $chocolate_house_categories as $chocolate_house_cat ) {
		$chocolate_house_term = term_exists( $chocolate_house_cat['slug'], 'product_cat' );

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

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

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

	return $chocolate_house_category_ids;
}

/**
 * Get demo product definitions.
 *
 * @return array<int, array<string, string>>
 */
function chocolate_house_get_demo_products() {
	return array(
		array(
			'title'             => 'Classic Milk Chocolate Bar',
			'price'             => '9.99',
			'image'             => get_template_directory() . '/assets/images/product-img1.png',
			'short_description' => 'Smooth milk chocolate crafted in small batches.',
			'description'       => 'A rich and creamy milk chocolate bar made from premium cocoa beans with a velvety finish.',
		),
		array(
			'title'             => 'Dark Cocoa Delight',
			'price'             => '11.99',
			'image'             => get_template_directory() . '/assets/images/product-img2.png',
			'short_description' => 'Deep cocoa profile with balanced sweetness.',
			'description'       => 'Intense dark chocolate made for true cocoa lovers, with subtle roasted notes and clean finish.',
		),
		array(
			'title'             => 'Hazelnut Praline Truffles',
			'price'             => '14.99',
			'image'             => get_template_directory() . '/assets/images/product-img1.png',
			'short_description' => 'Soft truffles with crunchy hazelnut center.',
			'description'       => 'Delicate truffles filled with silky praline and coated in premium chocolate.',
		),
		array(
			'title'             => 'Luxury Gift Chocolate Box',
			'price'             => '24.99',
			'image'             => get_template_directory() . '/assets/images/product-img2.png',
			'short_description' => 'Assorted gourmet chocolates for gifting.',
			'description'       => 'Handpicked assortment of artisan chocolates in an elegant box, perfect for special occasions.',
		),
		array(
			'title'             => 'Sea Salt Caramel Squares',
			'price'             => '12.99',
			'image'             => get_template_directory() . '/assets/images/product-img1.png',
			'short_description' => 'Sweet caramel with a hint of sea salt.',
			'description'       => 'Signature caramel chocolate squares that blend sweetness and salt for a bold taste.',
		),
		array(
			'title'             => 'Premium Cocoa Collection',
			'price'             => '29.99',
			'image'             => get_template_directory() . '/assets/images/product-img2.png',
			'short_description' => 'Curated collection of best-selling chocolates.',
			'description'       => 'A complete tasting set featuring milk, dark, praline and specialty chocolates.',
		),
	);
}

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

	foreach ( $chocolate_house_products as $chocolate_house_product ) {
		if ( empty( $chocolate_house_product['title'] ) ) {
			continue;
		}

		$chocolate_house_product_slug = sanitize_title( $chocolate_house_product['title'] );
		$chocolate_house_existing_product = get_page_by_path( $chocolate_house_product_slug, OBJECT, 'product' );

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

/**
 * Import demo products for Chocolate House.
 */
function chocolate_house_run_demo_import() {
	check_ajax_referer( 'chocolate_house_demo_nonce', 'nonce' );

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

	$result = chocolate_house_import_demo_products_data();

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

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

	wp_send_json_success( 'Demo data processed successfully' );
}
