<?php

namespace Brandy\Niches\Import;

use Brandy\Admin\Pages\Dashboard\ImportService;
use Brandy\Admin\PostEditor\PostMetaServices;

/**
 * Imports sample pages (default + niche-specific) and wires up special page
 * options (front page, blog, shop, cart, checkout, etc.).
 *
 * Extracted verbatim from NicheService as part of the behavior-preserving
 * decomposition.
 */
class PageImporter {

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

	/**
	 * Post meta services, used to clear existing page meta before re-import.
	 *
	 * @var PostMetaServices
	 */
	private $post_meta_services;

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

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

		$niche_id       = $this->selected_niche['id'];
		$imported_pages = array();
		$inserted_pages = array();

		// Get and merge sample pages from default and niche-specific sources
		$sample_pages = $this->get_merged_sample_pages( $builder );

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

		do_action( 'brandy_before_import_pages', $niche_id, $sample_pages );

		// Get existing pages to avoid duplicates
		$existing_pages     = $this->get_existing_pages( $sample_pages );
		$existed_pages_name = wp_list_pluck( $existing_pages->posts, 'post_name' );

		// Import existing pages
		if ( $existing_pages->have_posts() ) {
			$imported_pages = $this->process_existing_pages( $existing_pages->posts, $sample_pages );
		}

		// Import new pages
		$not_existed_pages = array_filter(
			$sample_pages,
			function( $page_info ) use ( $existed_pages_name ) {
				return ! in_array( $page_info['name'], $existed_pages_name, true );
			}
		);

		foreach ( $not_existed_pages as $page_info ) {
			$new_post_id = $this->insert_new_page( $page_info, $niche_id, $builder );

			if ( $new_post_id ) {
				$inserted_pages[] = $new_post_id;
				$imported_pages[] = array(
					'id'        => $new_post_id,
					'title'     => $page_info['title'],
					'name'      => $page_info['name'],
					'post_meta' => $page_info['post_meta'] ?? array(),
				);
			}
		}

		// Update page settings and metadata
		$this->update_page_settings( $imported_pages, $sample_pages );

		do_action( 'brandy_after_import_pages', $niche_id, $imported_pages );

