<?php
/**
 * Abstract base class for Smart Post Show Blocks.
 *
 * @package Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/blocks/includes
 */

namespace SmartPostShow\Blocks;

use SmartPostShow\Blocks\Block_Base;

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

/**
 * Post_Comment block class for rendering comments and comment form.
 */
class Post_Comment extends Block_Base {

	/**
	 * Settings variable.
	 *
	 * @var array
	 */
	protected static $settings = array();

	protected $field_sort_array = array();

	/**
	 * Set_block_properties function
	 *
	 * @return void
	 */
	protected function set_block_properties() {
		$this->block_name = 'post-comment';
		$this->styles     = array( 'sp_smart_post_blocks_google_fonts' );

		add_filter( 'comment_form_fields', array( $this, 'sp_custom_comment_field_order' ) );
	}

	/**
	 * Comment_callback function
	 *
	 * @param object $comment The comment object.
	 * @param array  $args    Comment form arguments.
	 * @param int    $depth   The depth of the current comment.
	 * @return void
	 */
	public static function comment_callback( $comment, $args, $depth ) {
		$show_name  = self::$settings['show_name'] ?? '';
		$show_des   = self::$settings['show_des'] ?? '';
		$show_image = self::$settings['show_image'] ?? '';
		$show_meta  = self::$settings['show_meta'] ?? '';

		?>
		<li id="comment-<?php comment_ID(); ?>" <?php comment_class( 'sp-smart-post-comment-item' ); ?>>

			<div class="sp-smart-post-comment-box">

				<div class="sp-smart-post-comment-avatar">
					<?php if ( $show_image ) { ?>
						<?php echo get_avatar( $comment, 60 ); ?>	
					<?php } ?>

					<div class="sp-smart-post-comment-author-info">
						
						<?php if ( $show_name ) { ?>
							<span class="sp-smart-post-comment-author">
								<?php echo get_comment_author_link(); ?>
							</span>
						<?php } ?>

						<?php if ( $show_meta ) { ?>
							<span class="sp-smart-post-comment-date">
								<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
									<?php echo wp_kses_post( get_comment_date() ); ?>
								</a>
							</span>
						<?php } ?>
					</div>
				</div>

				<div class="sp-smart-post-comment-content">
					<?php if ( $show_name ) { ?>
						<div class="sp-smart-post-comment-text">
							<?php comment_text(); ?>
						</div>
					<?php } ?>

					<div class="sp-smart-post-comment-actions">
						<?php
						// Reply link.
						comment_reply_link(
							array_merge(
								$args,
								array(
									'reply_text' => __( 'Reply', 'smart-post-show-pro' ),
									'depth'      => $depth,
									'max_depth'  => 5,
								)
							)
						);
						?>
					</div>

				</div>

			</div>
		<?php
	}

	/**
	 * Render Block
	 *
	 * @param array  $attributes The block attributes.
	 * @param string $content The block content.
	 * @param array  $blocks The blocks array.
	 * @return string
	 */
	public function render_block( $attributes, $content = '', $blocks = array() ) {

		if ( \SmartPostShow\Blocks\Helper::is_editor_page() ) {
			return $content;
		}
		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
			wp_enqueue_script( 'comment-reply' );
		}

		$unique_id               = $attributes['uniqueId'] ?? '';
		$name_label              = $attributes['nameLabel'] ?? '';
		$name_placeholder        = $attributes['namePlaceholder'] ?? '';
		$email_label             = $attributes['emailLabel'] ?? '';
		$email_placeholder       = $attributes['emailPlaceholder'] ?? '';
		$website_label           = $attributes['websiteLabel'] ?? '';
		$website_placeholder     = $attributes['websitePlaceholder'] ?? '';
		$comment_box_label       = $attributes['commentBoxLabel'] ?? '';
		$comment_box_placeholder = $attributes['commentBoxPlaceholder'] ?? '';
		$save_info_consent       = $attributes['saveInfoConsent'] ?? '';
		$btn_label               = $attributes['btnLabel'] ?? '';
		$btn_full                = $attributes['fullWidth'] ?? '';
		$form_heading_label      = $attributes['formHeadingLabel'] ?? '';
		$form_sub_heading_label  = $attributes['formSubHeadingLabel'] ?? '';
		$show_form_heading       = $attributes['showFormHeading'] ?? '';
		$show_form_sub_heading   = $attributes['showFormSubHeading'] ?? '';
		$show_comment_count      = $attributes['showCommentCount'] ?? '';
		$comment_text            = $attributes['commentText'] ?? '';
		$show_name               = $attributes['showCommentatorName'] ?? '';
		$show_des                = $attributes['showDescription'] ?? '';
		$show_image              = $attributes['showCommentatorImage'] ?? '';
		$show_meta               = $attributes['showMetaFields'] ?? '';
		$comment_form_sort_array = $attributes['commentFormSortArray'] ?? '';
		$disabled_website        = $attributes['disableWebsite'] ?? '';
		$additional_id           = $attributes['additionalId'] ?? '';
		$additional_class        = $attributes['additionalCssClass'] ?? '';

		$this->field_sort_array = $comment_form_sort_array;

		self::$settings = array(
			'show_name'  => $show_name,
			'show_des'   => $show_des,
			'show_image' => $show_image,
			'show_meta'  => $show_meta,
		);

		$commenter = wp_get_current_commenter();
		$req       = get_option( 'require_name_email' );
		$aria_req  = ( $req ? " aria-required='true'" : '' );

		/* ---------- Static Labels ---------- */
		$auth_label    = '<label for="author">' . $name_label . ( $req ? '<span class="required">*</span>' : '' ) . '</label>';
		$email_label   = '<label for="email">' . $email_label . ( $req ? '<span class="required">*</span>' : '' ) . '</label>';
		$url_label     = '<label for="url">' . $website_label . '</label>';
		$comment_label = '<label for="comment">' . $comment_box_label . ( $req ? '<span class="required">*</span>' : '' ) . '</label>';

