<?php

namespace HulkPlugins\ElementorPro\Forms\AdvancedFields;

use Elementor\Core\DynamicTags\Manager;
use Elementor\Plugin;
use ElementorPro\Modules\Forms\Registrars\Form_Fields_Registrar;
use ElementorPro\Modules\Forms\Widgets\Form;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Models\SettingsModel;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Routes\DropzoneRoute;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Routes\SettingsRoute;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Traits\SingletonTrait;
use HulkPlugins\ElementorPro\Forms\AdvancedFields\Utils\FileUtil;

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

class Base {
	use SingletonTrait;

	public function init_hooks(): void {
		add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 2 );
		add_action( 'admin_init', [ $this, 'is_elementor_pro_exist' ] );
		add_action( 'activated_plugin', [ $this, 'activated' ] );
		add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
		add_filter( 'elementor/widget/print_template', [ $this,'print_template' ], PHP_INT_MAX, 2 );
		add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'editor_enqueue_scripts' ] );
		add_action( 'elementor_pro/forms/fields/register', [ $this, 'register_fields' ] );
		add_action( 'elementor/dynamic_tags/register', [ $this, 'register_dynamic_tags' ] );
		add_action( 'shutdown', [ $this, 'shutdown' ] );
		hulk_affef_fs()->add_action( 'after_uninstall', [ $this, 'uninstall' ] );
	}

	/**
	 * Add plugin meta
	 *
	 * @param $links
	 * @param $file
	 *
	 * @return array|mixed
	 */
	public function plugin_row_meta( $links, $file ) {

		if ( strpos( $file, 'advanced-fields-for-elementor-forms.php' ) !== false ) {

			$row_meta['docs'] = sprintf(
			/** @lang text */                '<a target="_blank" href="%1$s" title="%2$s">%2$s</a>',
				esc_url( DOCUMENTATION ),
				esc_html__( 'Docs', 'advanced-fields-for-elementor-forms' )
			);

			$row_meta['settings'] = sprintf(
			/** @lang text */                '<a href="%1$s">%2$s</a>',
				admin_url( 'admin.php?page=advanced-fields-for-elementor-forms-settings' ),
				esc_html__( 'Settings', 'advanced-fields-for-elementor-forms' )
			);

			$row_meta['support'] = sprintf(
			/** @lang text */                '<a target="_blank" href="%1$s">%2$s</a>',
				esc_url( SUPPORT ),
				esc_html__( 'Help &amp; Support', 'advanced-fields-for-elementor-forms' )
			);

			$links = array_merge( $links, $row_meta );
		}

		return $links;
	}

	/**
	 * Function used to deactivate the plugin if "elementor pro" does not exist
	 *
	 * @return bool
	 */
	public function is_elementor_pro_exist(): bool {
		if ( is_plugin_active( 'elementor-pro/elementor-pro.php' ) ) {
			return true;
		}
		// If neither plugin is active, show an admin notice.
		add_action( 'admin_notices', [ $this, 'admin_notice_missing_required_plugin' ] );
		return false;
	}

	/**
	 * Show notice to enable Elementor Pro
	 * @return void
	 */
	public function admin_notice_missing_required_plugin(): void {
		$message = sprintf(
		// translators: %1$s replace with "Advanced Fields For Elementor Forms" & %2$s replace with "Elementor Pro".
			esc_html__(
				'%1$s requires %2$s to be installed and activated.',
				'advanced-fields-for-elementor-forms'
			),
			esc_html__( 'Advanced Fields For Elementor Forms', 'advanced-fields-for-elementor-forms' ),
			esc_html__( 'Elementor Pro', 'advanced-fields-for-elementor-forms' ),
		);
		printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', esc_html( $message ) );
		deactivate_plugins( 'advanced-fields-for-elementor-forms/advanced-fields-for-elementor-forms.php' );
	}

	/**
	 * Hooked into the 'activated_plugin' action to redirect to the settings page when the plugin is activated.
	 *
	 * @param $plugin
	 *
	 * @return void
	 */
	public function activated( $plugin ): void {
		if ( ! is_plugin_active( 'elementor-pro/elementor-pro.php' ) ) {
			return;
		}
		if ( $plugin === 'advanced-fields-for-elementor-forms/advanced-fields-for-elementor-forms.php' ) {

			// Redirect to settings page
	        $settingsPageUrl = add_query_arg(
	            [
					'page' => 'advanced-fields-for-elementor-forms-settings',
	            ],
	            admin_url( 'admin.php' )
	        );

	        wp_safe_redirect( $settingsPageUrl );
	        exit();
		}
	}

	/**
	 * Registers the REST API routes
	 *
	 * @return void
	 */
	public function rest_api_init(): void {
		new SettingsRoute();
		new DropzoneRoute();
	}

	public function register_field_scripts( string $handle ): void {
		$assets = require PLUGIN_DIR_PATH . 'build/fields/' . $handle . '/index.asset.php';
		wp_register_style(
			PREFIX . $handle,
			PLUGIN_DIR_URL . 'build/fields/' . $handle . '/index.css',
			[],
			$assets['version'],
		);
		wp_register_script(
			PREFIX . $handle,
			PLUGIN_DIR_URL . 'build/fields/' . $handle . '/index.js',
			$assets['dependencies'],
			$assets['version'],
			[ 'strategy' => 'defer' ]
		);
	}

	/**
	 * Filters the form template content before it's printed in the editor.
	 * @param $template_content
	 * @param $widget
	 *
	 * @return array|mixed|string|string[]
	 */
	public function print_template( $template_content, $widget ) {
		/** @var Form $widget */
		if ( $widget->get_name() === 'form' ) {
			return '';
		}
		return $template_content;
	}

	/**
	 * After editor enqueue scripts.
	 *
	 * Fires after Elementor editor scripts are enqueued.
	 */
	public function editor_enqueue_scripts(): void {
		wp_enqueue_script(
			PREFIX . 'repeater-control',
			PLUGIN_DIR_URL . 'build/controls/repeater/index.js',
			[ 'elementor-editor' ],
			VERSION,
			true
		);
	}

	/**
	 * Fires when scripts and styles are enqueued.
	 * @return void
	 */
	public function enqueue_scripts(): void {
		if ( ! wp_script_is( 'react-jsx-runtime', 'registered' ) ) {
			wp_register_script(
				'react-jsx-runtime',
				PLUGIN_DIR_URL . 'assets/js/react-jsx-runtime.js',
				[ 'react' ],
				'18.3.1',
				true
			);
		}

		$settingsModel = SettingsModel::getInstance();
		$fields = $settingsModel->getFieldsInfo();
		foreach ( $fields as $field ) {
			if ( $field['dirname'] ) {
				$this->register_field_scripts( $field['dirname'] );
			}
		}
	}

	/**
	 * Elementor Pro form fields registration.
	 * @param Form_Fields_Registrar $formFieldsRegistrar
	 *
	 * @return void
	 */
	public function register_fields( Form_Fields_Registrar $formFieldsRegistrar ): void {
		$settingsModel = SettingsModel::getInstance();
		$fields = $settingsModel->getFieldsInfo();
		foreach ( $fields as $field ) {
			if ( $field['dirname'] ) {
				$classFilePath = PLUGIN_DIR_PATH . 'includes/Fields/' . $field['dirname'] . '/Field.php';
				$className = "\\HulkPlugins\\ElementorPro\\Forms\\AdvancedFields\\Fields\\{$field['dirname']}\\Field";
                if ( class_exists( $className ) && file_exists( $classFilePath ) ) {
                    $formFieldsRegistrar->register( new $className( $field ) );
                }
			}
		}
	}

	/**
	 * Register dynamic tags.
	 *
	 * @param Manager $manager
	 *
	 * @return void
	 */
	public function register_dynamic_tags( Manager $manager ): void {
	}

	/**
	 * Fires just before PHP shuts down execution.
	 * @return void
	 */
	public function shutdown(): void {
		FileUtil::cleanup_upload_files();
	}

	/**
	 * Freemius uninstall hook
	 * @return void
	 */
	public function uninstall(): void {

		// Cleanup
		SettingsModel::getInstance()->deleteSettings();
		FileUtil::remove_upload_dir();

		// Check if Elementor is loaded
		if ( did_action( 'elementor/loaded' ) ) {
			// Clear Elementor cache
			Plugin::instance()->files_manager->clear_cache();
		}
	}
}
