<?php
/**
 * Render Other Books [Author Pro] Block
 */

$anchor = isset($attributes['anchor']) ? $attributes['anchor'] : '';
$fallback_id = isset($attributes['blockId']) ? $attributes['blockId'] : 'author-pro-books-' . uniqid();
// Use the anchor as the ID if present, otherwise use the fallback
$block_id = $anchor ? $anchor : $fallback_id;

$section_title = isset($attributes['sectionTitle']) ? $attributes['sectionTitle'] : 'Explore More Stories';
$section_badge = isset($attributes['sectionBadge']) ? $attributes['sectionBadge'] : 'Other Books';
$post_type = isset($attributes['postType']) ? $attributes['postType'] : 'book';
$posts_to_show = isset($attributes['postsToShow']) ? $attributes['postsToShow'] : 3;
$order = isset($attributes['order']) ? $attributes['order'] : 'desc';
$order_by = isset($attributes['orderBy']) ? $attributes['orderBy'] : 'date';
$selected_category = isset($attributes['selectedCategory']) ? $attributes['selectedCategory'] : '';
$include_post_ids = isset($attributes['includePostIds']) ? $attributes['includePostIds'] : '';

$padding_top = isset($attributes['paddingTop']) ? $attributes['paddingTop'] : 128;
$padding_bottom = isset($attributes['paddingBottom']) ? $attributes['paddingBottom'] : 128;

// Button Attributes
$button_text = isset($attributes['buttonText']) ? $attributes['buttonText'] : 'Buy on Amazon';
$button_icon_url = isset($attributes['buttonIconUrl']) ? $attributes['buttonIconUrl'] : '';

// View All Button
$show_view_all = isset($attributes['showViewAllBtn']) ? $attributes['showViewAllBtn'] : true;
$view_all_text = isset($attributes['viewAllBtnText']) ? $attributes['viewAllBtnText'] : 'View All Books';
$view_all_link = isset($attributes['viewAllBtnLink']) ? $attributes['viewAllBtnLink'] : '';

// Colors
$accent_color = isset($attributes['accentColor']) ? $attributes['accentColor'] : '';
$btn_color = isset($attributes['btnColor']) ? $attributes['btnColor'] : '';
$btn_hover_color = isset($attributes['btnHoverColor']) ? $attributes['btnHoverColor'] : '';
$btn_text_color = isset($attributes['btnTextColor']) ? $attributes['btnTextColor'] : '';
$btn_hover_text_color = isset($attributes['btnHoverTextColor']) ? $attributes['btnHoverTextColor'] : '';

// 1. Logic for Conditional Classes
$accent_class = 'text-accent'; // Default theme class
$star_class = 'text-yellow-400'; // Default star class
$title_hover_class = 'hover:text-accent'; // Default title hover

if ($accent_color) {
    $accent_class = 'awt-dynamic-accent';
    $star_class = 'awt-dynamic-accent';
    $title_hover_class = 'awt-dynamic-accent-hover';
}

// 2. Build Query Args
$args = [
    'post_type'      => $post_type,
    'posts_per_page' => $posts_to_show,
    'order'          => strtoupper($order),
    'orderby'        => $order_by,
    'post_status'    => 'publish',
];

// Specific IDs override other filters
if (!empty($include_post_ids)) {
    $ids_array = array_map('trim', explode(',', $include_post_ids));
    $args['post__in'] = $ids_array;
    $args['orderby'] = 'post__in'; // Preserve order of IDs
} elseif (!empty($selected_category)) {
    // Determine taxonomy based on post type
    $taxonomy = ($post_type === 'book') ? 'book_category' : 'category';
    $args['tax_query'] = [
        [
            'taxonomy' => $taxonomy,
            'field'    => 'term_id',
            'terms'    => $selected_category,
        ]
    ];
}

$query = new WP_Query($args);

// 3. Generate Dynamic CSS
$custom_css = "";

// Accent Color Logic
if ($accent_color) {
    $custom_css .= "#{$block_id} .awt-dynamic-accent { color: {$accent_color} !important; }";
    $custom_css .= "#{$block_id} .awt-dynamic-accent-hover:hover { color: {$accent_color} !important; }";
}

// Button Background
if ($btn_color) {
    $custom_css .= "#{$block_id} .bg-primary { background-color: {$btn_color} !important; }";
    // Ensure View All button gets it too if it doesn't use bg-primary
}

