<?php

namespace Elementor\Modules\Promotions;

use Elementor\Api;
use Elementor\Controls_Manager;
use Elementor\Core\Base\Module as Base_Module;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Custom_Code_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Custom_Elements_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Fonts_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Icons_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Popups_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Editor_One_Submissions_Menu;
use Elementor\Modules\Promotions\AdminMenuItems\Go_Pro_Promotion_Item;
use Elementor\Modules\Promotions\Controls\Atomic_Promotion_Control;
use Elementor\Modules\Promotions\Pointers\Birthday;
use Elementor\Modules\Promotions\Pointers\Black_Friday;
use Elementor\Modules\Promotions\PropTypes\Promotion_Prop_Type;
use Elementor\Modules\Promotions\Widgets\Ally_Dashboard_Widget;
use Elementor\Widgets_Manager;
use Elementor\Utils;
use Elementor\Includes\EditorAssetsAPI;
use Elementor\Plugin;
use Elementor\Modules\EditorOne\Classes\Menu_Data_Provider;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class Module extends Base_Module {

	const ADMIN_MENU_PRIORITY = 100;

	const ADMIN_MENU_PROMOTIONS_PRIORITY = 120;

	public static function is_active() {
		return ! Utils::has_pro();
	}

	public function get_name() {
		return 'promotions';
	}

	public function __construct() {
		parent::__construct();

		add_action( 'admin_init', function () {
			$this->handle_external_redirects();
		} );

		add_action( 'elementor/editor-one/menu/register', function ( Menu_Data_Provider $menu_data_provider ) {
			$this->register_editor_one_menu_items( $menu_data_provider );
		} );

		add_action( 'elementor/widgets/register', function( Widgets_Manager $manager ) {
			foreach ( Api::get_promotion_widgets() as $widget_data ) {
				$manager->register( new Widgets\Pro_Widget_Promotion( [], [
					'widget_name' => $widget_data['name'],
					'widget_title' => $widget_data['title'],
				] ) );
			}
		} );

		if ( Birthday::should_display_notice() ) {
			new Birthday();
		}

		if ( Black_Friday::should_display_notice() ) {
			new Black_Friday();
		}

		if ( Utils::has_pro() ) {
			return;
		}

		add_action( 'elementor/controls/register', function ( Controls_Manager $controls_manager ) {
			$controls_manager->register( new Controls\Promotion_Control() );
		} );

		add_action( 'elementor/editor/before_enqueue_scripts', [ $this, 'enqueue_react_data' ] );
		add_action( 'elementor/editor/before_enqueue_scripts', [ $this, 'enqueue_editor_v4_alphachip' ] );
		add_filter( 'elementor/editor/localize_settings', [ $this, 'add_v4_promotions_data' ] );

		// Add Ally promo
		Ally_Dashboard_Widget::init();

		$this->register_atomic_promotions();
	}

	/**
	 * Get Ally Scanner URL
	 *
	 * @return string
	 */
	public static function get_ally_external_scanner_url(): string {
		return apply_filters( 'elementor/ally_external_scanner_url', 'https://elementor.com/tools/ally-accessibility-checker/scanner' );
	}

	private function handle_external_redirects() {
		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( empty( $page ) ) {
			return;
		}

		if ( 'go_elementor_pro' === $page ) {
			wp_redirect( Go_Pro_Promotion_Item::get_url() ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
			die;
		}
	}

	private function register_editor_one_menu_items( Menu_Data_Provider $menu_data_provider ) {
		$menu_data_provider->register_menu( new Editor_One_Custom_Elements_Menu() );
		$menu_data_provider->register_menu( new Editor_One_Submissions_Menu() );
		$menu_data_provider->register_menu( new Editor_One_Fonts_Menu() );
		$menu_data_provider->register_menu( new Editor_One_Icons_Menu() );
		$menu_data_provider->register_menu( new Editor_One_Custom_Code_Menu() );
		$menu_data_provider->register_menu( new Editor_One_Popups_Menu() );
	}

	public function enqueue_react_data(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$min_suffix = Utils::is_script_debug() ? '' : '.min';

		wp_enqueue_script(
			'e-react-promotions',
			ELEMENTOR_ASSETS_URL . 'js/e-react-promotions' . $min_suffix . '.js',
			[
				'react',
				'react-dom',
				'backbone-marionette',
				'elementor-editor-modules',
				'elementor-v2-ui',
			],
			ELEMENTOR_VERSION,
			true
		);

		wp_set_script_translations( 'e-react-promotions', 'elementor' );

		wp_localize_script(
			'e-react-promotions',
			'elementorPromotionsData',
			$this->get_app_js_config()
		);
	}

	public function enqueue_editor_v4_alphachip(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$min_suffix = Utils::is_script_debug() ? '' : '.min';

		wp_enqueue_script(
			'editor-v4-opt-in-alphachip',
			ELEMENTOR_ASSETS_URL . 'js/editor-v4-opt-in-alphachip' . $min_suffix . '.js',
			[
				'react',
				'react-dom',
				'elementor-common',
				'elementor-v2-ui',
			],
			ELEMENTOR_VERSION,
			true
		);
	}

	private function get_app_js_config(): array {
		$editor_assets_api = new EditorAssetsAPI( $this->get_api_config() );
		$promotion_data = new PromotionData( $editor_assets_api );

		return $promotion_data->get_promotion_data();
	}

	private function get_api_config(): array {
		return [
			EditorAssetsAPI::ASSETS_DATA_URL => 'https://assets.elementor.com/free-to-pro-upsell/v1/free-to-pro-upsell.json',
			EditorAssetsAPI::ASSETS_DATA_TRANSIENT_KEY => '_elementor_free_to_pro_upsell',
			EditorAssetsAPI::ASSETS_DATA_KEY => 'free-to-pro-upsell',
		];
	}

	public function add_v4_promotions_data( array $settings ): array {
		if ( ! current_user_can( 'manage_options' ) ) {
			return $settings;
		}

		$editor_assets_api = new EditorAssetsAPI( $this->get_v4_promotions_api_config() );
		$promotion_data = new PromotionData( $editor_assets_api );

		$settings['v4Promotions'] = $promotion_data->get_v4_promotions_data();

		return $settings;
	}

	private function get_v4_promotions_api_config(): array {
		return [
			EditorAssetsAPI::ASSETS_DATA_URL => 'https://assets.elementor.com/packages/v1/promotions.json',
			EditorAssetsAPI::ASSETS_DATA_TRANSIENT_KEY => '_elementor_v4_promotions',
			EditorAssetsAPI::ASSETS_DATA_KEY => 'promotions',
		];
	}

	private function is_atomic_widgets_active(): bool {
		return Plugin::$instance->experiments->is_feature_active( 'e_atomic_elements' );
	}

	private function get_atomic_promotion_configs(): array {
		return [
			[
				'key' => 'attributes',
				'label' => __( 'Attributes', 'elementor' ),
				'section' => 'settings',
				'priority' => 40,
			],
			[
				'key' => 'display-conditions',
				'label' => __( 'Display Conditions', 'elementor' ),
				'section' => 'settings',
				'priority' => 50,
			],
		];
	}

	private function register_atomic_promotions(): void {
		add_action( 'elementor/init', function() {
			if ( ! $this->is_atomic_widgets_active() ) {
				return;
			}

			add_filter(
				'elementor/atomic-widgets/props-schema',
				[ $this, 'inject_atomic_promotion_props' ]
			);

			foreach ( $this->get_atomic_promotion_configs() as $config ) {
				add_filter(
					'elementor/atomic-widgets/controls',
					fn( array $controls, $element ) => $this->inject_atomic_promotion_control( $controls, $element, $config ),
					$config['priority'],
					2
				);
			}
		} );
	}

	public function inject_atomic_promotion_props( array $schema ): array {
		foreach ( $this->get_atomic_promotion_configs() as $config ) {
			$key = $config['key'];

			if ( isset( $schema[ $key ] ) ) {
				continue;
			}

			$schema[ $key ] = Promotion_Prop_Type::make( $key );
		}

		return $schema;
	}

	protected function inject_atomic_promotion_control( array $element_controls, $atomic_element, array $config ): array {
		$key = $config['key'];
		$schema = $atomic_element::get_props_schema();

		if ( ! array_key_exists( $key, $schema ) ) {
			return $element_controls;
		}

		foreach ( $element_controls as $item ) {
			if ( ! ( $item instanceof \Elementor\Modules\AtomicWidgets\Controls\Section ) ) {
				continue;
			}

			if ( $item->get_id() !== $config['section'] ) {
				continue;
			}

			$control = Atomic_Promotion_Control::make( $key )
				->set_label( $config['label'] )
				->set_meta( [
					'topDivider' => true,
				] );

			$item->add_item( $control );
			break;
		}

		return $element_controls;
	}
}
