<?php
/**
 * The template for displaying WooCommerce single products
 *
 * @package Theme_An_Phat
 */

get_header(); ?>

<!-- Breadcrumbs Navigation Bar -->
<div class="product-breadcrumb-bar py-3 mb-4">
    <div class="container">
        <div class="breadcrumbs text-sm mb-0">
            <a href="<?php echo esc_url( home_url('/') ); ?>"><?php esc_html_e( 'Trang chủ', 'theme-anphat' ); ?></a>
            <span class="mx-2 text-muted">/</span>
            <a href="<?php echo esc_url( home_url('/san-pham/') ); ?>"><?php esc_html_e( 'Sản phẩm', 'theme-anphat' ); ?></a>
            <?php
            $terms = get_the_terms( get_the_ID(), 'product_cat' );
            if ( $terms && ! is_wp_error( $terms ) ) :
                ?>
                <span class="mx-2 text-muted">/</span>
                <a href="<?php echo esc_url( get_term_link( $terms[0] ) ); ?>"><?php echo esc_html( $terms[0]->name ); ?></a>
            <?php endif; ?>
            <span class="mx-2 text-muted">/</span>
            <span class="text-dark fw-medium"><?php the_title(); ?></span>
        </div>
    </div>
</div>

<main id="primary" class="site-main py-2 bg-white text-dark">
    <div class="container">
        <?php while ( have_posts() ) : the_post(); 
            $product = function_exists( 'wc_get_product' ) ? wc_get_product( get_the_ID() ) : null;
            
            // Get brand
            $brands = get_the_terms( get_the_ID(), 'product_brand' );
            $brand_name = ( $brands && ! is_wp_error( $brands ) ) ? $brands[0]->name : 'GLOBAL PHARMA CM'; // Fallback
            
            // Get stock status
            $stock_status = $product ? $product->get_stock_status() : 'instock';
            $stock_label = ( $stock_status === 'instock' ) ? __( 'Còn hàng', 'theme-anphat' ) : __( 'Hết hàng', 'theme-anphat' );
            
            // Get price & handle placeholder "1 d" B2B pricing
            $price_val = $product ? $product->get_price() : '';
            $price_html = $product ? $product->get_price_html() : '';
            if ( empty( $price_val ) || floatval( $price_val ) <= 1 ) {
                $display_price = __( 'Liên hệ', 'theme-anphat' );
                $is_contact_only = true;
            } else {
                $display_price = $price_html ? $price_html : __( 'Liên hệ', 'theme-anphat' );
                $is_contact_only = false;
            }
        ?>
        
        <!-- Top Section: Image & Main Info -->
        <div class="row g-5 mb-5">
            <!-- Left Column: Product Image Gallery -->
            <div class="col-lg-6 scroll-reveal">
                <!-- Main Image Card -->
                <div class="product-gallery-main rounded-4 p-4 d-flex align-items-center justify-content-center mb-3" style="min-height: 420px; max-height: 480px; position: relative;">
                    <?php if ( has_post_thumbnail() ) : ?>
                        <?php 
                        $main_image_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
                        the_post_thumbnail( 'large', array( 'class' => 'img-fluid max-h-100 rounded-3 product-photo-main', 'style' => 'max-height: 380px; object-fit: contain;' ) ); 
                        ?>
                    <?php else : ?>
                        <div class="text-center text-muted">
                            <span class="d-block fs-1"><i class="fa-solid fa-capsules text-primary"></i></span>
                            <p class="mt-3 text-sm"><?php esc_html_e( 'Chưa có hình ảnh sản phẩm', 'theme-anphat' ); ?></p>
                        </div>
                    <?php endif; ?>
                    <div class="gallery-zoom-hint">
                        <i class="fa-solid fa-magnifying-glass-plus"></i>
                    </div>
                </div>

                <!-- Thumbnails Carousel (Horizontal scrollable) -->
                <?php
                $gallery_image_ids = $product ? $product->get_gallery_image_ids() : array();
                if ( ! empty( $gallery_image_ids ) || has_post_thumbnail() ) :
                ?>
                    <div class="product-thumbnails-carousel">
                        <?php if ( has_post_thumbnail() ) : ?>
                            <div class="product-thumb-item active" data-large-src="<?php echo esc_url( $main_image_url ); ?>">
                                <?php the_post_thumbnail( 'thumbnail', array( 'class' => 'img-fluid' ) ); ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php foreach ( $gallery_image_ids as $image_id ) : 
                            $thumb_url = wp_get_attachment_image_url( $image_id, 'thumbnail' );
                            $large_url = wp_get_attachment_image_url( $image_id, 'large' );
                        ?>
                            <div class="product-thumb-item" data-large-src="<?php echo esc_url( $large_url ); ?>">
                                <img src="<?php echo esc_url( $thumb_url ); ?>" alt="Gallery Image" class="img-fluid">
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <!-- Assurance Badges -->
                <div class="row g-3 mt-3">
                    <div class="col-6">
                        <div class="assurance-card">
                            <i class="fa-solid fa-shield-halved"></i>
                            <span><?php esc_html_e( 'Đạt chuẩn GSP', 'theme-anphat' ); ?></span>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="assurance-card">
                            <i class="fa-solid fa-certificate"></i>
                            <span><?php esc_html_e( 'Nhập khẩu chính hãng', 'theme-anphat' ); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Column: Product Meta Details -->
            <div class="col-lg-6 scroll-reveal-right">
                <div class="h-100 d-flex flex-column justify-content-start">
                    <h1 class="product-title font-heading fw-bold text-primary-dark mb-3 fs-2" style="letter-spacing: -0.2px; line-height: 1.25;"><?php the_title(); ?></h1>
                    
                    <!-- Pill Badges -->
                    <div class="d-flex flex-wrap gap-2 mb-4">
                        <span class="product-pill-badge badge-brand">
                            <i class="fa-solid fa-trademark"></i><?php echo esc_html( $brand_name ); ?>
                        </span>
                        <?php if ( $terms && ! is_wp_error( $terms ) ) : ?>
                            <span class="product-pill-badge badge-category">
                                <i class="fa-solid fa-folder"></i><?php echo esc_html( $terms[0]->name ); ?>
                            </span>
                        <?php endif; ?>
                        <span class="product-pill-badge <?php echo ($stock_status === 'instock') ? 'badge-stock-in' : 'badge-stock-out'; ?>">
                            <i class="fa-solid <?php echo ($stock_status === 'instock') ? 'fa-circle-check' : 'fa-circle-xmark'; ?>"></i><?php echo esc_html( $stock_label ); ?>
                        </span>
                    </div>

                    <?php if ( has_excerpt() ) : ?>
                        <div class="product-short-desc text-muted mb-4 border-start border-primary border-3 ps-3 py-1 fs-6 fw-medium bg-light rounded-end">
                            <?php the_excerpt(); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Specifications Table Grid -->
                    <div class="mb-4">
                        <table class="specs-table">
                            <tbody>
                                <tr>
                                    <th><?php esc_html_e( 'Thương hiệu', 'theme-anphat' ); ?></th>
                                    <td><?php echo esc_html( $brand_name ); ?></td>
                                </tr>
                                <?php if ( $terms && ! is_wp_error( $terms ) ) : ?>
                                <tr>
                                    <th><?php esc_html_e( 'Danh mục', 'theme-anphat' ); ?></th>
                                    <td><?php echo esc_html( $terms[0]->name ); ?></td>
                                </tr>
                                <?php endif; ?>
                                <tr>
                                    <th><?php esc_html_e( 'Nhà phân phối', 'theme-anphat' ); ?></th>
                                    <td><?php esc_html_e( 'Công ty CP Dược phẩm An Phát', 'theme-anphat' ); ?></td>
                                </tr>
                                <tr>
                                    <th><?php esc_html_e( 'Tiêu chuẩn kho', 'theme-anphat' ); ?></th>
                                    <td><span class="text-success fw-bold"><?php esc_html_e( 'Đạt chuẩn GSP & GDP (Bộ Y tế)', 'theme-anphat' ); ?></span></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Price Alert Premium Box -->
                    <div class="product-price-alert-premium mb-4">
                        <span class="price-label"><?php esc_html_e( 'Báo giá sản phẩm', 'theme-anphat' ); ?></span>
                        <div class="d-flex align-items-baseline gap-2">
                            <span class="price-value"><?php echo wp_kses_post( $display_price ); ?></span>
                            <?php if ( $is_contact_only ) : ?>
                                <span class="badge bg-danger text-white text-xs fw-bold px-2 py-1 rounded"><?php esc_html_e( 'B2B', 'theme-anphat' ); ?></span>
                            <?php endif; ?>
                        </div>
                        <p class="price-note mb-0">
                            <i class="fa-solid fa-circle-info text-primary me-1"></i>
                            <?php esc_html_e( 'Liên hệ trực tiếp để được tư vấn chính sách chiết khấu tốt nhất.', 'theme-anphat' ); ?>
                        </p>
                    </div>

                    <!-- CTA Buttons -->
                    <div class="row g-3">
                        <div class="col-md-6">
                            <a href="<?php echo esc_url( home_url('/lien-he/') ); ?>" class="btn btn-primary btn-lg w-100 py-3 fw-bold rounded-3 shadow-sm">
                                <i class="fa-solid fa-file-invoice-dollar me-2"></i><?php esc_html_e( 'Yêu cầu báo giá', 'theme-anphat' ); ?>
                            </a>
                        </div>
                        <div class="col-md-6">
                            <a href="https://zalo.me/0282211855" target="_blank" rel="nofollow" class="btn btn-cta-zalo btn-lg w-100 py-3 fw-bold rounded-3">
                                <i class="fa-solid fa-message me-2"></i><?php esc_html_e( 'Tư vấn qua Zalo', 'theme-anphat' ); ?>
                            </a>
                        </div>
                        <div class="col-12 mt-3">
                            <a href="tel:0282211855" class="btn btn-cta-hotline btn-lg w-100 py-3 fw-bold rounded-3 text-center">
                                <i class="fa-solid fa-phone me-2 text-primary"></i><?php esc_html_e( 'Hotline đặt hàng:', 'theme-anphat' ); ?> 028 2211 855
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bottom Section: Tabs & Sidebar -->
        <div class="row g-5">
            <!-- Left Column: Description -->
            <div class="col-lg-8 scroll-reveal">
                <div class="product-detail-wrapper bg-white rounded-4 p-4 p-md-5 border shadow-sm">
                    <h3 class="font-heading fw-bold text-primary mb-4 pb-3 border-bottom" style="font-size: 1.25rem;">
                        <span class="border-bottom border-primary border-3 pb-3"><?php esc_html_e( 'MÔ TẢ SẢN PHẨM', 'theme-anphat' ); ?></span>
                    </h3>
                    
                    <div class="entry-content lh-lg text-dark">
                        <p class="text-danger fw-bold mb-4"><?php esc_html_e( 'Liên hệ sản phẩm TẠI ĐÂY', 'theme-anphat' ); ?> <a href="<?php echo esc_url( home_url('/lien-he/') ); ?>" class="text-primary hover-underline"><i class="fa-solid fa-up-right-from-square ms-1"></i></a></p>
                        <?php the_content(); ?>
                    </div>
                </div>

                <!-- Review & Rating Section -->
                <?php
                // Fetch reviews
                $comments = get_comments( array(
                    'post_id' => get_the_ID(),
                    'status'  => 'approve',
                    'type'    => 'review'
                ) );
                $review_count = count( $comments );

                // Calculate ratings distribution
                $rating_counts = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
                $total_stars = 0;
                foreach ( $comments as $comment ) {
                    $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
                    if ( $rating >= 1 && $rating <= 5 ) {
                        $rating_counts[$rating]++;
                        $total_stars += $rating;
                    }
                }
                
                $average_rating = ($review_count > 0) ? round( $total_stars / $review_count, 1 ) : 5; // Default to 5 if no reviews
                
                // Calculate percentage for each star
                $rating_pct = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
                if ( $review_count > 0 ) {
                    foreach ( $rating_counts as $star => $count ) {
                        $rating_pct[$star] = round( ( $count / $review_count ) * 100 );
                    }
                } else {
                    // Default values if empty: 5 star 100% and others 0% to match preview design
                    $rating_pct[5] = 100;
                }
                ?>
                <div class="product-rating-box mt-4 scroll-reveal">
                    <h4 class="font-heading fw-bold text-dark mb-4 text-center text-md-start" style="font-size: 1.15rem;"><?php printf( esc_html__( 'Đánh giá %s', 'theme-anphat' ), get_the_title() ); ?></h4>
                    <div class="row align-items-center g-4">
                        <!-- Score Display Column (Left) -->
                        <div class="col-md-4 text-center border-end border-light">
                            <div class="d-flex align-items-center justify-content-center gap-2 mb-1">
                                <i class="fa-solid fa-star text-warning fs-3 mt-1"></i>
                                <span class="rating-score-large"><?php echo esc_html( $average_rating ); ?></span>
                                <span class="rating-score-total">/5</span>
                            </div>
                            <div class="text-muted text-sm fw-medium d-flex align-items-center justify-content-center gap-1">
                                <span>
                                    <?php 
                                    if ( $review_count === 1 ) {
                                        printf( esc_html__( '1 khách hài lòng', 'theme-anphat' ) );
                                    } else {
                                        printf( esc_html__( '%d khách hài lòng', 'theme-anphat' ), $review_count );
                                    }
                                    ?>
                                </span>
                                <i class="fa-regular fa-circle-question text-muted cursor-pointer" title="<?php esc_attr_e( 'Đánh giá thực tế từ khách hàng', 'theme-anphat' ); ?>"></i>
                            </div>
                        </div>

                        <!-- Progress Bars Column (Right) -->
                        <div class="col-md-8">
                            <?php for ( $i = 5; $i >= 1; $i-- ) : ?>
                                <div class="rating-progress-row">
                                    <span class="rating-progress-label">
                                        <?php echo $i; ?> <i class="fa-solid fa-star text-warning" style="font-size: 0.75rem;"></i>
                                    </span>
                                    <div class="rating-progress-bar-track">
                                        <div class="rating-progress-bar-fill" style="width: <?php echo esc_attr( $rating_pct[$i] ); ?>%;"></div>
                                    </div>
                                    <span class="rating-progress-percent"><?php echo esc_html( $rating_pct[$i] ); ?>%</span>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>

                    <!-- Toggle Form Button -->
                    <div class="text-center mt-4 pt-3 border-top border-light">
                        <button type="button" class="btn btn-write-review btn-lg" id="btn-toggle-review-form">
                            <?php esc_html_e( 'Viết đánh giá', 'theme-anphat' ); ?>
                        </button>
                    </div>
                </div>

                <!-- Custom Review Form Box -->
                <div class="review-form-card mt-4 scroll-reveal" id="review-form-container" style="display: none;">
                    <h4 class="font-heading fw-bold text-dark mb-3 text-center" style="font-size: 1.15rem;"><?php esc_html_e( 'Gửi đánh giá của bạn', 'theme-anphat' ); ?></h4>
                    <form action="<?php echo esc_url( site_url( '/wp-comments-post.php' ) ); ?>" method="post" id="custom-product-review-form">
                        <!-- Star Selection -->
                        <div class="text-center mb-3">
                            <label class="form-label d-block text-muted text-sm fw-bold mb-2"><?php esc_html_e( 'Chọn đánh giá của bạn (1-5 sao):', 'theme-anphat' ); ?></label>
                            <div class="star-rating-select d-flex gap-2 justify-content-center mb-3">
                                <input type="radio" id="star1" name="rating" value="1" style="display:none;" />
                                <label for="star1" class="fa-solid fa-star fs-3" style="cursor:pointer; color: #ccc;" title="1 sao"></label>
                                
                                <input type="radio" id="star2" name="rating" value="2" style="display:none;" />
                                <label for="star2" class="fa-solid fa-star fs-3" style="cursor:pointer; color: #ccc;" title="2 sao"></label>
                                
                                <input type="radio" id="star3" name="rating" value="3" style="display:none;" />
                                <label for="star3" class="fa-solid fa-star fs-3" style="cursor:pointer; color: #ccc;" title="3 sao"></label>
                                
                                <input type="radio" id="star4" name="rating" value="4" style="display:none;" />
                                <label for="star4" class="fa-solid fa-star fs-3" style="cursor:pointer; color: #ccc;" title="4 sao"></label>
                                
                                <input type="radio" id="star5" name="rating" value="5" checked style="display:none;" />
                                <label for="star5" class="fa-solid fa-star fs-3" style="cursor:pointer; color: #FFC107;" title="5 sao"></label>
                            </div>
                        </div>

                        <!-- Review Text -->
                        <div class="mb-3">
                            <label for="review-comment" class="form-label text-sm fw-bold text-dark"><?php esc_html_e( 'Nội dung nhận xét/đánh giá *', 'theme-anphat' ); ?></label>
                            <textarea id="review-comment" name="comment" class="form-control rounded-3" rows="4" required placeholder="<?php esc_attr_e( 'Chia sẻ cảm nhận của bạn về sản phẩm này...', 'theme-anphat' ); ?>"></textarea>
                        </div>

                        <div class="row g-3 mb-4">
                            <!-- Author Name -->
                            <div class="col-md-6">
                                <label for="review-author" class="form-label text-sm fw-bold text-dark"><?php esc_html_e( 'Họ tên của bạn *', 'theme-anphat' ); ?></label>
                                <input type="text" id="review-author" name="author" class="form-control rounded-3" required placeholder="<?php esc_attr_e( 'Nguyễn Văn A', 'theme-anphat' ); ?>" />
                            </div>
                            <!-- Author Email -->
                            <div class="col-md-6">
                                <label for="review-email" class="form-label text-sm fw-bold text-dark"><?php esc_html_e( 'Email liên hệ *', 'theme-anphat' ); ?></label>
                                <input type="email" id="review-email" name="email" class="form-control rounded-3" required placeholder="email@example.com" />
                            </div>
                        </div>

                        <!-- Hidden fields required by WordPress comments post -->
                        <input type="hidden" name="comment_post_ID" value="<?php echo get_the_ID(); ?>" />
                        <input type="hidden" name="comment_parent" value="0" />

                        <!-- Submit Button -->
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary btn-lg px-5 py-3 fw-bold rounded-3 shadow">
                                <i class="fa-solid fa-paper-plane me-2"></i><?php esc_html_e( 'Gửi đánh giá', 'theme-anphat' ); ?>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Reviews List -->
                <div class="reviews-list-container scroll-reveal">
                    <h4 class="font-heading fw-bold text-primary mb-4 pb-2 border-bottom" style="font-size: 1.15rem;">
                        <i class="fa-solid fa-comments me-2 text-accent"></i><?php esc_html_e( 'Ý kiến khách hàng', 'theme-anphat' ); ?>
                    </h4>

                    <?php if ( ! empty( $comments ) ) : ?>
                        <div class="reviews-list">
                            <?php foreach ( $comments as $comment ) : 
                                $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
                                $author_name = get_comment_author( $comment->comment_ID );
                                $initial = strtoupper( substr( $author_name, 0, 1 ) );
                                $date = get_comment_date( 'd/m/Y', $comment->comment_ID );
                            ?>
                                <div class="review-item-card">
                                    <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
                                        <div class="d-flex align-items-center gap-3">
                                            <div class="review-avatar"><?php echo esc_html( $initial ); ?></div>
                                            <div>
                                                <h5 class="fs-6 fw-bold text-dark mb-0 d-flex align-items-center gap-1">
                                                    <?php echo esc_html( $author_name ); ?>
                                                    <span class="badge bg-success-light text-success border-success-subtle text-xxs px-2 py-0.5 rounded-pill"><i class="fa-solid fa-circle-check me-1"></i><?php esc_html_e( 'Đã kiểm chứng', 'theme-anphat' ); ?></span>
                                                </h5>
                                                <span class="text-muted text-xs"><?php echo esc_html( $date ); ?></span>
                                            </div>
                                        </div>
                                        <?php if ( $rating >= 1 && $rating <= 5 ) : ?>
                                            <div class="text-warning text-sm">
                                                <?php
                                                for ( $s = 1; $s <= 5; $s++ ) {
                                                    if ( $s <= $rating ) {
                                                        echo '<i class="fa-solid fa-star"></i>';
                                                    } else {
                                                        echo '<i class="fa-regular fa-star"></i>';
                                                    }
                                                }
                                                ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="review-comment-content text-dark text-sm lh-base ps-md-5">
                                        <?php echo wp_kses_post( wpautop( get_comment_text( $comment->comment_ID ) ) ); ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else : ?>
                        <!-- Empty State -->
                        <div class="text-center py-5 px-4 bg-light rounded-4 border border-light">
                            <span class="fs-1 text-muted"><i class="fa-regular fa-comments text-primary-light"></i></span>
                            <h5 class="mt-3 font-heading fw-bold text-dark"><?php esc_html_e( 'Chưa có đánh giá nào', 'theme-anphat' ); ?></h5>
                            <p class="text-muted text-sm mb-0"><?php esc_html_e( 'Hãy là người đầu tiên gửi ý kiến nhận xét và đánh giá cho sản phẩm này.', 'theme-anphat' ); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Right Column: Sidebar Related Products -->
            <div class="col-lg-4 scroll-reveal-right">
                <!-- Related Products Sidebar -->
                <div class="sidebar-widget-premium p-4 mb-4">
                    <h3 class="font-heading fw-bold text-primary mb-4 pb-2 border-bottom" style="font-size: 1.15rem;">
                        <?php esc_html_e( 'CÓ THỂ BẠN THÍCH', 'theme-anphat' ); ?>
                    </h3>
                    
                    <div class="related-products-list d-flex flex-column gap-3">
                        <?php
                        $related_args = array(
                            'post_type'      => 'product',
                            'posts_per_page' => 4,
                            'post__not_in'   => array( get_the_ID() ),
                            'orderby'        => 'rand',
                        );
                        if ( $terms && ! is_wp_error( $terms ) ) {
                            $related_args['tax_query'] = array(
                                array(
                                    'taxonomy' => 'product_cat',
                                    'field'    => 'term_id',
                                    'terms'    => $terms[0]->term_id,
                                ),
                            );
                        }
                        $related_q = new WP_Query( $related_args );
                        if ( $related_q->have_posts() ) :
                            while ( $related_q->have_posts() ) : $related_q->the_post();
                                $rel_product = function_exists( 'wc_get_product' ) ? wc_get_product( get_the_ID() ) : null;
                                $rel_price_val = $rel_product ? $rel_product->get_price() : '';
                                $rel_price = $rel_product ? $rel_product->get_price_html() : '';
                                if ( empty( $rel_price_val ) || floatval( $rel_price_val ) <= 1 ) {
                                    $rel_display_price = __( 'Liên hệ', 'theme-anphat' );
                                } else {
                                    $rel_display_price = $rel_price ? $rel_price : __( 'Liên hệ', 'theme-anphat' );
                                }
                        ?>
                                <div class="related-product-item d-flex gap-3 align-items-center pb-3 border-bottom" style="border-bottom-style: dashed !important;">
                                    <a href="<?php the_permalink(); ?>" class="related-img-box border rounded-3 bg-light p-2 d-flex align-items-center justify-content-center" style="width: 75px; height: 75px; flex-shrink: 0; text-decoration: none;">
                                        <?php if ( has_post_thumbnail() ) : ?>
                                            <?php the_post_thumbnail( 'thumbnail', array( 'class' => 'img-fluid object-contain max-h-100', 'style' => 'max-height: 65px;' ) ); ?>
                                        <?php else : ?>
                                            <span class="fs-4 text-muted"><i class="fa-solid fa-capsules"></i></span>
                                        <?php endif; ?>
                                    </a>
                                    <div class="related-info-box">
                                        <h4 class="fs-6 fw-bold mb-1 line-clamp-2" style="font-size: 0.9rem !important; line-height: 1.4;">
                                            <a href="<?php the_permalink(); ?>" class="text-decoration-none text-dark hover-primary"><?php the_title(); ?></a>
                                        </h4>
                                        <span class="text-danger fw-bold text-sm" style="font-size: 0.85rem !important;"><?php echo wp_kses_post( $rel_display_price ); ?></span>
                                    </div>
                                </div>
                        <?php 
                            endwhile;
                            wp_reset_postdata();
                        else :
                            echo '<p class="text-sm text-muted mb-0">' . esc_html__( 'Chưa có sản phẩm liên quan.', 'theme-anphat' ) . '</p>';
                        endif;
                        ?>
                    </div>
                </div>

                <!-- Contact Quick Box -->
                <div class="sidebar-consulting-box text-center">
                    <i class="fa-solid fa-headset fs-2 text-accent mb-3 d-block"></i>
                    <h4 class="font-heading fw-bold mb-2"><?php esc_html_e( 'Cần tư vấn thêm?', 'theme-anphat' ); ?></h4>
                    <p class="text-white-80 text-sm mb-3"><?php esc_html_e( 'Dược sĩ An Phát Pharma luôn sẵn sàng hỗ trợ bạn 24/7.', 'theme-anphat' ); ?></p>
                    <a href="tel:0282211855" class="btn btn-accent btn-lg w-100 fw-bold">
                        <i class="fa-solid fa-phone me-2"></i>028 2211 855
                    </a>
                </div>
            </div>
        </div>

        <?php
        // Query related products in the same category (bottom list)
        $related_bottom_args = array(
            'post_type'      => 'product',
            'posts_per_page' => 4,
            'post__not_in'   => array( get_the_ID() ),
            'orderby'        => 'rand',
        );
        if ( $terms && ! is_wp_error( $terms ) ) {
            $related_bottom_args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'term_id',
                    'terms'    => $terms[0]->term_id,
                ),
            );
        }
        $related_bottom_q = new WP_Query( $related_bottom_args );
        if ( $related_bottom_q->have_posts() ) :
            ?>
            <div class="related-products-bottom-section mt-5 pt-5 border-top scroll-reveal">
                <h3 class="font-heading fw-bold text-primary mb-4 text-uppercase text-center text-md-start" style="font-size: 1.35rem; letter-spacing: 0.5px;">
                    <span class="border-bottom border-primary border-3 pb-2"><?php esc_html_e( 'Sản phẩm cùng danh mục', 'theme-anphat' ); ?></span>
                </h3>
                <div class="row g-4 mt-2">
                    <?php
                    while ( $related_bottom_q->have_posts() ) : $related_bottom_q->the_post();
                        theme_anphat_render_woocommerce_product_card();
                    endwhile;
                    ?>
                </div>
            </div>
            <?php
            wp_reset_postdata();
        endif;
        ?>

        <?php endwhile; ?>
    </div>
