<?php
/**
 * Render Book Page Reviews [Author Pro] Block
 */

$block_id = isset($attributes['blockId']) ? $attributes['blockId'] : '';
if (empty($block_id)) {
    $block_id = 'awt-book-reviews-' . uniqid();
}

$anchor = isset($attributes['anchor']) ? $attributes['anchor'] : '';
$element_id = !empty($anchor) ? $anchor : $block_id;

$section_title = !empty($attributes['sectionTitle']) ? $attributes['sectionTitle'] : 'Customer Reviews';
$form_title = !empty($attributes['formTitle']) ? $attributes['formTitle'] : 'Write a Review';
$submit_btn_text = !empty($attributes['submitBtnText']) ? $attributes['submitBtnText'] : 'Submit Review';

// New Attributes with Defaults
$sort_label_most_recent = !empty($attributes['sortLabelMostRecent']) ? $attributes['sortLabelMostRecent'] : 'Most Recent';
$sort_label_highest = !empty($attributes['sortLabelHighest']) ? $attributes['sortLabelHighest'] : 'Highest Rated';
$sort_label_lowest = !empty($attributes['sortLabelLowest']) ? $attributes['sortLabelLowest'] : 'Lowest Rated';

$text_based_on = !empty($attributes['textBasedOn']) ? $attributes['textBasedOn'] : 'Based on';
$text_reviews_suffix = !empty($attributes['textReviewsSuffix']) ? $attributes['textReviewsSuffix'] : 'reviews';
$text_star = !empty($attributes['textStar']) ? $attributes['textStar'] : 'Star';

$cta_heading = !empty($attributes['ctaHeading']) ? $attributes['ctaHeading'] : 'Share your thoughts';
$cta_description = !empty($attributes['ctaDescription']) ? $attributes['ctaDescription'] : "If you've read this book, we'd love to hear what you think!";
$cta_button_text = !empty($attributes['ctaButtonText']) ? $attributes['ctaButtonText'] : 'Write a Review';

$label_name = !empty($attributes['labelName']) ? $attributes['labelName'] : 'Name *';
$label_email = !empty($attributes['labelEmail']) ? $attributes['labelEmail'] : 'Email *';
$label_rating = !empty($attributes['labelRating']) ? $attributes['labelRating'] : 'Rating *';
$label_review_title = !empty($attributes['labelReviewTitle']) ? $attributes['labelReviewTitle'] : 'Review Title *';
$label_review_content = !empty($attributes['labelReviewContent']) ? $attributes['labelReviewContent'] : 'Your Review *';

$msg_no_reviews = !empty($attributes['msgNoReviews']) ? $attributes['msgNoReviews'] : 'No reviews yet. Be the first to review!';

$book_id = get_the_ID();
$is_editor = defined('REST_REQUEST') && REST_REQUEST === true;

// If in editor, preview with a real book if possible
if ($is_editor && get_post_type($book_id) !== 'book') {
    $min_query = new WP_Query([
        'post_type' => 'book',
        'posts_per_page' => 1,
        'post_status' => 'publish'
    ]);
    if ($min_query->have_posts()) {
        $min_query->the_post();
        $book_id = get_the_ID();
        wp_reset_postdata();
    }
}

// 1. Fetch Reviews
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'book_reviews',
    'posts_per_page' => 5,
    'paged' => $paged,
    'meta_query' => array(
        array(
            'key' => '_rswpbs_reviewed_book',
            'value' => $book_id,
            'compare' => '='
        )
    )
);
$reviews_query = new WP_Query($args);
$total_reviews = $reviews_query->found_posts;

// 2. Calculate Stats (All time)
// Separate query for ALL reviews to calculate stats correctly
$stats_args = $args;
$stats_args['posts_per_page'] = -1;
$stats_args['paged'] = 1;
$all_reviews = get_posts($stats_args);

$total_rating_sum = 0;
$star_counts = [5 => 0, 4 => 0, 3 => 0, 2 => 0, 1 => 0];

foreach ($all_reviews as $review) {
    $rating = get_post_meta($review->ID, '_rswpbs_rating', true);
    $rating = intval($rating);
    if ($rating >= 1 && $rating <= 5) {
        $total_rating_sum += $rating;
        $star_counts[$rating]++;
    }
}

$avg_rating = ($total_reviews > 0) ? round($total_rating_sum / count($all_reviews), 1) : 0; // Use count of fetched posts for accuracy

// Helper to render stars
function awt_render_stars($rating) {
    $html = '';

    for ($i = 1; $i <= 5; $i++) {
        $color_class = ($i <= $rating) ? 'text-yellow-400' : 'text-gray-300';

        $html .= '
        <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 640 640"
            class="w-4 h-4 inline-block ' . esc_attr($color_class) . '"
            fill="currentColor"
            aria-hidden="true"
        >
            <path d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z"/>
        </svg>';
    }

    return $html;
}


$wrapper_attributes = get_block_wrapper_attributes([
    'class' => 'awt-book-reviews',
    'id'    => $element_id,
]);
?>

