<?php
namespace SabaiApps\Directories\Component\WordPressContent\DisplayElement;

use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Context;

class CommentsDisplayElement extends Display\Element\AbstractElement {

	protected function _displayElementInfo( Entity\Model\Bundle $bundle ) {
		return array(
			'type'             => 'content',
			'label'            => _x( 'Comments', 'display element name', 'directories-pro' ),
			'description'      => __( 'Comments posted for the current content', 'directories-pro' ),
			'default_settings' => array(),
			'icon'             => 'far fa-comments',
			'designable'       => array( 'margin', 'padding' ),
		);
	}

	protected function _displayElementSupports( Entity\Model\Bundle $bundle, Display\Model\Display $display ) {
		return $display->type === 'entity' && empty( $bundle->info['is_taxonomy'] );
	}

	public function displayElementRender( Entity\Model\Bundle $bundle, array $element, $var, ?array $context = null ) {
		// Comments may be disabled
		if ( ! post_type_supports( $bundle->name, 'comments' ) ) {
			return __( 'Comments are not supported.', 'directories-pro' );
		}

		if ( ! comments_open( $var->getId() ) ) {
			return __( 'Comments are closed.', 'directories-pro' );
		}

		if ( ! $post = $var->post() ) {
			return;
		}

		setup_postdata( $post );
		$GLOBALS['post'] = $post;
		add_filter( 'deprecated_file_trigger_error', '__return_false' ); // Suppress deprecated error for FSE themes.
		ob_start();
		comments_template( '', true );
		$ret = ob_get_clean();
		remove_filter( 'deprecated_file_trigger_error', '__return_false' );
		wp_reset_postdata();

		return $ret;
	}
}
