<?php

namespace Brandy\Niches\Import;

use Brandy\Admin\Pages\Dashboard\ImportService;

/**
 * Imports sample posts for a niche.
 *
 * Extracted verbatim from NicheService as part of the behavior-preserving
 * decomposition. Owns post creation, meta, comments and featured images.
 */
class PostImporter {

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

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

	public function import( $builder = 'gutenberg' ) {
		if ( empty( $this->selected_niche ) ) {
			return array();
		}

		$niche_id     = $this->selected_niche['id'];
		$sample_posts = $this->get_sample_posts( $builder );

		if ( empty( $sample_posts ) ) {
			return array();
		}

		do_action( 'brandy_before_import_posts', $niche_id, $sample_posts );

		$existing_posts     = $this->get_existing_posts( $sample_posts );
		$existed_posts_name = wp_list_pluck( $existing_posts->posts, 'post_name' );

		$not_existed_posts = array_filter(
			$sample_posts,
			function( $post_info ) use ( $existed_posts_name ) {
				return ! in_array( $post_info['name'], $existed_posts_name, true );
			}
		);

		$inserted_posts = array();
		foreach ( $not_existed_posts as $post_info ) {
			$inserted_id = $this->insert_post( $post_info, $niche_id, $builder );
			if ( $inserted_id ) {
				$inserted_posts[] = $inserted_id;
			}
		}

		do_action( 'brandy_after_import_posts', $niche_id, $inserted_posts );

		return $inserted_posts;
	}

	private function get_sample_posts( $builder ) {
		if ( ! isset( $this->selected_niche['sample_posts'][ $builder ] ) ||
			 ! file_exists( $this->selected_niche['sample_posts'][ $builder ] ) ) {
			return array();
		}

		$csv_file = $this->selected_niche['sample_posts'][ $builder ];
		return ImportService::read_posts_from_csv( $csv_file );
	}

	private function get_existing_posts( $sample_posts ) {
		return new \WP_Query(
			array(
				'post_type'     => 'post',
				'post_name__in' => array_map(
					function( $p ) {
						return $p['name'];
					},
					$sample_posts
				),
			)
		);
	}

	private function insert_post( $post_info, $niche_id, $builder ) {
		$comment_status = isset( $post_info['comment_status'] ) ?
			( empty( $post_info['comment_status'] ) ? 'closed' : 'open' ) : 'open';
		$comments       = isset( $post_info['comments'] ) ? $post_info['comments'] : array();

		$post_args = array(
			'post_title'     => $post_info['title'],
			'post_type'      => 'post',
			'post_name'      => $post_info['name'],
			'post_content'   => $post_info['content'],
			'post_status'    => 'publish',
			'comment_status' => $comment_status,
			'ping_status'    => 'closed',
			'post_author'    => 1,
			'menu_order'     => 0,
		);

		$inserted_id = wp_insert_post( $post_args );

		if ( 0 === $inserted_id || is_wp_error( $inserted_id ) ) {
			return false;
		}

		$this->add_post_meta( $inserted_id, $post_info['post_meta'] );
		$this->add_post_meta( $inserted_id, array(
			'_brandy_demo' => 'yes'
		) );
		$this->add_comments( $inserted_id, $comments );

		$category_ids = $post_info['post_category'] ?? [];
    	$tag_ids = [];

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

		// 3. Create/find tags
		foreach ($post_info['tags_input'] as $tag_name) {
			$tag_name = trim($tag_name);

			if ($tag_name === '') {
				continue;
			}

			$term = term_exists($tag_name, 'post_tag');

			if (!$term) {
				$term = wp_insert_term($tag_name, 'post_tag');
			}

			if (!is_wp_error($term)) {
				$term_id = is_array($term) ? (int) $term['term_id'] : (int) $term;

				$tag_ids[] = $term_id;

				// Add your custom key to this tag
				update_term_meta($term_id, '_brandy_demo', 'yes');
			}
		}

		// 4. Assign categories/tags to post
		if (!empty($category_ids)) {
			wp_set_post_terms($inserted_id, $category_ids, 'category');
		}

		if (!empty($tag_ids)) {
			wp_set_post_terms($inserted_id, $tag_ids, 'post_tag');
		}

		do_action( 'brandy_after_import_post', $niche_id, $builder, $inserted_id, $post_info );

		ImportService::add_featured_image(
			$inserted_id,
			$post_info['featured_image'] ?? '',
			$post_info['name'] ?? ''
		);

		return $inserted_id;
	}

	private function add_post_meta( $post_id, $post_meta ) {
		if ( empty( $post_meta ) ) {
			return;
		}

		foreach ( $post_meta as $key => $value ) {
			update_post_meta( $post_id, $key, $value );
		}
	}

	private function add_comments( $post_id, $comments ) {
		foreach ( $comments as $comment ) {
			wp_insert_comment(
				array(
					'comment_post_ID' => $post_id,
					'comment_content' => $comment,
				)
			);
		}
	}
}