<section class="py-20 bg-white" <?php echo $wrapper_attributes; ?>>
    <div class="awt-container">
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-12">
            
            <!-- Left Column: Stats -->
            <div class="lg:col-span-4">
                <!-- Summary Card -->
                <div class="bg-paper p-8 rounded-xl border border-gray-100 text-center mb-8">
                    <div class="text-5xl font-bold text-primary mb-2"><?php echo esc_html($avg_rating); ?></div>
                    <div class="flex justify-center gap-1 text-yellow-400 mb-2">
                        <?php echo awt_render_stars(round($avg_rating)); ?>
                    </div>
                    <p class="text-secondary text-sm"><?php echo esc_html($text_based_on); ?> <?php echo esc_html($total_reviews); ?> <?php echo esc_html($text_reviews_suffix); ?></p>
                </div>

                <!-- Progress Bars -->
                <div class="space-y-3 mb-8">
                    <?php for ($star = 5; $star >= 1; $star--) : 
                        $count = $star_counts[$star];
                        $percent = ($total_reviews > 0) ? ($count / $total_reviews) * 100 : 0;
                    ?>
                    <?php
                    ?>
                    <div class="flex items-center text-sm">
                        <span class="w-12 text-secondary font-medium"><?php echo $star; ?> <?php echo esc_html($text_star); ?></span>
                        <div class="flex-1 h-2 bg-gray-100 rounded-full mx-3 overflow-hidden">
                            <div class="h-full bg-yellow-400 rounded-full" style="width: <?php echo esc_attr($percent); ?>%"></div>
                        </div>
                        <span class="w-8 text-right text-gray-400 text-xs"><?php echo round($percent); ?>%</span>
                    </div>
                    <?php endfor; ?>
                </div>

                <!-- CTA Box -->
                <div class="bg-primary text-white p-6 rounded-xl relative overflow-hidden">
                    <div class="relative z-10">
                        <h3 class="font-serif font-bold text-xl mb-2"><?php echo esc_html($cta_heading); ?></h3>
                        <p class="text-white/80 text-sm mb-6"><?php echo esc_html($cta_description); ?></p>
                        <a href="#write-review" class="block w-full py-3 bg-white text-primary text-center font-bold rounded-lg hover:bg-accent hover:text-white transition"><?php echo esc_html($cta_button_text); ?></a>
                    </div>
                    <!-- Decorative Circles in CSS/Class similar to ref if needed, strictly keeping structure simple as requested -->
                </div>
            </div>

            <!-- Right Column: Review List -->
            <div class="lg:col-span-8">
                <div class="flex justify-between items-center mb-8 pb-4 border-b border-gray-100">
                    <h2 class="font-serif font-bold text-2xl text-primary"><?php echo esc_html($section_title); ?></h2>
                    
                    <!-- Sorting Dropdown (Optional visual only for now) -->
                    <div class="relative">
                        <select class="appearance-none bg-white border border-gray-200 rounded-lg py-2 pl-4 pr-10 text-sm font-medium text-secondary focus:outline-none focus:border-accent">
                            <option><?php echo esc_html($sort_label_most_recent); ?></option>
                            <option><?php echo esc_html($sort_label_highest); ?></option>
                            <option><?php echo esc_html($sort_label_lowest); ?></option>
                        </select>
                         <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                            <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"/></svg>
                        </div>
                    </div>
                </div>
                
                <?php if ($reviews_query->have_posts()) : ?>
                    <div class="space-y-8 mb-12">
                    <?php while ($reviews_query->have_posts()) : $reviews_query->the_post(); 
                        $reviewer_email = get_post_meta(get_the_ID(), '_rswpbs_reviewer_email', true);
                        $reviewer_name = get_post_meta(get_the_ID(), '_rswpbs_reviewer_name', true);
                        $rating = get_post_meta(get_the_ID(), '_rswpbs_rating', true);
                        $avatar_url = get_avatar_url($reviewer_email, ['default' => 'mp']);
                    ?>
                        <div class="flex gap-4 mb-8">
                            <div class="flex-shrink-0">
                                <img src="<?php echo esc_url($avatar_url); ?>" alt="<?php echo esc_attr($reviewer_name); ?>" class="w-12 h-12 rounded-full object-cover border border-gray-100">
                            </div>
                            <div class="flex-grow">
                                <div class="flex justify-between items-start mb-2">
                                    <div>
                                        <h4 class="font-bold text-primary"><?php echo esc_html($reviewer_name); ?></h4>
                                        <div class="text-xs text-gray-400"><?php echo get_the_date(); ?></div>
                                    </div>
                                    <div class="flex text-yellow-400 text-xs gap-0.5">
                                        <?php echo awt_render_stars(intval($rating)); ?>
                                    </div>
                                </div>
                                <h5 class="font-bold text-sm text-primary mb-2"><?php the_title(); ?></h5>
                                <div class="text-secondary prose text-sm leading-relaxed">
                                    <?php the_content(); ?>
                                    <!-- Using the_content() or excerpt depending on need. The ref request asked for content. -->
                                </div>
                            </div>
                        </div>
                    <?php endwhile; wp_reset_postdata(); ?>
                    </div>
                    
                    <!-- Pagination -->
                    <div class="flex justify-center gap-2 mb-12">
                        <?php 
                        $prev_icon = '
                        <svg xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 640 640"
                            class="w-4 h-4"
                            fill="currentColor"
                            aria-hidden="true">
                            <path d="M169.4 297.4C156.9 309.9 156.9 330.2 169.4 342.7L361.4 534.7C373.9 547.2 394.2 547.2 406.7 534.7C419.2 522.2 419.2 501.9 406.7 489.4L237.3 320L406.6 150.6C419.1 138.1 419.1 117.8 406.6 105.3C394.1 92.8 373.8 92.8 361.3 105.3L169.3 297.3z"/>
                        </svg>';

                        $next_icon = '
                        <svg xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 640 640"
                            class="w-4 h-4"
                            fill="currentColor"
                            aria-hidden="true">
                            <path d="M471.1 297.4C483.6 309.9 483.6 330.2 471.1 342.7L279.1 534.7C266.6 547.2 246.3 547.2 233.8 534.7C221.3 522.2 221.3 501.9 233.8 489.4L403.2 320L233.9 150.6C221.4 138.1 221.4 117.8 233.9 105.3C246.4 92.8 266.7 92.8 279.2 105.3L471.2 297.3z"/>
                        </svg>';

                        $pagination = paginate_links(array(
                            'base'      => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
                            'format'    => '?paged=%#%',
                            'current'   => max(1, get_query_var('paged')),
                            'total'     => $reviews_query->max_num_pages,
                            'prev_text' => $prev_icon,
                            'next_text' => $next_icon,
                            'type'      => 'array',
                        ));


                        if( is_array( $pagination ) ) {
                            foreach ( $pagination as $page ) {
                                // Add tailwind classes to pagination links logic if needed, 
                                // but standard WP output is usually sufficient with theme styles, 
                                // or we can wrapper it.
                                // For now echoing simple links.
                                echo '<span class="px-4 py-2 border border-gray-200 rounded hover:bg-gray-50 text-sm font-medium text-secondary transition cursor-pointer">' . $page . '</span>';
                            }
                        }
                        ?>
                    </div>

                <?php else : ?>
                    <p class="text-gray-500 italic mb-12"><?php echo esc_html($msg_no_reviews); ?></p>
                <?php endif; ?>

                <!-- Submission Form -->
                <div id="write-review" class="pt-12 border-t border-gray-100">
                    <h3 class="font-serif font-bold text-2xl text-primary mb-6"><?php echo esc_html($form_title); ?></h3>
                    
                    <form id="rswpbs-review-form" action="" method="post" class="space-y-6">
                        <?php 
                        // AJAX Action and Nonce for RS WP Books Showcase
                        // Note: The plugin must handle this action.
                        wp_nonce_field( 'rswpbs_submit_review', '_rswpbs_submit_review_nonce' ); 
                        ?>
                        <input type="hidden" name="action" value="rswpbs_submit_review_form">
                        <input type="hidden" name="current_post_id" value="<?php echo esc_attr($book_id); ?>">
                        <input type="hidden" name="rating" value="5">

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-bold text-primary mb-2"><?php echo esc_html($label_name); ?></label>
                                <input type="text" name="reviewer_name" required class="w-full px-4 py-3 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition">
                            </div>
                            <div>
                                <label class="block text-sm font-bold text-primary mb-2"><?php echo esc_html($label_email); ?></label>
                                <input type="email" name="reviewer_email" required class="w-full px-4 py-3 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition">
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-primary mb-2"><?php echo esc_html($label_rating); ?></label>
<div class="flex gap-1 text-2xl awt-star-rating-select">
                                <?php for ($i = 1; $i <= 5; $i++) : ?>
                                    <svg 
                                        class="awt-star-icon w-6 h-6 cursor-pointer text-gray-300 hover:scale-110 transition-transform duration-200" 
                                        data-rating="<?php echo $i; ?>"
                                        fill="currentColor" 
                                        xmlns="http://www.w3.org/2000/svg" 
                                        viewBox="0 0 640 640">
                                        <path d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z"/>
                                    </svg>
                                <?php endfor; ?>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-primary mb-2"><?php echo esc_html($label_review_title); ?></label>
                            <input type="text" name="review_title" required class="w-full px-4 py-3 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition">
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-primary mb-2"><?php echo esc_html($label_review_content); ?></label>
                            <textarea name="reviewer_comment" rows="5" required class="w-full px-4 py-3 bg-paper border border-gray-200 rounded-lg focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition"></textarea>
                        </div>

                        <button type="submit" class="px-8 py-3 bg-accent text-white font-bold rounded-lg hover:border-orange-700 hover:bg-orange-700 transition shadow-lg shadow-orange-500/20">
                            <?php echo esc_html($submit_btn_text); ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>