		$cookies_label = '
		<p class="comment-form-cookies-consent">
			<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"/>
			<label for="wp-comment-cookies-consent">' . $save_info_consent . '</label>
		</p>';

		/* ---------- Comment Form Args ---------- */
		$comments_args = array(
			'comment_field'        =>
				'<div class="comment-form-comment sp-smart-post-comment-input sp-smart-post-field-control">'
				. $comment_label .
				'<textarea id="comment" name="comment" placeholder="' . $comment_box_placeholder . '" cols="45" rows="8" aria-required="true"></textarea>
				</div>',

			'fields'               => array(
				'author'  =>
					'<div class="sp-smart-post-field-control sp-smart-post-comment-name">'
					. $auth_label .
					'<input id="author" name="author" type="text" placeholder="' . $name_placeholder . '"
					value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' />
					</div>',

				'email'   =>
					'<div class="sp-smart-post-field-control sp-smart-post-comment-email">'
					. $email_label .
					'<input id="email" name="email" type="email" placeholder="' . $email_placeholder . '"
					value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' />
					</div>',

				'url'     => $disabled_website ? '' :
					'<div class="sp-smart-post-field-control sp-smart-post-comment-website">'
					. $url_label .
					'<input id="url" name="url" type="url" placeholder="' . $website_placeholder . '"
					value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" />
					</div>',

				'cookies' => $cookies_label,
			),

			'class_submit'         => $btn_full ? 'sp-smart-post-comment-btn sp-btn-full' : 'sp-smart-post-comment-btn',
			'class_form'           => 'sp-smart-post-comment-form',
			'class_container'      => 'sp-smart-post-comment-form-container',
			'comment_notes_after'  => '',
			'comment_notes_before' => $show_form_sub_heading ?
				'<div class="comment-notes">
				<span>' . $form_sub_heading_label . '</span><span class="required">*</span>
			</div>' : '',
			'submit_button'        =>
				'<input name="%1$s" type="submit" id="%2$s" class="%3$s"
				value="' . $btn_label . '" />',

			'title_reply'          => $show_form_heading ?
				'<div class="sp-smart-post-comment-title">' . $form_heading_label . '</div>' : '',
		);

		if ( ! $show_form_sub_heading ) {
			$comments_args['logged_in_as'] = '';
		}

		/* ---------- Comment List Args ---------- */
		$list_args = array(
			'style'             => 'ul',
			'walker'            => '',
			'type'              => 'comment',
			'avatar_size'       => 32,
			'max_depth'         => 5,
			'reverse_top_level' => true,
			'format'            => current_theme_supports( 'html5', 'comment-list' ) ? 'html5' : 'xhtml',
			'callback'          => array( __CLASS__, 'comment_callback' ),
		);

		/* ---------- Get Comments ---------- */
		$moderation_enable = get_option( 'comment_moderation' );
		$comments          = get_comments(
			array(
				'post_id' => get_the_ID(),
				'status'  => $moderation_enable ? 'approve' : 'all',
			)
		);

		/* ---------- Wrapper Markup ---------- */
		$id_attr        = ! empty( $additional_id ) ? ' id="' . esc_attr( $additional_id ) . '"' : '';
		$wrapper_before = '
		<div' . $id_attr . ' class="sp-smart-post-wrapper ' . $additional_class . '">
			<div id="' . esc_attr( $unique_id ) . '" class="sp-smart-post-comment">';

		$wrapper_content = '';

		$update_comment_text     = $comment_text;
		$is_default_comment_text = in_array( $comment_text, array( 'Comments', 'comments', 'Comment', 'comment' ), true );
		if ( $show_comment_count && $is_default_comment_text ) {
			if ( 1 === count( $comments ) ) {
				$update_comment_text = preg_replace( '/(s)$/i', '', $comment_text );
			} elseif ( 1 < count( $comments ) ) {
				$update_comment_text = preg_replace( '/(s)$/i', '', $comment_text ) . 's';
			}
		}

		if ( count( $comments ) > 0 ) {
			$wrapper_content .= '
			<div class="sp-smart-post-comment-reply-heading">'
				. ( $show_comment_count ? count( $comments ) : '' ) . ' ' . $update_comment_text .
			'</div>';
		}

		$wrapper_content .= '<ul class="sp-smart-post-comment-list">';
			ob_start();
			wp_list_comments( $list_args, $comments );
			$wrapper_content .= ob_get_clean();
		$wrapper_content     .= '</ul>';

		$wrapper_content .= '<div class="sp-smart-post-comment-form-wrap">';
			ob_start();
			comment_form( $comments_args );
			$wrapper_content .= ob_get_clean();
		$wrapper_content     .= '</div>';

		$wrapper_after = '</div></div>';

		return $wrapper_before . $wrapper_content . $wrapper_after;
	}

	/**
	 * Comment field sorting function.
	 *
	 * @param array $fields array of comment form field.
	 * @return array
	 */
	public function sp_custom_comment_field_order( $fields ) {

		$map = array(
			'name'       => 'author',
			'email'      => 'email',
			'commentBox' => 'comment',
			'website'    => 'url',
		);

		$sorted = array();

		foreach ( $this->field_sort_array as $item ) {

			if ( empty( $map[ $item['value'] ] ) ) {
				continue;
			}

			$key = $map[ $item['value'] ];

			if ( isset( $fields[ $key ] ) ) {
				$sorted[ $key ] = $fields[ $key ];
			}
		}

		// Append remaining fields (cookies, etc.).
		return $sorted + $fields;
	}
}