		return $inserted_pages;
	}

	private function get_merged_sample_pages( $builder ) {
		// Get default sample pages
		$sample_pages = ImportService::read_posts_from_csv(
			BRANDY_TEMPLATE_DIR . '/assets/sample-data/sample-pages.json'
		);

		// Filter out WooCommerce pages if not installed
		$sample_pages = array_filter(
			$sample_pages,
			function( $page ) {
				return ! ( ! empty( $page['dependency'] ) && 'wc' === $page['dependency'] && ! is_wc_installed() );
			}
		);

		// Merge with niche-specific pages
		if ( isset( $this->selected_niche['sample_pages'][ $builder ] ) ) {
			$niche_file = $this->selected_niche['sample_pages'][ $builder ];
			if ( file_exists( $niche_file ) ) {
				$niche_pages  = ImportService::read_posts_from_csv( $niche_file );
				$sample_pages = $this->merge_unique_pages( $sample_pages, $niche_pages );
			}
		}

		return $sample_pages;
	}

	private function get_existing_pages( $sample_pages ) {

		$should_check_pages = array_filter(
			$sample_pages,
			function( $page ) {
				if ( isset( $page['dependency'] ) && 'wc' === $page['dependency'] ) {
					return is_wc_installed();
				}
				return true;
			}
		);

		return new \WP_Query(
			array(
				'post_type'      => 'page',
				'post_status'    => array( 'publish', 'draft' ),
				'post_name__in'  => wp_list_pluck( $should_check_pages, 'name' ),
				'no_found_rows'  => true,
				'fields'         => 'all',
				'posts_per_page' => 12, //Currently is number of pages in sample-pages.json
			)
		);
	}

	private function process_existing_pages( $posts, $sample_pages ) {
		$imported_pages = array();
		foreach ( $posts as $post ) {
			$matching_page = current(
				array_filter(
					$sample_pages,
					function( $item ) use ( $post ) {
						return $post->post_name === $item['name'];
					}
				)
			);

			$imported_pages[] = array(
				'id'        => $post->ID,
				'name'      => $post->post_name,
				'title'     => $post->post_title,
				'post_meta' => $matching_page['post_meta'] ?? array(),
			);
		}
		return $imported_pages;
	}

	private function insert_new_page( $page_info, $niche_id, $builder ) {
		$post_args = array_merge(
			array(
				'post_title'     => $page_info['title'],
				'post_type'      => 'page',
				'post_name'      => $page_info['name'],
				'post_content'   => $page_info['content'],
				'post_status'    => 'publish',
				'comment_status' => 'closed',
				'ping_status'    => 'closed',
				'post_author'    => 1,
				'menu_order'     => 0,
			),
			isset( $page_info['page_template'] ) ? array(
				'page_template' => $page_info['page_template'],
			) : array()
		);

		$new_post_id = wp_insert_post( $post_args );

		if ( ! is_wp_error( $new_post_id ) && $new_post_id ) {
			do_action( 'brandy_after_import_page', $niche_id, $builder, $new_post_id, $page_info );
			return $new_post_id;
		}

		return false;
	}

	private function update_page_settings( $imported_pages, $sample_pages ) {
		$page_options = array(
			'homepage'             => 'page_on_front',
			'blog'                 => 'page_for_posts',
			'terms-and-conditions' => 'woocommerce_terms_page_id',
			'privacy-policy'       => 'wp_page_for_privacy_policy',
			'shop'                 => 'woocommerce_shop_page_id',
			'cart'                 => 'woocommerce_cart_page_id',
			'checkout'             => 'woocommerce_checkout_page_id',
		);

		foreach ( $imported_pages as $data ) {
			$page_info = current(
				array_filter(
					$sample_pages,
					function( $item ) use ( $data ) {
						return $item['name'] === $data['name'];
					}
				)
			);

			if ( empty( $page_info ) ) {
				continue;
			}

			$post_id = $data['id'];

			// Update special page options
			if ( ! empty( $page_info['name'] ) ) {
				if ( isset( $page_options[ $page_info['name'] ] ) ) {
					if ( in_array( $page_info['name'], array( 'homepage', 'blog' ) ) ) {
						update_option( 'show_on_front', 'page' );
					}
					update_option( $page_options[ $page_info['name'] ], $post_id );
				}
			}

			// Update post status and template
			wp_update_post(
				array_merge(
					array(
						'ID'          => $post_id,
						'post_status' => 'publish',
					),
					! empty( $page_info['page_template'] ) ? array(
						'page_template' => $page_info['page_template'],
					) : array()
				)
			);

			// Update post meta
			$this->update_page_meta( $post_id, $page_info );
		}
	}

	private function update_page_meta( $post_id, $page_info ) {
		// Clear existing meta
		foreach ( ( $this->post_meta_services->services ?? array() ) as $meta_service ) {
			delete_post_meta( $post_id, $meta_service::META_NAME );
		}

		// Add new meta
		if ( ! empty( $page_info['post_meta'] ) ) {
			foreach ( $page_info['post_meta'] as $key => $value ) {
				update_post_meta( $post_id, $key, $value );
			}
		}
	}

	private function merge_unique_pages( $sample_pages, $niche_pages ) {
		foreach ( $niche_pages as $page ) {
			if ( ! $this->page_exists( $sample_pages, $page['name'] ) ) {
				$sample_pages[] = $page;
			}
		}
		return $sample_pages;
	}

	private function page_exists( $pages, $name ) {
		return (bool) array_filter(
			$pages,
			function( $p ) use ( $name ) {
				return $p['name'] === $name;
			}
		);
	}
}
