<?php
/*
Theme Designed By: Meysam Hosseinkhani
Email: Meysam98@Gmail.com
Author Website: i-design.ir
*/
if ( ! defined( 'ABSPATH' ) ) exit;

function dina_enqueue_comments_script() {
    if ( is_singular() && comments_open() && ( dina_opt( 'product_comments_ajax_load' ) || dina_opt( 'post_comments_ajax_load' ) ) ) {
        $post_type = get_post_type( get_the_ID() );
        $raw_value = dina_opt( $post_type === 'product' ? 'product_comments_per_page' : 'post_comments_per_page' );
        $comments_per_page = ( is_numeric( $raw_value ) && (int) $raw_value > 0 ) ? (int) $raw_value : 6;
        $total_parent_comments = get_comments( array(
            'post_id' => get_the_ID(),
            'status'  => 'approve',
            'parent'  => 0,
            'count'   => true,
        ) );

        if ( $total_parent_comments > $comments_per_page ) {
            wp_enqueue_script(
                'dina-comments-js',
                DI_URI . '/js/comments-load-more.js',
                array( 'jquery' ),
                DI_VER,
                true
            );

            wp_localize_script( 'dina-comments-js', 'dina_ajax', array(
                'ajax_url'        => admin_url( 'admin-ajax.php' ),
                'load_more_text'  => $post_type === 'product' ? __( 'Load More Reviews', 'dina-kala' ) : __( 'Load More Comments', 'dina-kala' ),
                'loading_text'    => __( 'Loading...', 'dina-kala' ),
                'error_text'      => __( 'Error loading comments', 'dina-kala' ),
                'nonce'           => wp_create_nonce( 'dina_load_more_comments_nonce' ),
            ) );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'dina_enqueue_comments_script' );

add_action( 'wp_ajax_load_more_comments', 'dina_load_more_comments' );
add_action( 'wp_ajax_nopriv_load_more_comments', 'dina_load_more_comments' );

function dina_get_all_child_comments( $comment_ids, $post_id ) {
    $all_comments = array();
    
    if ( empty( $comment_ids ) ) {
        return $all_comments;
    }

    $child_comments = get_comments( array(
        'post_id'      => $post_id,
        'status'       => 'approve',
        'parent__in'   => $comment_ids,
        'order'        => 'ASC',
        'meta_query'   => array(
            'relation' => 'OR',
            array(
                'key'     => 'verified',
                'compare' => 'EXISTS',
            ),
            array(
                'key'     => 'verified',
                'compare' => 'NOT EXISTS',
            ),
        ),
    ) );

    if ( ! empty( $child_comments ) ) {
        $all_comments = array_merge( $all_comments, $child_comments );
        $child_ids = wp_list_pluck( $child_comments, 'comment_ID' );
        $grandchild_comments = dina_get_all_child_comments( $child_ids, $post_id );
        $all_comments = array_merge( $all_comments, $grandchild_comments );
    }

    return $all_comments;
}

// Custom function for rendering WooCommerce comments
function dina_woocommerce_comments( $comment, $args, $depth ) {
    global $post;
    $post = get_post( $comment->comment_post_ID ); // Set $post to ensure access in review-meta
    $GLOBALS['comment'] = $comment; // Ensure comment object is set for comment_class()
    ?>
    <li <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?> id="comment-<?php comment_ID(); ?>">
        <div id="div-comment-<?php comment_ID(); ?>" class="comment_container">
            <?php if ( $args['avatar_size'] != 0 ) : ?>
                <?php echo get_avatar( $comment, $args['avatar_size'] ); ?>
            <?php endif; ?>
            <div class="comment-text">
                <?php if ( $comment->comment_approved == '0' ) : ?>
                    <em class="woocommerce-review__awaiting-approval"><?php esc_html_e( 'Your review is awaiting approval', 'dina-kala' ); ?></em><br />
                <?php else : ?>
                    <?php
                    // Show rating if any
                    if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ( $rating = get_comment_meta( $comment->comment_ID, 'rating', true ) ) ) : ?>
                        <div class="star-rating" role="img" aria-label="<?php printf( esc_html__( 'Rated %s out of 5', 'dina-kala' ), $rating ); ?>">
                            <span style="width:<?php echo ( ( $rating / 5 ) * 100 ); ?>%"><?php printf( esc_html__( 'Rated %s out of 5', 'dina-kala' ), '<strong class="rating">' . esc_html( $rating ) . '</strong>' ); ?></span>
                        </div>
                    <?php endif; ?>

                    <p class="meta">
                        <?php
                        $user_id = $comment->user_id;
                        ?>
                        <strong class="woocommerce-review__author"><?php comment_author(); ?></strong>
                        <?php
                        if ( user_can( $user_id, 'manage_options' ) ) {
                            echo '<em class="woocommerce-review__verified verified">(' . esc_attr__( 'Admin', 'dina-kala' ) . ')</em> ';
                        } elseif ( $post->post_author == $comment->user_id ) {
                            echo '<em class="woocommerce-review__verified verified">(' . esc_attr__( 'Seller', 'dina-kala' ) . ')</em> ';
                        } elseif ( 'yes' === get_option( 'woocommerce_review_rating_verification_label' ) && wc_review_is_from_verified_owner( $comment->comment_ID ) ) {
                            echo '<em class="woocommerce-review__verified verified">(' . esc_attr__( 'verified owner', 'dina-kala' ) . ')</em> ';
                        }
                        ?>
                        <time class="woocommerce-review__published-date" datetime="<?php echo esc_attr( get_comment_date( 'c' ) ); ?>"><?php echo esc_html( get_comment_date( wc_date_format() ) ); ?></time>
                    </p>
                <?php endif; ?>

                <div class="description"><?php comment_text(); ?></div>
            </div>
        </div>
        <?php
        // Add reply link only for non-product posts
        if ( $depth < $args['max_depth'] && get_post_type( $post ) !== 'product' ) {
            ?>
            <div class="reply">
                <?php
                comment_reply_link(
                    array_merge(
                        $args,
                        array(
                            'depth'      => $depth,
                            'max_depth'  => $args['max_depth'],
                            'reply_text' => $args['reply_text'],
                        )
                    )
                );
                ?>
            </div>
            <?php
        }
        // Do not close </li> here to allow wp_list_comments to handle nested comments
}

// dina_load_more_comments
function dina_load_more_comments() {
    if ( ! check_ajax_referer( 'dina_load_more_comments_nonce', 'nonce', false ) ) {
        wp_send_json_error( array(
            'message' => __( 'Request security not verified.', 'dina-kala' )
        ) );
        wp_die();
    }

    $post_id  = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
    $page     = isset( $_POST['page'] ) ? intval( $_POST['page'] ) : 1;
    $per_page = isset( $_POST['perpage'] ) ? intval( $_POST['perpage'] ) : 6;

    $total_parent_comments = get_comments( array(
        'post_id' => $post_id,
        'status'  => 'approve',
        'parent'  => 0,
        'count'   => true,
    ) );

    $comment_order = get_option( 'comment_order', 'asc' );

    $total_pages = ceil( $total_parent_comments / $per_page );

    if ( $comment_order === 'desc' ) {
        $reverse_page = $total_pages - $page + 1;
        $offset = ( $reverse_page - 1 ) * $per_page;
        $no_more_comments = $page >= $total_pages;
    } else {
        $offset = ( $page - 1 ) * $per_page;
        $no_more_comments = $page >= $total_pages;
    }

    $parent_comments = get_comments( array(
        'post_id'    => $post_id,
        'status'     => 'approve',
        'parent'     => 0,
        'number'     => $per_page,
        'offset'     => $offset,
        'order'      => 'ASC',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'verified',
                'compare' => 'EXISTS',
            ),
            array(
                'key'     => 'verified',
                'compare' => 'NOT EXISTS',
            ),
        ),
    ) );

    $comment_ids    = wp_list_pluck( $parent_comments, 'comment_ID' );
    $child_comments = dina_get_all_child_comments( $comment_ids, $post_id );

    $comments = array_merge( $parent_comments, $child_comments );

    $post_type = get_post_type( $post_id );
    $comment_args = array(
        'avatar_size' => 50,
        'style'       => 'ol',
        'short_ping'  => true,
        'reply_text'  => __( 'Reply', 'dina-kala' ),
        'max_depth'   => get_option( 'thread_comments_depth', 5 ),
        'type'        => 'all',
    );

    if ( $post_type === 'product' ) {
        $comment_args['callback'] = 'dina_woocommerce_comments';
        $comment_args             = apply_filters( 'woocommerce_product_review_list_args', $comment_args );
    }

    if ( ! empty( $comments ) ) {
        ob_start();
        wp_list_comments( $comment_args, $comments );
        $html = ob_get_clean();

        wp_send_json_success( array(
            'html'             => $html,
            'page'             => $page + 1,
            'no_more_comments' => $no_more_comments,
        ) );
    } else {
        wp_send_json_success( array(
            'html'             => '',
            'page'             => $page + 1,
            'no_more_comments' => true,
        ) );
    }

    wp_die();
}
