<?php
add_filter('comment_form_default_fields', 'book_review_blog_comment_form');
function book_review_blog_comment_form($book_review_blog_comment_field) {
    $commenter = wp_get_current_commenter();
    $req = get_option('require_name_email'); // Check if name and email are required
    $aria_req = ($req ? ' aria-required="true" required' : '');

    $book_review_blog_comment_field['author'] = '<p class="comment-form-author"><label for="name-cmt" class="screen-reader-text">' . esc_html__('Your Name', 'book-review-blog') . '</label><input type="text" class="form-control" name="author" id="name-cmt" value="' . esc_attr($commenter['comment_author']) . '" placeholder="' . esc_attr__('Your Name', 'book-review-blog') . '"' . $aria_req . '></p>';

    $book_review_blog_comment_field['email'] = '<p class="comment-form-email"><label for="email-cmt" class="screen-reader-text">' . esc_html__('Your Email', 'book-review-blog') . '</label><input type="email" class="form-control" name="email" id="email-cmt" value="' . esc_attr($commenter['comment_author_email']) . '" placeholder="' . esc_attr__('Your Email', 'book-review-blog') . '"' . $aria_req . '></p>';

    $book_review_blog_comment_field['url'] = '<p class="comment-form-url"><label for="website" class="screen-reader-text">' . esc_html__('Your Website', 'book-review-blog') . '</label><input type="text" class="form-control" name="url" id="website" value="' . esc_attr($commenter['comment_author_url']) . '" placeholder="' . esc_attr__('Your Website', 'book-review-blog') . '"></p>';

    return $book_review_blog_comment_field;
}

add_filter('comment_form_defaults', 'book_review_blog_comment_default_form');
function book_review_blog_comment_default_form($default_form) {
    $default_form['comment_field'] = '<p class="comment-form-comment"><label for="comment" class="screen-reader-text">' . esc_html__('Comment', 'book-review-blog') . '</label><textarea class="form-control" name="comment" id="comment" rows="7" placeholder="' . esc_attr__('Message goes here', 'book-review-blog') . '" aria-required="true" required></textarea></p>';

    $default_form['submit_button'] = '<button type="submit" class="btn btn-primary">' . esc_attr__('Post Comment', 'book-review-blog') . '</button>';
    $default_form['comment_notes_before'] = '';
    $default_form['title_reply'] = esc_attr__('Leave A Comment', 'book-review-blog');
    $default_form['title_reply_before'] = '<h4>';
    $default_form['title_reply_after'] = '</h4>';

    return $default_form;
}

function book_review_blog_comment_form_structure( $fields ) {
		$author_field = $fields['author'];
		$email_field = $fields['email'];
		if (function_exists('is_woocommerce') && !is_woocommerce()) {
			$url_field = $fields['url'];
		}
		$comment_field = $fields['comment'];
		$cookies_field = $fields['cookies'];
		unset( $fields['author'] );
		unset( $fields['email'] );
		unset( $fields['url'] );
		unset( $fields['comment'] );
		unset( $fields['cookies'] );
		$fields['author'] = $author_field;
		$fields['email'] = $email_field;
		if (function_exists('is_woocommerce') && !is_woocommerce()) {
			$fields['url'] = $url_field;
		}
		$fields['comment'] = $comment_field;
		$fields['cookies'] = $cookies_field;
	return $fields;
}

add_filter( 'comment_form_fields', 'book_review_blog_comment_form_structure' );

