<?php

namespace Brandy\Niches\Import;

use Brandy\Admin\Pages\Dashboard\ImportService;

/**
 * Imports sample products, product categories, category images and reviews.
 *
 * Extracted verbatim from NicheService as part of the behavior-preserving
 * decomposition.
 */
class CommerceImporter {

	/**
	 * Selected niche import data.
	 *
	 * @var array
	 */
	private $selected_niche;

	public function __construct( $selected_niche ) {
		$this->selected_niche = $selected_niche;
	}

	public function import_products() {
		if ( empty( $this->selected_niche ) ) {
			return array();
		}

		if ( ! isset( $this->selected_niche['sample_products'] ) || ! file_exists( $this->selected_niche['sample_products'] ) ) {
			return array();
		}

		$csv_file = $this->selected_niche['sample_products'];

		if ( ! file_exists( $csv_file ) ) {
			return array();
		}

		$imported_products = ImportService::read_products_from_csv( $csv_file );

		if ( ! empty( $imported_products['imported'] ) ) {
			foreach ( $imported_products['imported'] as $imported_id ) {
				update_post_meta( $imported_id, '_brandy_demo', 'yes' );

				$category_ids = wp_get_post_terms($imported_id, 'product_cat', [
					'fields' => 'ids',
				]);

				if (!is_wp_error($category_ids)) {
					foreach ($category_ids as $term_id) {
						update_term_meta($term_id, '_brandy_demo', 'yes');
					}
				}

				// 3. Mark product tags.
				$tag_ids = wp_get_post_terms($imported_id, 'product_tag', [
					'fields' => 'ids',
				]);

				if (!is_wp_error($tag_ids)) {
					foreach ($tag_ids as $term_id) {
						update_term_meta($term_id, '_brandy_demo', 'yes');
					}
				}
			}

		}

		return $imported_products;
	}

	public function import_categories() {
		if ( empty( $this->selected_niche ) ) {
			return array();
		}

		$this->import_category_images();
		$reviewed_product_ids = $this->add_sample_product_reviews();

		do_action( 'brandy_after_import_products', $this->selected_niche['id'] );

		return $reviewed_product_ids;
	}

	private function import_category_images() {
		$category_images_file = $this->selected_niche['sample_product_category_images'] ?? '';
		if ( ! file_exists( $category_images_file ) ) {
			return;
		}

		try {
			$images_data = json_decode( file_get_contents( $category_images_file ) ) ?: array();
		} catch ( \Error $error ) {
			return;
		}

		foreach ( $images_data as $cat_slug => $img_source ) {
			$cat = get_term_by( 'slug', $cat_slug, 'product_cat' );
			if ( empty( $cat ) || empty( $cat->term_id ) || empty( $img_source ) ) {
				continue;
			}

			if ( ! empty( \get_term_meta( $cat->term_id, 'thumbnail_id' ) ) ) {
				continue;
			}

			try {
				$image_id = media_sideload_image( $img_source, 0, '', 'id' );
				if ( ! is_wp_error( $image_id ) ) {
					\update_term_meta( $cat->term_id, 'thumbnail_id', absint( $image_id ) );
				}
			} catch ( \Error $error ) {
				continue;
			}
		}
	}

	private function add_sample_product_reviews() {
		$sample_ratings = array(
			array(
				'rate'   => 4,
				'review' => __( 'Great product! It exceeded my expectations in quality and performance. The only downside is the packaging, which could be more eco-friendly.', 'brandy' ),
			),
			array(
				'rate'   => 3,
				'review' => __( 'Decent product but not worth the price. It works as advertised, but I found similar options for less money. Customer service was helpful, though.', 'brandy' ),
			),
			array(
				'rate'   => 5,
				'review' => __( 'Absolutely love this product! It has made my daily routine so much easier. Highly recommend to anyone looking for reliability and efficiency.', 'brandy' ),
			),
			array(
				'rate'   => 4,
				'review' => __( "Very good product overall. It's sturdy and performs well, but it took a bit longer to arrive than I expected. Still, I'd buy it again!", 'brandy' ),
			),
			array(
				'rate'   => 1,
				'review' => __( "Disappointed with this product. It didn't work as promised, and I had issues with durability. Customer support was slow to respond, which made it worse.", 'brandy' ),
			),
		);

		try {
			$product_ids = $this->get_tagged_product_ids();
			$this->add_reviews_to_products( $product_ids, $sample_ratings );
			return $product_ids;
		} catch ( \Error $error ) {
			return array();
		}
	}

	private function get_tagged_product_ids() {
		$product_tags_ids = get_terms(
			array(
				'taxonomy' => 'product_tag',
				'fields'   => 'ids',
				'meta_query' => [
					'relation' => 'OR',
					[
						'key'     => '_brandy_demo',
						'value'   => 'yes',
						'compare' => '=',
					],
				],
			)
		);

		$query = new \WP_Query(
			array(
				'posts_per_page' => -1,
				'tax_query'      => array(
					'relation' => 'AND',
					array(
						'taxonomy' => 'product_tag',
						'field'    => 'id',
						'terms'    => $product_tags_ids,
					),
				),
				'post_type'      => 'product',
				'orderby'        => 'title',
				'fields'         => 'ids',
			)
		);

		return $query->posts;
	}

	private function add_reviews_to_products( $product_ids, $sample_ratings ) {
		foreach ( $product_ids as $id ) {
			$random_rating_indexes = array_rand( $sample_ratings, wp_rand( 2, 4 ) );
			foreach ( $random_rating_indexes as $random_index ) {
				if ( empty( $sample_ratings[ $random_index ] ) ) {
					continue;
				}

				$rating_data = $sample_ratings[ $random_index ];
				$comment_id  = wp_new_comment(
					array(
						'comment_post_ID'      => $id,
						'comment_content'      => $rating_data['review'],
						'comment_type'         => 'review',
						'comment_approved'     => true,
						'user_ID'              => get_current_user_id(),
						'comment_author_email' => '',
						'comment_author'       => wp_get_current_user()->display_name,
						'comment_author_url'   => '#',
					)
				);

				if ( $comment_id && ! is_wp_error( $comment_id ) ) {
					add_comment_meta( $comment_id, 'rating', $rating_data['rate'], true );
				}
			}
		}
	}
}
