<?php
declare( strict_types=1 );

namespace FiboFilters\Config;

use FiboFilters\Filtering\Request;
use FiboFilters\Filters\FilterFactory;
use FiboFilters\Integrations\Themes;
use FiboFilters\Settings\Onboarding;
use FiboFilters\Settings\Settings;
use FiboFilters\WP\Helper as WordPressHelper;
use Freemius;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class AdminAssetsLoader
 */
class AdminAssetsLoader {
	/** @var FilterFactory */
	private $filter_factory;

	/** @var Freemius */
	private $freemius;

	/** @var Onboarding */
	private $onboarding;

	/** @var WordPressHelper */
	private $wp_helper;

	/** @var Settings */
	private $settings;

	/** @var Themes */
	private $themes;

	public function __construct(
		FilterFactory $filter_factory,
		Freemius $freemius,
		Onboarding $onboarding,
		Request $request,
		Settings $settings,
		WordPressHelper $wp_helper,
		Themes $themes
	) {
		$this->filter_factory = $filter_factory;
		$this->freemius       = $freemius;
		$this->onboarding     = $onboarding;
		$this->settings       = $settings;
		$this->wp_helper      = $wp_helper;
		$this->themes         = $themes;
	}

	public function enqueue_admin_assets(): void {
		$block_settings = [
			'filters'     => [
				'filter_location' => apply_filters( 'fibofilters/config/filter_location', $this->settings->get( 'general_filter_location', 'above_products' ) ),
			],
			'settingsUrl' => admin_url( 'admin.php?page=fibofilters#general' ),
		];
		wp_add_inline_script(
			'fibofilters-filters-editor-script',
			sprintf( 'window.fiboFiltersBlockSettings = %s', wp_json_encode( $block_settings ) )
		);
		if ( Menu::is_on_settings_admin_page() && ! $this->freemius->is_activation_mode() ) {
			$script_dependencies = [
				'dependencies' => null,
				'version'      => Env::$version,
			];

			if ( file_exists( Env::$build_path . '/admin/settings.asset.php' ) ) {
				$script_dependencies = require Env::$build_path . '/admin/settings.asset.php';
			}

			// Enqueue media scripts for the media uploader.
			wp_enqueue_media();

			wp_enqueue_script(
				'fibofilters-settings-js',
				Env::$build_url . '/admin/settings.js',
				$script_dependencies['dependencies'],
				$script_dependencies['version'],
				true
			);

			wp_set_script_translations(
				'fibofilters-settings-js',
				'fibofilters',
				Env::$languages_path
			);

			wp_add_inline_script(
				'fibofilters-settings-js',
				sprintf(
					'wp.domReady( function() {
						fiboFiltersAdmin.initialize( "fibofilters", %s );
					} );',
					wp_json_encode( $this->get_admin_scripts_config() )
				)
			);

			wp_enqueue_style(
				'fibofilters-settings-css',
				Env::$build_url . '/admin/settings.css',
				[
					'wp-components',
					'wc-components',
					'wp-block-editor',
				],
				Env::$version
			);

			wp_enqueue_style( 'fibofilters-style-settings-css', Env::$build_url . '/admin/style-settings.css', [], Env::$version );
		}

		if ( Menu::is_on_debug_admin_page() && ! $this->freemius->is_activation_mode() ) {
			add_filter(
				'removable_query_args',
				function ( $args ) {
					$args[] = '_wpnonce';
					$args[] = 'fibofilters-action';

					return $args;
				}
			);

			$script_dependencies = [
				'dependencies' => null,
				'version'      => Env::$version,
			];

			if ( file_exists( Env::$build_path . '/admin/debug.asset.php' ) ) {
				$script_dependencies = require Env::$build_path . '/admin/debug.asset.php';
			}

			wp_enqueue_script(
				'fibofilters-debug-js',
				Env::$build_url . '/admin/debug.js',
				array_merge( [ 'wp-dom-ready' ], $script_dependencies['dependencies'] ),
				$script_dependencies['version'],
				true
			);

			wp_add_inline_script(
				'fibofilters-debug-js',
				'wp.domReady( function() {
					//fiboFiltersAdmin.initialize( "fibofilters-debug");
					fiboFiltersAdmin.initializeNotifications( "fibofilters-debug-notifications");
				} );'
			);

			wp_enqueue_style(
				'fibofilters-debug-css',
				Env::$build_url . '/admin/debug.css',
				[
					'wp-components',
				],
				Env::$version
			);

			wp_enqueue_style( 'fibofilters-style-settings-css', Env::$build_url . '/admin/style-settings.css', [], Env::$version );
		}
	}

	private function get_admin_scripts_config(): array {
		$fields = [];
		foreach ( $this->settings->get_fields() as $section => $items ) {
			$fields[ $section ] = array_values( $items );
		}

		$source_analyzer_status = 'active';
		if ( get_option( Env::$plugin_prefix . 'disable_source_analyzer' ) === '1' ) {
			$source_analyzer_status = 'disabled_by_option';
		} elseif ( apply_filters( 'fibofilters/analyse_source_value_types', true ) === false ) {
			$source_analyzer_status = 'disabled_by_filter';
		}

		$data = [
			'pluginFullName'       => Env::$plugin_full_name,
			'pluginSlug'           => Env::$plugin_slug,
			'buildUrl'             => Env::$build_url . '/admin',
			'freemius'             => [
				'contactPageUrl'   => admin_url( sprintf( 'admin.php/?page=%s-contact', Menu::MAIN_PAGE_SLUG ) ),
				'myAccountPageUrl' => admin_url( sprintf( 'admin.php/?page=%s-account', Menu::MAIN_PAGE_SLUG ) ),
			],
			'settings'             => [
				'prefix'   => Env::$plugin_prefix,
				'sections' => array_values( $this->settings->get_sections() ),
				'fields'   => $fields,
			],
			'filters'              => [
				'types'                => $this->filter_factory->get_filter_types(),
				'prohibited_url_slugs' => apply_filters( 'fibofilters/prohibited_url_slugs', [ 'tag', 'day', 'month', 'year' ] ),
			],
			'blockEditorSettings'  => [
				'renderAppender' => false,
			],
			'widgetAreas'          => $this->wp_helper->get_widget_areas(),
			'onboardingFinished'   => $this->onboarding->is_finished(),
			/**
			 * @see \FiboFilters\Integrations\BulkIntegrations::use_initial_nonce_if_litespeed_cache_esi_is_active
			 */
			'useInitialNonce'      => apply_filters( 'fibofilters/admin_script/config/use_initial_nonce', false ),
			'themeIntegration'     => empty( $this->themes->get_current_integration() ) ? false : $this->themes->get_current_integration(),
			'sourceAnalyzerStatus' => $source_analyzer_status,
		];

		/**
		 * Some of the data passed to the plugin settings contains translations and if the user's language
		 * is different from the website language, we must change the language, load the translation files
		 * again and then get this data.
		 *
		 * Thanks to this, these phrases are in the language of the website and not the user.
		 */
		$restore_needed = $this->wp_helper->maybe_switch_to_locale();

		$data['stringsInDefaultLanguage'] = [
			'label_category'    => _x( 'Category', '[front] Label for selected category', 'fibofilters' ),
			'label_subcategory' => _x( 'Subcategory', '[front] Label for selected subcategory', 'fibofilters' ),
			'any'               => _x( 'Any', '[front]', 'fibofilters' ),
		];

		if ( $restore_needed ) {
			$this->wp_helper->restore_previous_locale();
		}

		return apply_filters( 'fibofilters/admin_script/config', $data );
	}
}
