<?php 
class HTMega_Addons_Elementor_Pro {

    const MINIMUM_HTMEGA_VERSION = '2.6.9';
    /**
     * [$_instance description]
     * @var null
     */
    private static $_instance = null;

    /**
     * [instance] Initializes a singleton instance
     * @return [HTMega_Addons_Elementor_Pro]
     */
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * [__construct] Calss Constructor
     */
    public function __construct() {
        if ( ! function_exists('is_plugin_active') ) { include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); }

        add_action( 'init', [ $this, 'i18n' ] );
        add_action( 'plugins_loaded', [ $this, 'init' ]);

        // Register Plugin Active Hook
        register_activation_hook( HTMEGA_ADDONS_PL_ROOT_PRO, [ $this, 'plugin_activate_hook'] );

        // Plugin Deactive Hook
        register_deactivation_hook( HTMEGA_ADDONS_PL_ROOT_PRO, [ $this, 'plugin_deactive_hook'] );

        add_action( 'admin_init', [ $this, 'admin_init' ] );
        add_action( 'wp_ajax_htmega_live_editor_handler', array( $this, 'htmega_live_editor_handler' ) );
        add_action( 'elementor/editor/after_enqueue_styles', array( $this, 'load_el_live_editor_modal' ) );
        add_action( 'elementor/editor/after_enqueue_scripts', array( $this, 'live_el_editor_asset_enqueue' ) );
        add_action( 'wp_ajax_htmega_temp_validity_status', array( $this, 'htmega_temp_validity_status' ) );
		add_action( 'wp_ajax_htmega_get_update_title', array( $this, 'htmega_get_update_title' ) );
        // HT Mega free verson compability
        if( is_plugin_active( 'ht-mega-for-elementor/htmega_addons_elementor.php' ) ){
            if ( ! version_compare( HTMEGA_VERSION, self::MINIMUM_HTMEGA_VERSION, '>=' ) ) {
                add_action('admin_init', function() {
                    if (current_user_can('manage_options')) {
                        $result = htmega_force_update_plugin('ht-mega-for-elementor/htmega_addons_elementor.php');
                        if ( $result !== true ) {
                            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_htmega_free_version' ] );
                        }
                    }
                });
            }
        }

    }

    /**
     * [i18n] Load Text Domain
     * @return [void]
     */
    public function i18n() {
        load_plugin_textdomain( 'htmega-pro', false, dirname( plugin_basename( HTMEGA_ADDONS_PL_PATH_PRO ) ) . '/languages/' );  
    }

    /**
     * [init] Initializes plugin load
     * @return [void]
     */
    public function init() {
        $this->includes();
    }

    /**
     * [admin_init] Admin Initializes
     * @return [void]
     */
    public function admin_init(){
        if( !is_plugin_active( 'ht-mega-for-elementor/htmega_addons_elementor.php' ) ){
            add_action( 'admin_notices', [ $this, 'admin_notice_missing_main_plugin' ] );
            return;
        }

    }

    /**
     * [is_plugins_active]
     * @param  [string]  $pl_file_path plugin location
     * @return boolean   true|false
     */
    public function is_plugins_active( $pl_file_path = NULL ){
        $installed_plugins_list = get_plugins();
        return isset( $installed_plugins_list[$pl_file_path] );
    }

    /**
     * [admin_notice_missing_main_plugin] Admin Notice for HT Mega Free
     * @return [void]
     */
    public function admin_notice_missing_main_plugin() {

        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );

        $htmega = 'ht-mega-for-elementor/htmega_addons_elementor.php';
        if( $this->is_plugins_active( $htmega ) ) {
            if( ! current_user_can( 'activate_plugins' ) ) { return; }

            $activation_url = wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . $htmega . '&amp;plugin_status=all&amp;paged=1&amp;s', 'activate-plugin_' . $htmega );

            $message = '<p>' . __( '<strong>HTMEGA Pro</strong> requires "<strong>HTMega Absolute Addons</strong>" plugin to be active. Please activate HTMega Absolute Addons to continue.', 'htmega-pro' ) . '</p>';

            $message .= '<p>' . sprintf( '<a href="%s" class="button-primary">%s</a>', $activation_url, esc_html__( 'Activate Now', 'htmega-pro' ) ) . '</p>';
        } else {
            if ( ! current_user_can( 'install_plugins' ) ) { return; }

            $install_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=ht-mega-for-elementor' ), 'install-plugin_ht-mega-for-elementor' );

            $message = '<p>' . __( '<strong>HTMEGA Pro</strong> requires "<strong>HTMega Absolute Addons</strong>" plugin to be active. Please install the HTMega Absolute Addons plugin to continue.', 'htmega-pro' ) . '</p>';

            $message .= '<p>' . sprintf( '<a href="%s" class="button-primary">%s</a>', $install_url, esc_html__( 'Install Now', 'htmega-pro' ) ) . '</p>';
        }
        echo '<div class="error"><p>' . $message . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

    }

    /**
     * [admin_notice_minimum_htmega_free_version]
     * @return [void] Elementor Required version check with current version
     */
    public function admin_notice_minimum_htmega_free_version() {
        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
        $message = sprintf(
            /* translators: 1: Plugin name (HTMega Pro), 2: Required plugin name (HT Mega Free), 3: Minimum required version */
            __( '"%1$s" requires "%2$s" version %3$s or greater.', 'htmega-pro' ),
            '<strong>' . esc_html( 'HT Mega Pro', 'htmega-pro' ) . '</strong>',
            '<strong>' . esc_html__( 'HT Mega – Absolute Addons for Elementor.', 'htmega-pro' ) . '</strong>',
             self::MINIMUM_HTMEGA_VERSION
        );
        printf( '<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', $message ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }
    /**
     * [plugin_activate_hook] Plugin Activation Hook
     * @return [void]
     */
    public function plugin_activate_hook() {
        delete_transient( 'htmega_template_info' );
        delete_transient( 'htmega_severdown_request_pending' );
    }

    /**
     * [plugin_deactive_hook] Plugin Deactivation Hook
     * @return [void]
     */
    public function plugin_deactive_hook(){
        delete_transient( 'htmega_template_info' );
        delete_transient( 'htmega_severdown_request_pending' );
    }

    /**
     * [includes] Required Necessary File
     * @return [void]
     */
    public function includes() {
        require_once( HTMEGA_ADDONS_PL_PATH_PRO.'includes/helper-function.php' );
        require_once( HTMEGA_ADDONS_PL_PATH_PRO.'includes/ajax-posts-load-function.php' );
        require_once( HTMEGA_ADDONS_PL_PATH_PRO.'classes/class.enqueue_scripts.php' );
        require_once( HTMEGA_ADDONS_PL_PATH_PRO.'includes/class.assets.php' );
        require_once( HTMEGA_ADDONS_PL_PATH_PRO.'classes/class.widgets-control.php' );

        // HT Builder
        if ( 'on' == htmega_get_module_option( 'htmega_themebuilder_module_settings','themebuilder','themebuilder_enable','off' ) ) {
            require_once( HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/ht-builder/init.php' );
        } else {
            if ( htmega_get_option_pro( 'themebuilder', 'htmega_advance_element_tabs', 'off' ) === 'on' && empty ( htmega_get_module_option( 'htmega_themebuilder_module_settings') ) ){
                require_once( HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/ht-builder/init.php' );
            }
        }
        // Admin Required File
        if( is_admin() ){

            // Cross Site Copy Pest Manager
            if( htmega_get_option_pro( 'crossdomaincp', 'htmega_advance_element_tabs', 'off' ) === 'on' ){
                require_once( HTMEGA_ADDONS_PL_PATH_PRO . 'includes/class.cross-domain-copy-paste.php' );
            }
            
        }
        // Parallax Module
        if( htmega_get_option_pro( 'parallax_module', 'htmega_advance_element_tabs', 'off' ) === 'on' ){
            require_once( HTMEGA_ADDONS_PL_PATH_PRO.'extensions/parallax/class.parallax.php' );
        }  
        // Particles Module
        if( htmega_get_option_pro( 'particles_module', 'htmega_advance_element_tabs', 'off' ) === 'on' ){
            require_once( HTMEGA_ADDONS_PL_PATH_PRO.'extensions/particles/class.particles.php' );
        }  
        // Conditional Display Module
        if( htmega_get_option_pro( 'd_conditional_module', 'htmega_advance_element_tabs', 'off' ) === 'on' ){
            require_once( HTMEGA_ADDONS_PL_PATH_PRO.'extensions/conditional-display/class.conditional-display.php' );
        }  
        // Advanced Sticky Module
        if( htmega_get_option_pro( 'advanced_sticky_module', 'htmega_advance_element_tabs', 'off' ) === 'on' ){
            require_once( HTMEGA_ADDONS_PL_PATH_PRO.'extensions/advanced-sticky/class.advanced-sticky.php' );
        }  
        // Custom CSS Module
        if ( htmega_get_option_pro( 'custom_css_module', 'htmega_advance_element_tabs', 'off' ) === 'on' ) {
            require_once( HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/custom-css/class.custom-css.php' );
        }
    }

	//Load Elementor Live Editor Modal.
	public function load_el_live_editor_modal() {
		ob_start();
		include_once HTMEGA_ADDONS_PL_PATH_PRO . 'includes/live-editor-modal-template.php';
		$output = ob_get_contents();
		ob_end_clean();
		echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}


	//Live Editor Assets Enqueue.
	public function live_el_editor_asset_enqueue() {

		wp_enqueue_script(
			'htmega-live-editor-js',
			HTMEGA_ADDONS_PL_URL_PRO . 'assets/js/admin/template-live-editor.js',
			array( 'elementor-editor', 'jquery' ),
			HTMEGA_VERSION_PRO,
			true
		);

		$live_editor_data = array(
			'ajaxurl' => esc_url( admin_url( 'admin-ajax.php' ) ),
			'nonce'   => wp_create_nonce( 'htmega-live-editor' ),
		);

		wp_localize_script( 'htmega-live-editor-js', 'liveEditor', $live_editor_data );

	}

	// Get Template Title.
	public function htmega_get_update_title() {
		check_ajax_referer( 'htmega-live-editor', 'security' );
		if ( ! isset( $_POST['id'] ) ) {
			wp_send_json_error();
		}
        $res = get_post($_POST['id']);
		wp_send_json_success( $res );
        exit();
	}


	//Template Validity Check . 
	public function htmega_temp_validity_status() {

		check_ajax_referer( 'htmega-live-editor', 'security' );

		if ( ! isset( $_POST['templateID'] ) ) {
			wp_send_json_error( 'Template ID is not set' );
		}

		$temp_id = sanitize_text_field( wp_unslash( $_POST['templateID'] ) );

		$template_content = $this->template_instance->get_template_content( $temp_id, true );

		if ( empty( $template_content ) || ! isset( $template_content ) ) {

			$res = wp_delete_post( $temp_id, true );

			if ( ! is_wp_error( $res ) ) {
				$res = 'Template Deleted.';
			}
		} else {
			$res = 'Template Has Content.';
		}

		wp_send_json_success( $res );
        exit();
	}

	// Live Editor Handler.
	public function htmega_live_editor_handler() {
		check_ajax_referer( 'htmega-live-editor', 'security' );

		if ( ! isset( $_POST['key'] ) ) {
			wp_send_json_error();
		}

		$template_name  = 'htmega-dynamic-temp-' . sanitize_text_field( wp_unslash( $_POST['key'] ) );
		$template_title = '';
		$args       = array(
			'post_type'              => 'elementor_library',
			'name'                   => $template_name,
			'post_status'            => 'publish',
			'update_post_term_cache' => false,
			'update_post_meta_cache' => false,
			'posts_per_page'         => 1,
		);

		$post = get_posts( $args );
 		// create a new template.
		if ( empty( $post ) ) {

			$key        = sanitize_text_field( wp_unslash( $_POST['key'] ) );
			$template_title = 'Template name-' . substr( md5( $key ), 0, 6 );

			$params = array(
				'post_content' => '',
				'post_type'    => 'elementor_library',
				'post_title'   => $template_title,
				'post_name'    => $template_name,
				'post_status'  => 'publish',
				'meta_input'   => array(
					'_elementor_edit_mode'     => 'builder',
					'_elementor_template_type' => 'page',
					'_wp_page_template'        => 'elementor_canvas',
				),
			);

			$template_id = wp_insert_post( $params );

		} else { // edit template.
			$template_id    = $post[0]->ID;
			$template_title = $post[0]->post_title;
		}

		$edit_url = get_admin_url() . '/post.php?post=' . $template_id . '&action=elementor';

		$result = array(
			'url'   => $edit_url,
			'id'    => $template_id,
			'title' => $template_title,
		);

		wp_send_json_success( $result );
        exit();
	}

}

HTMega_Addons_Elementor_Pro::instance();