<?php
/**
 * Reusable Elementor trait for adding Custom CSS control
 * (Elementor Pro–like functionality).
 *
 * @package Sifency\Traits
 */

namespace Sifency\Traits;

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

use Elementor\Controls_Manager;

trait Sifency_Addons_Custom_CSS_Controls {

	/**
	 * Register Custom CSS controls.
	 *
	 * @param array $args Optional arguments.
	 */
	protected function add_Sifency_Addons_Custom_CSS_Controls( array $args = array() ) {

		$args = wp_parse_args(
			$args,
			array(
				'condition' => array(),
			)
		);

		$this->start_controls_section(
			'section_sifency_custom_css',
			array(
				'label'     => esc_html__( 'Sifency Custom CSS', 'sifency-addons' ),
				'tab'       => Controls_Manager::TAB_ADVANCED,
				'condition' => $args['condition'],
			)
		);

		$this->add_control(
			'sifency_custom_css',
			array(
				'type'        => Controls_Manager::CODE,
				'language'    => 'css',
				'render_type' => 'none',
				'description' => wp_kses(
					__( 'Use <code>selector</code> to target this widget only.<br><br><strong>Example:</strong><br><code>selector .title { color: red; }</code>', 'sifency-addons' ),
					array(
						'br'     => array(),
						'code'   => array(),
						'strong' => array(),
					)
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Print Custom CSS during widget render.
	 * Call this inside render().
	 */
	protected function sifency_addons_render_custom_css() {

		$settings = $this->get_settings_for_display();

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

		$css = trim( $settings['sifency_custom_css'] );

		if ( '' === $css ) {
			return;
		}

		$css = str_replace(
			'selector',
			$this->get_unique_selector(),
			$css
		);

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Scoped custom CSS output
		printf(
			'<style>%s</style>',
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS is stripped of HTML tags before output in a style block.
			wp_strip_all_tags( $css )
		);
	}
}
