<?php
/**
 * Shared renderer for semantic MuchWOW Elementor widgets.
 *
 * The original demo fragment remains the visual source of truth, while each
 * semantic widget gets its own Elementor identity, editable content and a
 * complete Style tab.
 *
 * @package Shabnam_MuchWOW
 */

defined( 'ABSPATH' ) || exit;

abstract class Shabnam_Elementor_Fragment_Widget_Base extends Shabnam_Elementor_Widget_Base {
	protected function register_controls() {
		$this->start_controls_section(
			'section_content',
			array( 'label' => __( 'محتوای بخش', 'shabnam-muchwow' ) )
		);

		$this->add_control(
			'section_label',
			array(
				'label'       => __( 'نام بخش در ویرایشگر', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'label_block' => true,
				'default'     => $this->get_title(),
			)
		);
		$this->add_control( 'demo_key', array( 'type' => \Elementor\Controls_Manager::HIDDEN, 'default' => 'one' ) );
		$this->add_control( 'section_key', array( 'type' => \Elementor\Controls_Manager::HIDDEN, 'default' => '' ) );

		$text_repeater = new \Elementor\Repeater();
		$text_repeater->add_control( 'key', array( 'type' => \Elementor\Controls_Manager::HIDDEN ) );
		$text_repeater->add_control(
			'label',
			array(
				'label'       => __( 'عنوان فیلد', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'label_block' => true,
			)
		);
		$text_repeater->add_control(
			'value',
			array(
				'label'       => __( 'متن', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::TEXTAREA,
				'rows'        => 3,
				'label_block' => true,
			)
		);
		$this->add_control(
			'texts',
			array(
				'label'       => __( 'متن‌های قابل ویرایش', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::REPEATER,
				'fields'      => $text_repeater->get_controls(),
				'title_field' => '{{{ label }}}',
			)
		);

		$image_repeater = new \Elementor\Repeater();
		$image_repeater->add_control( 'key', array( 'type' => \Elementor\Controls_Manager::HIDDEN ) );
		$image_repeater->add_control(
			'label',
			array(
				'label'       => __( 'عنوان تصویر', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'label_block' => true,
			)
		);
		$image_repeater->add_control(
			'image',
			array(
				'label'   => __( 'تصویر', 'shabnam-muchwow' ),
				'type'    => \Elementor\Controls_Manager::MEDIA,
				'dynamic' => array( 'active' => true ),
			)
		);
		$this->add_control(
			'images',
			array(
				'label'       => __( 'تصاویر قابل ویرایش', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::REPEATER,
				'fields'      => $image_repeater->get_controls(),
				'title_field' => '{{{ label }}}',
			)
		);

		$link_repeater = new \Elementor\Repeater();
		$link_repeater->add_control( 'key', array( 'type' => \Elementor\Controls_Manager::HIDDEN ) );
		$link_repeater->add_control(
			'label',
			array(
				'label'       => __( 'عنوان پیوند', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'label_block' => true,
			)
		);
		$link_repeater->add_control(
			'link',
			array(
				'label'       => __( 'نشانی پیوند', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::URL,
				'label_block' => true,
				'placeholder' => 'https://',
			)
		);
		$this->add_control(
			'links',
			array(
				'label'       => __( 'پیوندهای قابل ویرایش', 'shabnam-muchwow' ),
				'type'        => \Elementor\Controls_Manager::REPEATER,
				'fields'      => $link_repeater->get_controls(),
				'title_field' => '{{{ label }}}',
			)
		);
		$this->end_controls_section();

		$this->shabnam_register_common_style_controls();
	}

	private function fragment_path( $section_key ) {
		$section_key = sanitize_key( (string) $section_key );
		if ( ! preg_match( '/^(one|two|three)-[0-9]{2}$/', $section_key ) ) {
			return '';
		}
		$file = trailingslashit( get_template_directory() ) . 'inc/elementor/demo-fragments/' . $section_key . '.php';
		return is_readable( $file ) ? $file : '';
	}

	protected function render() {
		$settings = $this->get_settings_for_display();
		$file     = $this->fragment_path( isset( $settings['section_key'] ) ? $settings['section_key'] : '' );
		if ( ! $file ) {
			if ( current_user_can( 'edit_theme_options' ) ) {
				echo '<div class="shabnam-section-card p-3">' . esc_html__( 'ساختار این بخش پیدا نشد. پوسته را دوباره نصب یا به‌روزرسانی کنید.', 'shabnam-muchwow' ) . '</div>';
			}
			return;
		}

		$markup = include $file;
		if ( ! is_string( $markup ) || '' === trim( $markup ) ) {
			return;
		}
		$markup = str_replace( '__SHCD_THEME_URI__', esc_url( untrailingslashit( get_template_directory_uri() ) ), $markup );

		foreach ( isset( $settings['texts'] ) && is_array( $settings['texts'] ) ? $settings['texts'] : array() as $item ) {
			$key = isset( $item['key'] ) ? sanitize_key( $item['key'] ) : '';
			if ( preg_match( '/^t[0-9]+$/', $key ) ) {
				$markup = str_replace( '%%SHCD_TEXT_' . $key . '%%', esc_html( isset( $item['value'] ) ? (string) $item['value'] : '' ), $markup );
			}
		}
		foreach ( isset( $settings['images'] ) && is_array( $settings['images'] ) ? $settings['images'] : array() as $item ) {
			$key = isset( $item['key'] ) ? sanitize_key( $item['key'] ) : '';
			if ( ! preg_match( '/^i[0-9]+$/', $key ) ) { continue; }
			$url = '';
			if ( ! empty( $item['image']['id'] ) ) {
				$attachment = wp_get_attachment_image_url( absint( $item['image']['id'] ), 'full' );
				if ( $attachment ) { $url = $attachment; }
			}
			if ( ! $url && ! empty( $item['image']['url'] ) ) { $url = (string) $item['image']['url']; }
			$markup = str_replace( '%%SHCD_IMG_' . $key . '%%', esc_url( $url ), $markup );
		}
		foreach ( isset( $settings['links'] ) && is_array( $settings['links'] ) ? $settings['links'] : array() as $item ) {
			$key = isset( $item['key'] ) ? sanitize_key( $item['key'] ) : '';
			if ( ! preg_match( '/^l[0-9]+$/', $key ) ) { continue; }
			$url = isset( $item['link']['url'] ) ? (string) $item['link']['url'] : '#';
			$markup = str_replace( '%%SHCD_LINK_' . $key . '%%', esc_url( $url ? $url : '#' ), $markup );
		}
		$markup = preg_replace( '/%%SHCD_(?:TEXT|IMG|LINK)_[a-z0-9]+%%/', '', $markup );
		?>
		<div class="shabnam-demo-editable-section shabnam-elementor-section shabnam-semantic-widget" data-shabnam-section="<?php echo esc_attr( isset( $settings['section_key'] ) ? $settings['section_key'] : '' ); ?>">
			<?php echo $markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Theme-owned markup; user values are escaped before replacement. ?>
		</div>
		<?php
	}
}