if (!function_exists('book_review_blog_comment_list')) :
    /**
     * Template for comments and pingbacks.
     *
     * Used as a callback by wp_list_comments() for displaying the comments.
     *
     * @since Book Review Blog 1.0
     */
    function book_review_blog_comment_list($comment, $args, $depth) {
        $tag = ('div' === $args['style']) ? 'div' : 'li';
        $add_below = ('div' === $args['style']) ? 'comment' : 'div-comment';
        ?>
        <<?php echo esc_attr($tag); ?> <?php comment_class(empty($args['has_children']) ? '' : 'parent', null, null, false); ?> id="comment-<?php comment_ID(); ?>">
            <?php if ('div' === $args['style']) : ?>
                <div id="div-comment-<?php comment_ID(); ?>" class="comment-body review-list">
            <?php endif; ?>
            <article class="single-comment" role="article">
                <div class="commenter-image">
                    <?php if (0 != $args['avatar_size']) : ?>
                        <?php echo get_avatar($comment, $args['avatar_size'], '', esc_attr__('Commenter avatar', 'book-review-blog'), ['class' => 'avatar', 'loading' => 'lazy']); ?>
                    <?php endif; ?>
                </div>
                <div class="commnenter-details">
                    <footer class="comment-meta">
                        <div class="comment-author vcard">
                            <h4 class="fn"><?php echo wp_kses_post(get_comment_author_link()); ?></h4>
                        </div>
                        <div class="comment-time">
                            <p>
                                <a href="<?php echo esc_url(get_comment_link($comment->comment_ID)); ?>">
                                    <time datetime="<?php comment_time('c'); ?>">
                                        <?php printf(esc_html__('%1$s at %2$s', 'book-review-blog'), get_comment_date(), get_comment_time()); ?>
                                    </time>
                                </a>
                            </p>
                        </div>
                        <?php if ($comment->comment_approved == '0') : ?>
                            <p class="comment-awaiting-moderation"><?php esc_html_e('Your comment is awaiting moderation.', 'book-review-blog'); ?></p>
                        <?php endif; ?>
                    </footer>
                    <div class="comment-content">
                        <?php comment_text(); ?>
                    </div>
                    <?php
                    comment_reply_link(
                        array_merge(
                            $args,
                            [
                                'depth'     => $depth,
                                'max_depth' => $args['max_depth'],
                                'before'    => '<div class="reply"><span class="rswpthemes-icon icon-reply-solid"></span>',
                                'after'     => '</div>',
                                'reply_text' => esc_html__('Reply', 'book-review-blog'),
                                'add_below' => $add_below,
                            ]
                        )
                    );
                    ?>
                    <?php if ($rating = get_comment_meta($comment->comment_ID, 'rating', true)) : ?>
                        <div class="comment-rating"><?php printf(esc_html__('Rating: %s/5', 'book-review-blog'), absint($rating)); ?></div>
                    <?php endif; ?>
                </div>
            </article>
            <?php if ('div' === $args['style']) : ?>
                </div>
            <?php endif; ?>
        <?php
    }
endif;


// Add nonce to comment form for CSRF protection
add_filter('comment_form_defaults', 'book_review_blog_add_nonce_to_comment_form');
function book_review_blog_add_nonce_to_comment_form($defaults) {
    $defaults['comment_notes_before'] = wp_nonce_field('book_review_blog_comment_nonce', 'comment_nonce', true, false);
    return $defaults;
}

// Validate and sanitize comment form inputs
add_filter('preprocess_comment', 'book_review_blog_validate_comment_data');
function book_review_blog_validate_comment_data($commentdata) {
    // Verify nonce
    if (!isset($_POST['comment_nonce']) || !wp_verify_nonce($_POST['comment_nonce'], 'book_review_blog_comment_nonce')) {
        wp_die(esc_html__('Security check failed. Please try again.', 'book-review-blog'));
    }

    // Sanitize inputs
    $commentdata['comment_content'] = sanitize_textarea_field($commentdata['comment_content']);
    $commentdata['comment_author'] = sanitize_text_field($commentdata['comment_author']);
    $commentdata['comment_author_email'] = sanitize_email($commentdata['comment_author_email']);
    $commentdata['comment_author_url'] = esc_url_raw($commentdata['comment_author_url']);

    // Validate email format
    if (!empty($commentdata['comment_author_email']) && !is_email($commentdata['comment_author_email'])) {
        wp_die(esc_html__('Invalid email address.', 'book-review-blog'));
    }

    return $commentdata;
}
