<?php

namespace Brandy\Niches\Import;

use Brandy\Core\Services\ButtonService;
use Brandy\Core\Services\ProductCatalogService;
use Brandy\Utils\Helpers;

/**
 * Applies a niche's template settings (button, WooCommerce, header/footer
 * builder overrides) and resets WP templates / editor global styles.
 *
 * Extracted verbatim from NicheService as part of the behavior-preserving
 * decomposition.
 */
class TemplateSettingsApplier {

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

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

	public function install_template() {

		if ( empty( $this->selected_niche ) ) {
			return;
		}

		$niche_id = $this->selected_niche['id'];

		do_action( 'brandy_before_' . $niche_id . '_installing_template_settings' );

		if ( isset( $this->selected_niche['template_data'] ) ) {
			$this->override_template_settings( $this->selected_niche['template_data'] );
		}

		do_action( 'brandy_after_' . $niche_id . '_installing_template_settings' );
	}

	private function override_template_settings( $data ) {
		/**
		 * Override button
		 */
		$button_settings = ButtonService::get_default_settings();
		if ( isset( $data['button'] ) ) {
			$button_settings = Helpers::recursive_wp_parse_args( $data['button'], $button_settings );
		}
		$this->override_button_settings( $button_settings );

		/**
		 * Override woocommerce
		 */
		$woocommerce_settings = array(
			'product_layout'     => 'option_1',
			'product_thumb_size' => 'size_1',
		);
		if ( isset( $data['woocommerce'] ) ) {
			$woocommerce_settings = Helpers::recursive_wp_parse_args( $data['woocommerce'], $woocommerce_settings );
		}
		$this->override_woocommerce_settings( $woocommerce_settings );

		/**
		 * Override builder settings
		 */
		if ( isset( $data['headers'] ) ) {
			$this->override_builder_settings( $data['headers'], 'header' );
		}

		if ( isset( $data['footers'] ) ) {
			$this->override_builder_settings( $data['footers'], 'footer' );
		}
	}

	private function override_button_settings( $data ) {
		ButtonService::save_settings( $data );
	}

	private function override_builder_settings( $files, $builder = 'header' ) {

		if ( empty( $this->selected_niche ) ) {
			return;
		}

		$niche_id = $this->selected_niche['id'];

		$fn = "brandy_get_{$builder}_settings";

		if ( ! is_callable( $fn ) ) {
			return;
		}

		$builder_settings = call_user_func( $fn );
		$templates        = &$builder_settings['templates'];
		$imported_data    = array();
		$main_data        = array();

		foreach ( $files as $index => $file ) {
			if ( ! file_exists( $file ) ) {
				continue;
			}

			$template_data = json_decode( file_get_contents( $file ), true ); //phpcs:ignore

			if ( $index === 'main' ) {
				$main_data = $template_data;
			}

			if ( $index !== 'main' && $main_data ) {
				$template_data = Helpers::recursive_wp_parse_args( $template_data, $main_data );
			}

			$template_exists = false;

			foreach ( $templates as $existing_index => $template ) {
				if ( $template_data['id'] === $template['id'] ) {
					$template_exists                                  = true;
					$builder_settings['templates'][ $existing_index ] = $template_data;
					break;
				}
			}

			if ( ! $template_exists ) {
				$builder_settings['templates'][] = $template_data;
			}

			$imported_data[] = $template_data;
		}

		$save_function = "brandy_save_{$builder}_settings";

		if ( is_callable( $save_function ) ) {
			call_user_func( $save_function, $builder_settings );

			do_action( "brandy_after_{$niche_id}_import_{$builder}", $imported_data );
		}
	}

	private function override_woocommerce_settings( $data ) {
		$product_catalog_data = array();
		if ( isset( $data['product_layout'] ) ) {
			$product_catalog_data['product_layout'] = $data['product_layout'];
		}
		if ( isset( $data['product_thumb_size'] ) ) {
			$product_catalog_data['product_thumb_size'] = $data['product_thumb_size'];
		}

		if ( isset( $data['product_image_hover_effect'] ) ) {
			set_theme_mod( 'product_image_hover_effect', $data['product_image_hover_effect'] );
			set_theme_mod( 'enable_product_image_hover_effect', true );
		}

		if ( isset( $data['enable_product_image_hover_zoom'] ) ) {
			set_theme_mod( 'enable_product_image_hover_zoom', $data['enable_product_image_hover_zoom'] );
		}

		if ( isset( $data['product_image_hover_scale'] ) ) {
			set_theme_mod( 'product_image_hover_scale', $data['product_image_hover_scale'] );
		}

		ProductCatalogService::save_settings( $product_catalog_data );

	}

	public function reset_wp_templates() {

		$post_names = array();

		$dir = new \DirectoryIterator( BRANDY_TEMPLATE_DIR . '/templates' );
		foreach ( $dir as $fileinfo ) {
			if ( ! $fileinfo->isDot() ) {
				$post_names[] = basename( $fileinfo->getFilename(), '.html' );
			}
		}
		$dir = new \DirectoryIterator( BRANDY_TEMPLATE_DIR . '/parts' );
		foreach ( $dir as $fileinfo ) {
			if ( ! $fileinfo->isDot() ) {
				$post_names[] = basename( $fileinfo->getFilename(), '.html' );
			}
		}
		$args  = array(
			'post_type'     => array( 'wp_template', 'wp_template_part' ),
			'post_name__in' => $post_names,
		);
		$query = new \WP_Query( $args );

		if ( ! $query->have_posts() ) {
			return;
		}

		foreach ( $query->posts as $post ) {
			wp_delete_post( $post->ID );
		}
	}

	public function reset_editor_settings() {

		if ( ! class_exists( 'WP_Theme_JSON_Resolver' ) ) {
			return;
		}

		$id = \WP_Theme_JSON_Resolver::get_user_global_styles_post_id();

		if ( empty( $id ) ) {
			return;
		}

		if ( ! class_exists( 'WP_REST_Global_Styles_Controller' ) ) {
			return;
		}

		try {

			wp_update_post(
				array(
					'ID'           => $id,
					'post_content' => '{"isGlobalStylesUserThemeJSON":true,"version":3}',
				)
			);

		} catch ( \WP_Error $error ) {
			// This is silent
		} catch ( \Exception $exp ) {
			// This is silent
		}

	}

	public function reset_data() {
		$this->reset_editor_settings();
		$this->reset_wp_templates();
	}
}
