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

$post_count     = isset($attributes['postCount']) ? $attributes['postCount'] : 5;
$accent_color   = isset($attributes['accentColor']) ? $attributes['accentColor'] : '#ea580c';
$autoplay_speed = isset($attributes['autoplaySpeed']) ? $attributes['autoplaySpeed'] : 5000;
$enable_autoplay = isset($attributes['enableAutoplay']) ? $attributes['enableAutoplay'] : false;
$enable_title_trim = isset($attributes['enableTitleTrim']) ? $attributes['enableTitleTrim'] : false;
$title_trim_length = isset($attributes['titleTrimLength']) ? $attributes['titleTrimLength'] : 10;

// Dynamic Color Attributes
$title_color = isset($attributes['titleColor']) ? $attributes['titleColor'] : '';
$price_color = isset($attributes['priceColor']) ? $attributes['priceColor'] : '';
$excerpt_color = isset($attributes['excerptColor']) ? $attributes['excerptColor'] : '';
$blob_color_1 = isset($attributes['blobColor1']) ? $attributes['blobColor1'] : '';
$blob_color_2 = isset($attributes['blobColor2']) ? $attributes['blobColor2'] : '';
$featured_tag_bg = isset($attributes['featuredTagBg']) ? $attributes['featuredTagBg'] : '';
$featured_tag_text = isset($attributes['featuredTagText']) ? $attributes['featuredTagText'] : '';

// CSS Classes & Styles Logic
$title_class = $title_color ? '' : 'text-primary';
$title_style = $title_color ? "color: {$title_color};" : '';

$price_class = $price_color ? '' : 'text-primary';
$price_style = $price_color ? "color: {$price_color};" : '';

$excerpt_class = $excerpt_color ? '' : 'text-secondary';
$excerpt_style = $excerpt_color ? "color: {$excerpt_color};" : '';

$blob1_class = $blob_color_1 ? '' : 'bg-blue-50/50';
$blob1_style = $blob_color_1 ? "background-color: {$blob_color_1};" : '';

$blob2_class = $blob_color_2 ? '' : 'bg-accent/5';
// If blobColor2 is set, use it. Otherwise use the accent color with opacity logic from before.
$blob2_style = $blob_color_2 ? "background-color: {$blob_color_2};" : "background-color: {$accent_color}10;";

$featured_bg_class = $featured_tag_bg ? '' : 'bg-yellow-100';
$featured_bg_style = $featured_tag_bg ? "background-color: {$featured_tag_bg};" : '';

$featured_text_class = $featured_tag_text ? '' : 'text-yellow-800';
$featured_text_style = $featured_tag_text ? "color: {$featured_tag_text};" : '';

// Logic to determine Autoplay value
$autoplay_val = $enable_autoplay ? $autoplay_speed : 'false';

// Wrapper Attributes
$wrapper_classes = ['relative', 'overflow-hidden', 'h-auto', 'min-h-[600px]', 'md:min-h-[700px]', 'lg:h-[800px]', 'flex', 'items-center', 'py-20'];
// Only add bg-paper if NO background color is selected via standard supports
if (empty($attributes['backgroundColor']) && empty($attributes['style']['color']['background'])) {
    $wrapper_classes[] = 'bg-paper';
}
$wrapper_class_string = implode(' ', $wrapper_classes);

$wrapper_attributes = get_block_wrapper_attributes([
    'class' => $wrapper_class_string,
    'data-autoplay' => $autoplay_val
]);