// Button Text Colors (Using specific class .awt-buy-btn)
// Button Text Colors (Using specific class .awt-buy-btn and .awt-view-all-btn)
if ($btn_text_color) {
    $custom_css .= "#{$block_id} .awt-buy-btn, #{$block_id} .awt-view-all-btn { color: {$btn_text_color} !important; }";
}

// Button Hover Logic
$hover_bg = $btn_hover_color ? $btn_hover_color : $accent_color;
if ($hover_bg) {
    $custom_css .= "#{$block_id} .awt-buy-btn:hover, #{$block_id} .awt-view-all-btn:hover { background-color: {$hover_bg} !important; }";
}

if ($btn_hover_text_color) {
    $custom_css .= "#{$block_id} .awt-buy-btn:hover, #{$block_id} .awt-view-all-btn:hover { color: {$btn_hover_text_color} !important; }";
}

$style = "padding-top: {$padding_top}px; padding-bottom: {$padding_bottom}px;";

// Prepare wrapper attributes
$wrapper_opts = [
    'class' => 'awt-author-pro-books bg-paper',
    'style' => $style
];

// Only duplicate the ID if the anchor is NOT set (to provide a hook for our styles)
// If anchor is set, get_block_wrapper_attributes() adds it automatically.
// if (!$anchor) {
//    $wrapper_opts['id'] = $block_id; 
// }
$wrapper_opts['id'] = $block_id;

$wrapper_attributes = get_block_wrapper_attributes($wrapper_opts);
?>

<?php if (!empty($custom_css)) : ?>
    <style><?php echo $custom_css; ?></style>
<?php endif; ?>

