<?php 
namespace HTMega_Custom_Css;
use Elementor\Controls_Manager;

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

class HTMegaCustomCss_Elementor {

    private static $_instance = null;
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
    public function __construct() {
		add_action('elementor/element/after_section_end', [$this, 'register_controls'], 20, 2);
		add_action('elementor/element/parse_css', array( $this, 'htmega_add_post_css'), 10, 2 );
    }

	/**
	 * Register Custom CSS controls.
	 *
	 * @since 1.6.3
	 * @access public
	 * @param object $element for current element.
	 */
	public function register_controls( $element, $section_id ) {
		
		if ('section_custom_css_pro' !== $section_id) {
			return;
		}
		$element->start_controls_section(
			'section_htmega_custom_css',
			array(
				'label' => __( 'HT Mega Custom CSS', 'htmega-pro' ),
				'tab'   => Controls_Manager::TAB_ADVANCED,
			)
		);

		$element->add_control(
			'htmega_custom_css',
			array(
				'type'        => Controls_Manager::CODE,
				'label'       => __('Custom CSS', 'htmega-pro' ),
				'label_block' => true,
				'language'    => 'css',
				'description' => __('Use "selector" keyword to target wrapper element. Example: selector { background-color: #D73361; }', 'htmega-pro' ),
				'render_type' => 'ui',
			)
		);
		$element->end_controls_section();

	}

	/**
	 * Render HTML output on the frontend.
	 *
	 * Written in PHP and used to generate the final Output.
	 *
	 * @since 1.6.3
	 * @access public
	 * @param object $element for current element.
	 */
	public function htmega_add_post_css( $post_css, $element ) {
		$settings = $element->get_settings();

		if ( empty( $settings['htmega_custom_css'] ) ) {
			return;
		}
		$generated_css = trim( $settings['htmega_custom_css'] );

		if ( empty( $generated_css ) ) {
			return;
		}
		$generated_css = str_replace( 'selector', $post_css->get_element_unique_selector( $element ), $generated_css );

		// Add a css comment
		$generated_css = sprintf( '/* Start custom CSS for %s, class: %s */', $element->get_name(), $element->get_unique_selector() ) . $generated_css . '/* End custom CSS */';

		$post_css->get_stylesheet()->add_raw_css( $generated_css );
		
		// enqueue editor css
		wp_enqueue_script('htmega-widgets-editor');
	}
}

HTMegaCustomCss_Elementor::instance();