<?php
/**
 * Main Plugin class.
 *
 * Bootstraps all sub-components and registers top-level hooks.
 *
 * @package IGIT_RPWT
 */

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

class IGIT_RPWT_Plugin {

	/**
	 * Plugin version.
	 */
	const VERSION = IGIT_RPWT_VERSION;

	/**
	 * Boot the plugin.
	 */
	public function __construct() {
		$this->define_hooks();
		$this->load_components();
	}

	/**
	 * Register top-level hooks that are needed regardless of context.
	 */
	private function define_hooks() {
		// Register the custom image size after the theme has set up its sizes.
		add_action( 'after_setup_theme', array( 'IGIT_RPWT_Image_Helper', 'register_image_size' ) );

		// Boot series taxonomy.
		new IGIT_RPWT_Series();

		// Clear a post's related-posts cache when that post is saved.
		add_action( 'save_post', array( 'IGIT_RPWT_Query', 'flush_post_cache' ) );

		// Register the Gutenberg block (server-side rendered) — Pro only.
		if ( igit_rpwt_is_pro() ) {
			add_action( 'init', array( $this, 'register_block' ) );
		}

		// Async-loading AJAX endpoint — must be registered here (not in IGIT_RPWT_Frontend)
		// because wp_ajax_* fires inside wp-admin/admin-ajax.php where is_admin()=true and
		// the frontend class is never instantiated.
		add_action( 'wp_ajax_'        . IGIT_RPWT_Frontend::AJAX_ACTION, array( 'IGIT_RPWT_Frontend', 'ajax_load_static' ) );
		add_action( 'wp_ajax_nopriv_' . IGIT_RPWT_Frontend::AJAX_ACTION, array( 'IGIT_RPWT_Frontend', 'ajax_load_static' ) );
		// Classic widget.
		add_action( 'widgets_init', array( $this, 'register_widgets' ) );

		// Elementor widget — Pro only, and only when Elementor is active.
		if ( igit_rpwt_is_pro() ) {
			add_action( 'elementor/widgets/register', array( $this, 'register_elementor_widget' ) );
		}
	}

	/**
	 * Instantiate admin and frontend components.
	 */
	private function load_components() {
		if ( is_admin() ) {
			new IGIT_RPWT_Admin();
			new IGIT_RPWT_Metabox();
		} else {
			new IGIT_RPWT_Frontend();
		}
	}

	/**
	 * Register the Elementor widget.
	 *
	 * @param \Elementor\Widgets_Manager $manager
	 */
	public function register_elementor_widget( $manager ) {
		require_once IGIT_RPWT_PLUGIN_DIR . 'includes/class-elementor-widget.php';
		$manager->register( new IGIT_RPWT_Elementor_Widget() );
	}

	/**
	 * Register the classic sidebar widget.
	 */
	public function register_widgets() {
		register_widget( 'IGIT_RPWT_Widget' );
	}

	/**
	 * Register the Gutenberg block type.
	 */
	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) {
			return; // WP < 5.0 fallback.
		}

		register_block_type(
			IGIT_RPWT_PLUGIN_DIR . 'block.json',
			array(
				'render_callback' => array( 'IGIT_RPWT_Frontend', 'render_block' ),
			)
		);
	}

}