<section <?php echo $wrapper_attributes; ?>>
    <div class="awt-container">
        <!-- Section Header (Centered) -->
        <div class="flex flex-col items-center justify-center text-center mb-16 gap-2">
            <div data-aos="fade-up">
                <span class="awt-accent <?php echo esc_attr($accent_class); ?> font-bold text-xs uppercase tracking-widest mb-2 block"><?php echo esc_html($section_badge); ?></span>
                <h2 class="text-4xl font-serif font-bold text-primary"><?php echo esc_html($section_title); ?></h2>
            </div>
        </div>

        <?php if ($query->have_posts()) : ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                <?php while ($query->have_posts()) : $query->the_post(); 
                    $post_id = get_the_ID();
                    $permalink = get_permalink();
                    $buy_btn_text = get_post_meta($post_id, '_rsbs_buy_btn_text', true);
                    $buy_btn_link = get_post_meta($post_id, '_rsbs_buy_btn_link', true);
                    $title = get_the_title();
                    $thumbnail_url = get_the_post_thumbnail_url($post_id, 'large');
                    
                    // Fetch Price & Sale Price
                    $regular_price = get_post_meta($post_id, '_rsbs_book_price', true);
                    $sale_price = get_post_meta($post_id, '_rsbs_book_sale_price', true);
                    $regular_price = str_replace('$', '', $regular_price);
                    $sale_price = str_replace('$', '', $sale_price);
                    
                    // Rating
                    $rating = get_post_meta($post_id, '_rsbs_average_book_rating', true);
                ?>
                    <div class="bg-white rounded-xl shadow-sm hover:shadow-xl transition duration-300 overflow-hidden border border-gray-100 flex flex-col" data-aos="fade-up">
                        <div class="p-6 bg-gray-50 flex justify-center">
                            <?php if ($thumbnail_url) : ?>
                                <a href="<?php echo esc_url($permalink); ?>">
                                    <img src="<?php echo esc_url($thumbnail_url); ?>" class="h-64 shadow-lg rounded transform hover:scale-105 transition" alt="<?php echo esc_attr($title); ?>">
                                </a>
                            <?php else : ?>
                                <div class="h-64 w-full bg-gray-200 flex items-center justify-center text-gray-400 rounded shadow-lg">
                                    <?php esc_html_e('No Image', 'author-website-templates'); ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="p-6 flex-1 flex flex-col">
                            <!-- Rating -->
                            <div class="flex <?php echo esc_attr($star_class); ?> text-xs mb-2">
                                <?php 
                                    if ($rating) {
                                        $rating_val = floatval($rating);
                                        for ($i = 0; $i < 5; $i++) {
                                            if ($i < $rating_val) {
                                                echo '★';
                                            } else {
                                                echo '<span class="text-gray-300">★</span>';
                                            }
                                        }
                                    } else {
                                        // Default 5 stars
                                        echo '★★★★★';
                                    }
                                ?>
                            </div>
                            
                            <h3 class="text-xl font-serif font-bold text-primary mb-2">
                                <a href="<?php echo esc_url($permalink); ?>" class="<?php echo esc_attr($title_hover_class); ?> transition duration-300"><?php echo esc_html($title); ?></a>
                            </h3>
                            
                            <p class="text-sm text-secondary mb-4 line-clamp-3">
                                <?php echo get_the_excerpt(); ?>
                            </p>

                            <div class="mt-auto flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <?php if ($sale_price && $sale_price < $regular_price) : ?>
                                        <span class="text-sm text-gray-400 line-through"><?php echo '$' . esc_html($regular_price); ?></span>
                                        <span class="text-2xl font-bold <?php echo esc_attr($accent_class); ?>"><?php echo '$' . esc_html($sale_price); ?></span>
                                    <?php elseif ($regular_price) : ?>
                                        <span class="text-2xl font-bold <?php echo esc_attr($accent_class); ?>"><?php echo '$' . esc_html($regular_price); ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <a href="<?php echo esc_url($buy_btn_link); ?>" class="awt-buy-btn px-4 py-2 bg-primary text-xs font-bold rounded hover:bg-accent transition flex items-center gap-1">
                                    <?php if ($button_icon_url) : ?>
                                        <img src="<?php echo esc_url($button_icon_url); ?>" class="w-4 h-4 object-contain" alt="icon">
                                    <?php else: ?>
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="currentColor" viewBox="0 0 640 640"><path d="M353.7 226.7C305 228.5 184.2 242.2 184.2 344.2C184.2 453.7 322.5 458.2 367.7 387.4C374.2 397.6 403.1 424.9 413 434.2L469.8 378.2C469.8 378.2 437.5 352.9 437.5 325.4L437.5 178.3C437.5 153 413 96 325.2 96C237.2 96 190.5 151 190.5 200.3L264 207.1C280.3 157.6 318.2 157.6 318.2 157.6C358.9 157.5 353.7 187.4 353.7 226.7zM353.7 313.5C353.7 393.5 269.5 381.5 269.5 330.7C269.5 283.5 320 274 353.7 272.9L353.7 313.5zM489.7 477C482 487 419.7 544 315.2 544C210.7 544 130.7 472.5 106.2 443C99.4 435.3 107.2 431.7 111.7 434.7C185 479.2 299.5 552.5 484.2 465C491.7 461.3 497.5 467 489.7 477zM529.5 479.2C523 495 513.5 506 508.3 510.2C502.8 514.7 498.8 512.9 501.8 506.4C504.8 499.9 521.1 459.9 514.5 451.4C508 443.1 477.5 447.1 466.5 448.2C455.7 449.2 453.5 450.2 452.5 447.9C450.2 442.2 474.2 432.4 490 430.4C505.7 428.6 531 429.6 536 436.1C539.7 441.2 536 463.2 529.5 479.2z"/></svg> 
                                    <?php endif; ?>
                                    <?php echo esc_html($button_text); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endwhile; wp_reset_postdata(); ?>
            </div>
            
            <?php 
                // View All Button Logic
                if ($show_view_all) : 
                    $target_link = $view_all_link ? $view_all_link : get_post_type_archive_link('book');
            ?>

            <div class="mt-16 text-center">
                <a href="<?php echo esc_url($target_link); ?>"
                    class="inline-flex items-center gap-2 px-8 py-3 border border-primary text-primary font-bold text-sm uppercase tracking-wider rounded-full hover:bg-primary hover:text-white transition duration-300 group">
                    <?php echo esc_html($view_all_text); ?> 
                    <svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M566.6 342.6C579.1 330.1 579.1 309.8 566.6 297.3L406.6 137.3C394.1 124.8 373.8 124.8 361.3 137.3C348.8 149.8 348.8 170.1 361.3 182.6L466.7 288L96 288C78.3 288 64 302.3 64 320C64 337.7 78.3 352 96 352L466.7 352L361.3 457.4C348.8 469.9 348.8 490.2 361.3 502.7C373.8 515.2 394.1 515.2 406.6 502.7L566.6 342.7z"/></svg>
                </a>
            </div>
            <?php endif; ?>

        <?php else : ?>
            <?php if (current_user_can('edit_posts')) : ?>
                <div class="p-8 bg-gray-100 rounded text-center text-gray-500">
                    <p><?php esc_html_e('No posts found directly matching your criteria.', 'author-website-templates'); ?></p>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</section>
