<?php

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

class QiAddonsForElementor_Framework_Shortcodes {
	private $shortcodes = array();

	public function __construct() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['elementor_updater'] ) && 'continue' === $_GET['elementor_updater'] ) {
			// Permission 5 is set in order to include shortcode files before register '-elementor.php' files.
			add_action( 'elementor/widgets/register', array( $this, 'register' ), 5 );
		} else {
			// 'init' changed for 'elementor/init' because in some cases, when elementor update is performed, there is php error that shortcodes bases are not available
			add_action( 'elementor/init', array( $this, 'register' ) );
		}
	}

	public function get_shortcodes() {
		return $this->shortcodes;
	}

	public function set_shortcodes( $base, $shortcode ) {
		$this->shortcodes[ $base ] = $shortcode;
	}

	public function get_shortcode( $base ) {
		$shortcodes = $this->get_shortcodes();

		if ( ! empty( $shortcodes ) && isset( $shortcodes[ $base ] ) ) {
			return $shortcodes[ $base ];
		}

		return false;
	}

	private function set_shortcode( QiAddonsForElementor_Framework_Shortcode $shortcode ) {
		$this->set_shortcodes( $shortcode->get_base(), $shortcode );
	}

	public function shortcode_exists( $base ) {
		return array_key_exists( $base, $this->get_shortcodes() );
	}

	public function add_shortcode( QiAddonsForElementor_Framework_Shortcode $shortcode ) {
		$key = $shortcode->get_base();

		if ( ! empty( $key ) ) {
			$this->set_shortcode( $shortcode );

			return $shortcode;
		}

		return false;
	}

	public function register() {
		do_action( 'qi_addons_for_elementor_action_framework_before_shortcodes_register' );

		$shortcodes = $this->get_shortcodes();

		if ( ! empty( $shortcodes ) && is_array( $shortcodes ) ) {
			ksort( $shortcodes );

			foreach ( $shortcodes as $shortcode ) {
				$shortcode->register();
			}
		}
		do_action( 'qi_addons_for_elementor_action_framework_after_shortcodes_register' );
	}
}
