<?php
/**
 * Book Carousel Block Render Template.
 *
 * @var array $attributes Block attributes.
 * @var array $content Block content.
 * @var array $block Block instance.
 */

// Attributes
$post_count       = isset($attributes['postCount']) ? $attributes['postCount'] : 10;
$columns          = isset($attributes['columns']) ? $attributes['columns'] : 3;
$gap              = isset($attributes['gap']) ? $attributes['gap'] : 32;
$enable_autoplay  = isset($attributes['enableAutoplay']) ? $attributes['enableAutoplay'] : false;
$autoplay_speed   = isset($attributes['autoplaySpeed']) ? $attributes['autoplaySpeed'] : 3000;
$enable_title_trim = isset($attributes['enableTitleTrim']) ? $attributes['enableTitleTrim'] : false;
$title_trim_length = isset($attributes['titleTrimLength']) ? $attributes['titleTrimLength'] : 10;

// Content Attributes
$section_title      = isset($attributes['sectionTitle']) ? $attributes['sectionTitle'] : 'More Books by Author';
$section_subtitle   = isset($attributes['sectionSubtitle']) ? $attributes['sectionSubtitle'] : 'Library';
$show_section_title = isset($attributes['showSectionTitle']) ? $attributes['showSectionTitle'] : true;
$view_all_text      = isset($attributes['viewAllText']) ? $attributes['viewAllText'] : 'View All Books';
$view_all_link      = isset($attributes['viewAllLink']) ? $attributes['viewAllLink'] : '/books';
$show_view_all      = isset($attributes['showViewAll']) ? $attributes['showViewAll'] : true;

// Color Attributes
$section_bg_color = isset($attributes['sectionBgColor']) ? $attributes['sectionBgColor'] : '';
$card_bg_color    = isset($attributes['cardBgColor']) ? $attributes['cardBgColor'] : '';
$title_color      = isset($attributes['titleColor']) ? $attributes['titleColor'] : '';
$author_color     = isset($attributes['authorColor']) ? $attributes['authorColor'] : '';
$price_color      = isset($attributes['priceColor']) ? $attributes['priceColor'] : '';
$accent_color     = isset($attributes['accentColor']) ? $attributes['accentColor'] : '';
$arrow_bg_color   = isset($attributes['arrowBgColor']) ? $attributes['arrowBgColor'] : '';
$arrow_icon_color = isset($attributes['arrowIconColor']) ? $attributes['arrowIconColor'] : '';


// --- Logic for Inline Styles & Classes ---

// 1. Section BG
$section_style = $section_bg_color ? 'style="background-color: ' . esc_attr($section_bg_color) . ';"' : '';
$section_class = $section_bg_color ? 'py-24' : 'py-24 bg-paper';

// 2. Title (Section)
$title_style = $title_color ? 'style="color: ' . esc_attr($title_color) . ';"' : '';
$title_class = $title_color ? 'awt-title text-4xl font-serif font-bold mt-2' : 'awt-title text-4xl font-serif font-bold text-primary mt-2';

// 3. Subtitle (Accent)
$subtitle_style = $accent_color ? 'style="color: ' . esc_attr($accent_color) . ';"' : '';
// Note: Default for subtitle was text-accent. 
// If custom accent is set, use it. If not, use text-accent class.
$subtitle_class = $accent_color ? 'awt-subtitle font-bold text-xs uppercase tracking-widest' : 'awt-subtitle font-bold text-xs uppercase tracking-widest text-accent';

// 4. Card BG
$card_style = $card_bg_color ? 'style="background-color: ' . esc_attr($card_bg_color) . ';"' : '';
$card_class = $card_bg_color ? 'awt-card group rounded-xl shadow-sm hover:shadow-xl hover:-translate-y-1 transition duration-300 overflow-hidden border border-gray-100 flex flex-col h-full' : 'awt-card group bg-white rounded-xl shadow-sm hover:shadow-xl hover:-translate-y-1 transition duration-300 overflow-hidden border border-gray-100 flex flex-col h-full';

// 5. Book Title
$book_title_style = $title_color ? 'style="color: ' . esc_attr($title_color) . ';"' : '';
$book_title_class = $title_color ? 'awt-book-title text-xl font-serif font-bold mb-1 transition' : 'awt-book-title text-xl font-serif font-bold text-primary mb-1 transition';