</main>

<script>
    jQuery(document).ready(function($) {
        // Handle changing main image when clicking thumbnails
        $('.product-thumb-item').on('click', function() {
            var newSrc = $(this).data('large-src');
            if (newSrc) {
                $('.product-photo-main')
                    .attr('src', newSrc)
                    .removeAttr('srcset')
                    .removeAttr('sizes');
                $('.product-thumb-item').removeClass('active');
                $(this).addClass('active');
            }
        });

        // Toggle review form
        $('#btn-toggle-review-form').on('click', function() {
            $('#review-form-container').slideToggle(300);
            $('html, body').animate({
                scrollTop: $('#review-form-container').offset().top - 120
            }, 500);
        });

        // Star rating click interactive behavior
        $('.star-rating-select label').on('click', function() {
            var selectedVal = parseInt($(this).prev('input').val());
            $('.star-rating-select label').each(function() {
                var starVal = parseInt($(this).prev('input').val());
                if (starVal <= selectedVal) {
                    $(this).css('color', '#FFC107'); // Gold color
                } else {
                    $(this).css('color', '#ccc'); // Gray color
                }
            });
        });

        // Star rating hover interactive behavior
        $('.star-rating-select label').hover(
            function() {
                var hoverVal = parseInt($(this).prev('input').val());
                $('.star-rating-select label').each(function() {
                    var starVal = parseInt($(this).prev('input').val());
                    if (starVal <= hoverVal) {
                        $(this).css('color', '#FFD54F'); // Light gold on hover
                    } else {
                        $(this).css('color', '#ccc');
                    }
                });
            },
            function() {
                // Restore selected rating
                var selectedVal = parseInt($('.star-rating-select input:checked').val()) || 5;
                $('.star-rating-select label').each(function() {
                    var starVal = parseInt($(this).prev('input').val());
                    if (starVal <= selectedVal) {
                        $(this).css('color', '#FFC107'); // Gold
                    } else {
                        $(this).css('color', '#ccc');
                    }
                });
            }
        );
    });
</script>

<?php get_footer(); ?>