$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="absolute top-0 right-0 w-1/2 h-full rounded-bl-[100px] -z-10 pointer-events-none <?php echo esc_attr($blob1_class); ?>" style="<?php echo esc_attr($blob1_style); ?>"></div>
		<div class="absolute bottom-0 left-0 w-64 h-64 rounded-full blur-3xl -z-10 pointer-events-none <?php echo esc_attr($blob2_class); ?>" style="<?php echo esc_attr($blob2_style); ?>"></div>

		<div class="glide hero-slider w-full h-full relative group">
			<div class="glide__track h-full" data-glide-el="track">
				<ul class="glide__slides h-full p-0 m-0">
					<?php
					while ($book_query->have_posts()) :
						$book_query->the_post();
						$book_id = get_the_ID();

						// Price Calculation Logic
						$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);

						// 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();
							}
						}

						// Logic
						$has_sale        = !empty($sale_price) && $sale_price < $regular_price && $sale_price > 0;
						$display_price   = $has_sale ? $sale_price : $regular_price;
						$currency_symbol = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$';

						$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);
						$shortDescription = get_post_meta($book_id, '_rsbs_short_description', true);
						?>
						<li class="glide__slide flex items-center h-full m-0">
							<div class="awt-container">
								<div class="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
									<div class="space-y-6">
										<?php if ( get_post_meta( $book_id, 'is_featured', true ) ) : // Optional: Logic for featured tag if it exists, or just hardcode as in example ?>
										<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider <?php echo esc_attr($featured_bg_class . ' ' . $featured_text_class); ?>" style="<?php echo esc_attr($featured_bg_style . $featured_text_style); ?>">
											<i class="fas fa-star"></i> Featured
										</div>
										<?php else : ?>
											<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider <?php echo esc_attr($featured_bg_class . ' ' . $featured_text_class); ?>" style="<?php echo esc_attr($featured_bg_style . $featured_text_style); ?>">
												<i class="fas fa-star"></i> Featured
											</div>
										<?php endif; ?>

										<div>
											<h2 class="text-4xl md:text-5xl lg:text-6xl font-serif font-bold leading-tight mb-2">
    											<a class="hover:opacity-90 transition-opacity duration-300 <?php echo esc_attr($title_class); ?>" 
												   href="<?php the_permalink(); ?>" 
												   style="<?php echo esc_attr($title_style); ?>">
													<?php 
                                                    if ( $enable_title_trim ) {
                                                        echo esc_html( wp_trim_words( get_the_title(), $title_trim_length, '...' ) );
                                                    } else {
                                                        the_title(); 
                                                    }
                                                    ?>
												</a>
											</h2>
										</div>
										<?php 
										if ($display_price) : ?>
										<div class="text-3xl font-serif font-bold <?php echo esc_attr($price_class); ?>" style="<?php echo esc_attr($price_style); ?>">
											<?php echo esc_html($currency_symbol . $display_price); ?>
											<?php if ($has_sale) : ?>
												<span class="text-lg text-gray-400 line-through font-sans font-normal ml-2">
													<?php echo esc_html($currency_symbol . $regular_price); ?>
												</span>
											<?php endif; ?>
										</div>
										<?php endif; ?>
										<div class="leading-relaxed text-lg max-w-lg line-clamp-3 <?php echo esc_attr($excerpt_class); ?>" style="<?php echo esc_attr($excerpt_style); ?>">
											<p class="leading-relaxed text-lg max-w-lg <?php echo esc_attr($excerpt_class); ?>" style="<?php echo esc_attr($excerpt_style); ?>"> 
												<?php echo $shortDescription; ?></p>
										</div>

										<div class="flex flex-wrap gap-4 pt-4">
											<?php 
											if (shortcode_exists('rswpbs_book_loop_btn')) {
												echo do_shortcode('[rswpbs_book_loop_btn]');
											}	
										
                                            echo '<a target="_blank" href="'.esc_url($buy_btn_link).'"
                                            class="px-6 py-3.5 bg-white text-primary border border-gray-200 font-bold rounded hover:border-[#FF9900] hover:text-[#FF9900] transition flex items-center gap-2">'
                                            . esc_html($buy_btn_text) .
                                            '</a>';

											$buy_links = get_post_meta($book_id, 'rswpbs_also_available_website_list', true);

											if (!empty($buy_links) && is_array($buy_links)) {
												foreach (array_slice($buy_links, 0, 2) as $link) {
													$url  = isset($link['book_url']) ? esc_url($link['book_url']) : '#';
													$name = isset($link['website_name']) ? esc_html($link['website_name']) : 'Buy Now';
													?>
													<a href="<?php echo $url; ?>" class="px-6 py-3.5 bg-white text-primary border border-gray-200 font-bold rounded hover:border-[#FF9900] hover:text-[#FF9900] transition flex items-center gap-2">
														<?php echo $name; ?>
													</a>
													<?php
												}
											}
											?>
										</div>
									</div>

									<div class="flex justify-center lg:justify-end relative">
										<?php if (has_post_thumbnail()) : ?>
											<img src="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'large'); ?>"
												class="w-[300px] md:w-[380px] rounded shadow-1xl border-4 border-white transform rotate-[-3deg] hover:rotate-0 transition duration-700">
										<?php endif; ?>
									</div>
								</div>
							</div>
						</li>
						<?php
					endwhile;
					wp_reset_postdata();
					?>
				</ul>
			</div>

			<div data-glide-el="controls">
    <button class="absolute top-1/2 left-4 md:left-8 transform -translate-y-1/2 w-12 h-12 rounded-full border border-gray-200 bg-white/80 backdrop-blur text-primary hover:bg-accent hover:text-white hover:border-accent transition flex items-center justify-center shadow-lg z-20 group" data-glide-dir="&lt;" style="--hover-bg: <?php echo esc_attr($accent_color); ?>">
        <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="absolute top-1/2 right-4 md:right-8 transform -translate-y-1/2 w-12 h-12 rounded-full border border-gray-200 bg-white/80 backdrop-blur text-primary hover:bg-accent hover:text-white hover:border-accent transition flex items-center justify-center shadow-lg z-20 group" data-glide-dir="&gt;" style="--hover-bg: <?php echo esc_attr($accent_color); ?>">
        <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>
	</section>
	<?php
else :
	?>
	<p><?php esc_html_e('No books found.', 'author-website-templates'); ?></p>
	<?php
endif;
?>