// 6. Author
$author_style = $author_color ? 'style="color: ' . esc_attr($author_color) . ';"' : '';
$author_class = $author_color ? 'awt-author text-xs font-bold' : 'awt-author text-xs font-bold text-secondary';

// 7. Price
// Default price class is text-primary
$price_style = $price_color ? 'style="color: ' . esc_attr($price_color) . ';"' : '';
$price_class = $price_color ? 'awt-price text-sm font-bold' : 'awt-price text-sm font-bold text-primary';

// 8. Buttons (View Details)
// Default: border-primary text-primary
$btn_outline_style = $accent_color ? 'style="border-color: ' . esc_attr($accent_color) . '; color: ' . esc_attr($accent_color) . ';"' : '';
$btn_outline_class = $accent_color ? 'awt-btn awt-btn-outline flex-1 block py-2.5 border text-center text-xs font-bold uppercase rounded transition' : 'awt-btn awt-btn-outline flex-1 block py-2.5 border border-primary text-primary text-center text-xs font-bold uppercase rounded hover:bg-primary hover:text-white transition';

// 9. Arrows
$arrow_style = '';
if ($arrow_bg_color || $arrow_icon_color) {
    if ($arrow_bg_color) $arrow_style .= "background-color: {$arrow_bg_color};";
    if ($arrow_icon_color) $arrow_style .= "color: {$arrow_icon_color};";
    $arrow_style = 'style="' . esc_attr($arrow_style) . '"';
}


// Autoplay
$autoplay_bool = $enable_autoplay ? 'true' : 'false';

// Wrapper Attributes
$wrapper_attributes = get_block_wrapper_attributes([
    'class' => $section_class,
    'style' => $section_bg_color ? "background-color: {$section_bg_color};" : '',
    'id'    => 'other-books',
    'data-autoplay' => $autoplay_bool,
    'data-autoplay-speed' => $autoplay_speed,
    'data-columns' => $columns,
    'data-gap' => $gap
]);

// Query
$args = array(
    'post_type'      => 'book',
    'posts_per_page' => $post_count,
    'post_status'    => 'publish',
);
$book_query = new WP_Query($args);

