<?php

namespace WPFormsSurveys;

use WPForms_Updater;

/**
 * WPForms Surveys and Polls loader class.
 *
 * @since 1.0.0
 */
final class Loader {

	/**
	 * URL to a plugin directory. Used for assets.
	 *
	 * @var string
	 *
	 * @since 1.0.0
	 */
	public $url = '';

	/**
	 * Initiate main plugin instance.
	 *
	 * @since 1.0.0
	 *
	 * @return Loader
	 */
	public static function get_instance() {

		static $instance;

		if ( ! $instance ) {
			$instance = new self();

			$instance->init();
		}

		return $instance;
	}

	/**
	 * All the actual plugin loading is done here.
	 *
	 * @since 1.0.0
	 */
	private function init() {

		$this->url = plugin_dir_url( __DIR__ );

		( new Migrations\Migrations() )->init();

		new Reporting\Ajax();
		new Fields\LikertScale\Field();
		new Fields\NetPromoterScore\Field();
		new Polls();

		( new Integrations() )->hooks();

		// The admin_init action is too late for FSE.
		// We have to run it before register_block_type() is executed in \WPForms\Integrations\Gutenberg\FormSelector.
		new Admin();

		$this->hooks();

		if ( is_admin() ) {
			( new Fields\LikertScale\EntriesEdit() )->init();
			( new Fields\NetPromoterScore\EntriesEdit() )->init();
		}
		// phpcs:enable WPForms.PHP.BackSlash.UseShortSyntax

		// Register the updater of this plugin.
		$this->updater();
	}

	/**
	 * Add hooks.
	 *
	 * @since 1.12.0
	 */
	private function hooks() {

		add_action(
			'admin_init',
			static function() {
				new Reporting\Admin();
				new Templates\Poll();
				new Templates\Survey();
				new Templates\NPSSurveySimple();
				new Templates\NPSSurveyEnhanced();
			}
		);
	}

	/**
	 * Load the plugin updater.
	 *
	 * @since 1.0.0
	 */
	private function updater() { // phpcs:ignore WPForms.PHP.HooksMethod.InvalidPlaceForAddingHooks

		$url = $this->url;

		add_action(
			'wpforms_updater',
			static function( $key ) use ( $url ) {

				new WPForms_Updater(
					[
						'plugin_name' => 'WPForms Surveys and Polls',
						'plugin_slug' => 'wpforms-surveys-polls',
						'plugin_path' => plugin_basename( WPFORMS_SURVEYS_POLLS_FILE ),
						'plugin_url'  => trailingslashit( $url ),
						'remote_url'  => WPFORMS_UPDATER_API,
						'version'     => WPFORMS_SURVEYS_POLLS_VERSION,
						'key'         => $key,
					]
				);
			}
		);
	}
}
