<?php
namespace AvasElements\Modules\CustomCss;

use AvasElements\Base\Module_Base;
use Elementor\Controls_Manager;
// use Elementor\Group_Control_Box_Shadow;

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

class Module extends Module_Base {

    // 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', [$this, 'avas_add_post_css'], 10, 2);
    }

    public function get_name() {
		return 'avas-custom-css';
	}

    /**
     * Register Custom CSS Controls in Elementor Free.
     */
    public function register_controls( $element, $section_id ) {
        // Elementor Free uses 'section_custom_css' instead of 'section_custom_css_pro'
        if ('section_custom_css' !== $section_id) {
            return;
        }

        $element->start_controls_section(
            'section_avas_custom_css',
            [
                'label' => __( 'Avas Custom CSS', 'avas-core' ),
                'tab'   => Controls_Manager::TAB_ADVANCED,
            ]
        );

        $element->add_control(
            'avas_custom_css',
            [
                'type'        => Controls_Manager::CODE,
                'label'       => __( 'Custom CSS', 'avas-core' ),
                'label_block' => true,
                'language'    => 'css',
                'description' => __( 'Use "selector" keyword to target wrapper element. Example: selector { background-color: #000 !important; }', 'avas-core' ),
                'render_type' => 'ui',
            ]
        );

        $element->end_controls_section();
    }

    /**
     * Add Custom CSS to Elementor Widgets.
     */
    public function avas_add_post_css( $post_css, $element ) {
        $settings = $element->get_settings_for_display();

        if ( empty( $settings['avas_custom_css'] ) ) {
            return;
        }

        $generated_css = trim( $settings['avas_custom_css'] );

        if ( empty( $generated_css ) ) {
            return;
        }

        // Replace 'selector' with the actual element selector
        $generated_css = str_replace( 
            'selector', 
            $post_css->get_element_unique_selector( $element ), 
            $generated_css 
        );

        // Format CSS correctly
        $generated_css = sprintf( 
            "/* Start custom CSS for %s, class: %s */\n%s\n/* End custom CSS */",
            esc_html( $element->get_name() ),
            esc_html( $element->get_unique_selector() ),
            $generated_css
        );

        if ( method_exists( $post_css->get_stylesheet(), 'add_raw_css' ) ) {
            $post_css->get_stylesheet()->add_raw_css( $generated_css );
        }
    }
}