if ($book_query->have_posts()) :
    ?>
    <section <?php echo $wrapper_attributes; ?>>
        <div class="max-w-7xl mx-auto px-6 lg:px-8 relative">

            <?php if ($show_section_title) : ?>
            <div class="text-center mb-16">
                <!-- Library Label -->
                <span class="<?php echo esc_attr($subtitle_class); ?>" <?php echo $subtitle_style; ?>>
                    <?php echo esc_html($section_subtitle); ?>
                </span>
                
                <!-- Main Title -->
                <h2 class="<?php echo esc_attr($title_class); ?>" <?php echo $title_style; ?>>
                    <?php echo esc_html($section_title); ?>
                </h2>
            </div>
            <?php endif; ?>

            <div class="glide">
                <div class="glide__track" data-glide-el="track">
                    <ul class="glide__slides py-8">
                        <?php 
                        while ($book_query->have_posts()) : $book_query->the_post();
                            $book_id = get_the_ID();
                            
                            // --- 1. Get Initial Prices from Meta ---
                            $raw_price = get_post_meta($book_id, '_rsbs_book_price', true);
                            $raw_sale_price = get_post_meta($book_id, '_rsbs_book_sale_price', true);

                            // Clean data
                            $regular_price = (float) preg_replace('/[^0-9.]/', '', $raw_price);
                            $sale_price = (float) preg_replace('/[^0-9.]/', '', $raw_sale_price);

                            // --- 2. Linked Product Override ---
                            if(function_exists('rswpbs_get_linked_product')){
                                $linked_product = rswpbs_get_linked_product();
                                if ($linked_product) {
                                    $regular_price = $linked_product->get_regular_price();
                                    $sale_price = $linked_product->get_sale_price();
                                }
                            }

                            // --- 3. Calculate Logic ---
                            $has_sale = !empty($sale_price) && $sale_price < $regular_price && $sale_price > 0;
                            $display_price = $has_sale ? $sale_price : $regular_price;
                            
                            $savings_pct = 0;
                            if ($has_sale && $regular_price > 0) {
                                $savings_pct = round((($regular_price - $sale_price) / $regular_price) * 100);
                            }

                            // Other Data
                            $rating = get_post_meta($book_id, '_rsbs_average_book_rating', true);
                            if (!is_numeric($rating)) $rating = 0;
                            
                            $author_terms = get_the_terms($book_id, 'book-author');
                            $author_name = $author_terms ? $author_terms[0]->name : 'Unknown Author';
                            $cat_terms = get_the_terms($book_id, 'book-category');
                            $cat_name = $cat_terms ? $cat_terms[0]->name : '';
                            
                            $img_url = get_the_post_thumbnail_url($book_id, 'large');
                            $short_desc = get_post_meta($book_id, '_rswpbs_short_description', true);
                            $permalink = get_permalink();
                            $buy_links = get_post_meta($book_id, 'rswpbs_also_available_website_list', true);
                            $buy_btn_text = get_post_meta($book_id, '_rsbs_buy_btn_text', true);
                            $buy_btn_link = get_post_meta($book_id, '_rsbs_buy_btn_link', true);
                            $format_val = get_post_meta($book_id, '_rsbs_book_format', true);

                            // Icons
                            $icon_star = '<svg class="w-3 h-3 text-yellow-400 fill-current" viewBox="0 0 20 20"><path d="M10 15l-5.878 3.09 1.123-6.545L.489 6.91l6.572-.955L10 0l2.939 5.955 6.572.955-4.756 4.635 1.123 6.545z"/></svg>';
                            $icon_pen = '<svg class="w-3 h-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>';
                        ?>
                        <li class="glide__slide h-auto">
                            <div class="<?php echo esc_attr($card_class); ?>" <?php echo $card_style; ?>>
                                <div class="relative p-6 bg-[#f1f5f9] flex justify-center items-center h-64 overflow-hidden">
                                    <?php if($format_val): ?>
                                    <span class="absolute top-4 left-4 bg-accent text-white text-[10px] font-bold px-2 py-1 rounded uppercase z-10" <?php echo $accent_color ? 'style="background-color: '.esc_attr($accent_color).';"' : ''; ?>>
                                        <?php echo esc_html($format_val); ?>
                                    </span>
                                    <?php endif; ?>
                                    
                                    <?php if($img_url): ?>
                                    <img src="<?php echo esc_url($img_url); ?>" class="h-48 shadow-lg rounded transform group-hover:scale-105 transition duration-500">
                                    <?php else: ?>
                                    <div class="h-48 w-32 bg-gray-200 shadow-lg rounded flex items-center justify-center text-gray-400 text-xs">No Image</div>
                                    <?php endif; ?>
                                </div>

                                <div class="p-5 flex-1 flex flex-col">
                                    
                                    <div class="mb-3 flex justify-between items-start">
                                        <span class="text-[10px] font-bold text-accent uppercase tracking-widest px-1 py-0.5 rounded mt-1" <?php echo $accent_color ? 'style="color: '.esc_attr($accent_color).';"' : ''; ?>>
                                            <?php echo esc_html($cat_name); ?>
                                        </span>

                                        <div class="flex flex-col items-end">
                                            <?php if ($has_sale) : ?>
                                                <span class="text-[10px] font-bold text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded mb-1">
                                                    Save <?php echo $savings_pct; ?>%
                                                </span>
                                                <div class="flex items-center gap-1.5 leading-none">
                                                    <span class="text-xs text-gray-400 line-through decoration-gray-400">
                                                        $<?php echo number_format($regular_price, 2); ?>
                                                    </span>
                                                    <span class="<?php echo esc_attr($price_class); ?>" <?php echo $price_style; ?>>
                                                        $<?php echo number_format($sale_price, 2); ?>
                                                    </span>
                                                </div>
                                            <?php else : ?>
                                                <span class="<?php echo esc_attr($price_class); ?> mt-1" <?php echo $price_style; ?>>
                                                    <?php echo $display_price > 0 ? '$' . number_format($display_price, 2) : 'Free'; ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <h3 class="<?php echo esc_attr($book_title_class); ?>">
                                        <a href="<?php echo esc_url($permalink); ?>" <?php echo $book_title_style; ?>><?php 
                                            echo $enable_title_trim ? wp_trim_words(get_the_title(), $title_trim_length) : get_the_title(); 
                                        ?></a>
                                    </h3>

                                    <div class="flex items-center mb-2">
                                        <div class="flex text-yellow-400 text-xs gap-0.5">
                                            <?php for($i=1; $i<=5; $i++) {
                                                echo $i <= $rating ? $icon_star : str_replace('text-yellow-400', 'text-gray-300', $icon_star);
                                            } ?>
                                        </div>
                                        <span class="text-[10px] text-gray-400 font-medium ml-1.5">(<?php echo esc_html($rating); ?>)</span>
                                    </div>

                                    <div class="flex items-center gap-2 mb-3">
                                        <?php echo $icon_pen; ?>
                                        <span class="<?php echo esc_attr($author_class); ?>" <?php echo $author_style; ?>><?php echo esc_html($author_name); ?></span>
                                    </div>

                                    <p class="text-xs text-secondary mb-4 line-clamp-3 leading-relaxed"><?php echo esc_html(wp_trim_words($short_desc, 20)); ?></p>

                                    <div class="mt-auto space-y-3">
                                        <div class="flex flex-wrap gap-2">
                                            <?php
                                            echo '<a target="_blank" href="'.esc_url($buy_btn_link).'"
                                                class="flex-1 min-w-[110px] flex items-center justify-center gap-1 py-2 bg-gray-50 border border-gray-200 rounded text-xs font-bold text-primary hover:bg-white hover:border-[#FF9900] hover:text-[#FF9900] transition">'
                                                . esc_html($buy_btn_text) .
                                            '</a>';

                                            if (!empty($buy_links)) {
                                                foreach (array_slice($buy_links, 0, 4) as $link) {
                                                    echo '<a target="_blank" href="'.esc_url($link['book_url']).'"
                                                        class="flex-1 min-w-[110px] flex items-center justify-center gap-1 py-2 bg-gray-50 border border-gray-200 rounded text-xs font-bold text-primary hover:bg-white hover:border-[#FF9900] hover:text-[#FF9900] transition">'
                                                        . esc_html($link['website_name']) .
                                                    '</a>';
                                                }
                                            }
                                            ?>
                                        </div>

                                        <div class="flex items-center gap-2 w-full">
                                            
                                            <?php 
                                            // 1. Shortcode Check & Output
                                            if ( shortcode_exists('rswpbs_book_loop_btn') ) {
                                                echo do_shortcode( '[rswpbs_book_loop_btn]' );
                                            } 
                                            ?>

                                            <a href="<?php echo esc_url($permalink); ?>" class="<?php echo esc_attr($btn_outline_class); ?>" <?php echo $btn_outline_style; ?>>
                                                <?php _e('View Details', 'author-website-templates'); ?>
                                            </a>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </li>
                        <?php endwhile; wp_reset_postdata(); ?>
                    </ul>
                </div>

                <!-- Arrows -->
                <div class="glide__arrows" data-glide-el="controls">
                    <button class="awt-arrow glide__arrow glide__arrow--left" data-glide-dir="&lt;" <?php echo $arrow_style; ?>>
                        <svg class="w-6 h-6" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                            <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>
                    </button>
                    <button class="awt-arrow glide__arrow glide__arrow--right" data-glide-dir="&gt;" <?php echo $arrow_style; ?>>
                        <svg class="w-6 h-6" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                            <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>
                    </button>
                </div>
            </div>

            <?php if ($show_view_all) : ?>
            <div class="mt-16 text-center">
                <a href="<?php echo esc_url($view_all_link); ?>"
                    class="awt-btn-view-all inline-flex items-center gap-2 px-8 py-3 border font-bold text-sm uppercase tracking-wider rounded-full transition duration-300 group"
                    <?php echo $title_color ? 'style="color: ' . esc_attr($title_color) . '; border-color: ' . esc_attr($title_color) . ';"' : 'style="border-color: currentColor;"'; ?>>
                    <?php echo esc_html($view_all_text); ?> <i class="fas fa-arrow-right group-hover:translate-x-1 transition-transform"></i>
                </a>
            </div>
            <?php endif; ?>

        </div>
    </section>
    <?php
else :
    ?>
    <p><?php esc_html_e('No books found.', 'author-website-templates'); ?></p>
    <?php
endif;