<?php
/**
 * User Comments Block Template
 *
 * @since 4.2.0
 *
 * @var WP_User $user User object
 * @var array $attributes Block attributes
 * @var string $content Block content
 * @var WP_Block $block Block instance
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! $user ) {
    return;
}

$comments_per_page = ! empty( $attributes['commentsPerPage'] ) ? intval( $attributes['commentsPerPage'] ) : 5;
$show_content = ! empty( $attributes['showContent'] ) ? $attributes['showContent'] : true;
$show_date = ! empty( $attributes['showDate'] ) ? $attributes['showDate'] : true;
$show_label = ! empty( $attributes['showLabel'] ) ? $attributes['showLabel'] : true;
$label_text = ! empty( $attributes['labelText'] ) ? $attributes['labelText'] : __( 'Recent Comments', 'wpuf-pro' );

// Get user comments
$user_comments = get_comments( [
    'user_id'     => $user->ID,
    'number'      => $comments_per_page,
    'status'      => 'approve',
    'orderby'     => 'comment_date',
    'order'       => 'DESC',
] );

// Don't show anything if no comments
if ( empty( $user_comments ) ) {
    return;
}

// Get block wrapper attributes (includes styling from block editor)
$wrapper_attributes = wpuf_get_block_wrapper_attributes( $attributes, 'comments', [
    'data-user-id' => $user->ID,
] );

?>
<div <?php echo $wrapper_attributes; ?>>
    <?php if ( $show_label ) : ?>
    <div>
        <strong><?php echo esc_html( $label_text ); ?></strong>
    </div>
    <?php endif; ?>

    <div>
        <?php foreach ( $user_comments as $comment ) : ?>
        <div>
            <div>
                <span>
                    <?php esc_html_e( 'On:', 'wpuf-pro' ); ?>
                    <a href="<?php echo esc_url( get_permalink( $comment->comment_post_ID ) ); ?>">
                        <?php echo esc_html( get_the_title( $comment->comment_post_ID ) ); ?>
                    </a>
                </span>

                <?php if ( $show_date ) : ?>
                <span>
                    <small><?php echo esc_html( get_comment_date( '', $comment ) ); ?></small>
                </span>
                <?php endif; ?>
            </div>

            <?php if ( $show_content ) : ?>
            <div>
                <?php
                $content = get_comment_text( $comment );
                // Limit content length for better display
                if ( strlen( $content ) > 150 ) {
                    $content = substr( $content, 0, 150 ) . '...';
                }
                echo '<p>' . esc_html( $content ) . '</p>';
                ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>
