<?php
/**
 * Render Callback for Books Gallery Block
 * 
 * @param array $attributes Block attributes
 * @return string HTML output
 */

// Extract attributes with defaults
$heading = isset($attributes['heading']) ? $attributes['heading'] : 'My Book Shelf';
$books_per_page = isset($attributes['booksPerPage']) ? intval($attributes['booksPerPage']) : 8;
$books_per_row = isset($attributes['booksPerRow']) ? intval($attributes['booksPerRow']) : 4;
$order = isset($attributes['order']) ? $attributes['order'] : 'DESC';
$orderby = isset($attributes['orderby']) ? $attributes['orderby'] : 'date';
$exclude_books = isset($attributes['excludeBooks']) ? $attributes['excludeBooks'] : '';
$section_bg_color = isset($attributes['sectionBgColor']) ? $attributes['sectionBgColor'] : '';
$section_padding = isset($attributes['sectionPadding']) ? intval($attributes['sectionPadding']) : null;
$heading_color = isset($attributes['headingColor']) ? $attributes['headingColor'] : '';
$book_title_color = isset($attributes['bookTitleColor']) ? $attributes['bookTitleColor'] : '';
$card_bg_color = isset($attributes['cardBgColor']) ? $attributes['cardBgColor'] : '';
$block_id = isset($attributes['blockId']) ? $attributes['blockId'] : 'books-gallery';
$gallery_style = isset($attributes['galleryStyle']) ? $attributes['galleryStyle'] : 'fun';

$is_fun = $gallery_style === 'fun';
$is_elegant = $gallery_style === 'elegant';

// Map books per row to Tailwind grid classes
$grid_class = match ($books_per_row) {
    2 => 'grid-cols-1 md:grid-cols-2',
    3 => 'grid-cols-1 md:grid-cols-3',
    5 => 'grid-cols-2 md:grid-cols-5',
    default => 'grid-cols-2 md:grid-cols-4', // 4 is default
};

// Conditional container class
$container_class = ($section_bg_color || $section_padding !== null) ? '' : 'py-24';

// Build inline styles
$styles = '';
if ($section_bg_color) {
    $styles .= 'background-color: ' . esc_attr($section_bg_color) . ';';
}
if ($section_padding !== null) {
    $styles .= 'padding-top: ' . esc_attr($section_padding) . 'px;';
    $styles .= 'padding-bottom: ' . esc_attr($section_padding) . 'px;';
}

// Parse exclude IDs
$exclude_ids = array();
if (!empty($exclude_books)) {
    $exclude_ids = array_map('trim', explode(',', $exclude_books));
    $exclude_ids = array_filter($exclude_ids, 'is_numeric');
}

// Build WP_Query arguments
$query_args = array(
    'post_type' => 'book',
    'posts_per_page' => $books_per_page,
    'order' => $order,
    'orderby' => $orderby,
    'post_status' => 'publish',
);

if (!empty($exclude_ids)) {
    $query_args['post__not_in'] = $exclude_ids;
}

// Run query
$books_query = new WP_Query($query_args);

// Conditional Classes & Styles using PHP variables
$heading_class = ($is_elegant) ? 'text-3xl md:text-5xl font-serif font-bold text-brand-dark text-center mb-12' : 'section-heading';

$grid_gap_class = ($is_elegant) ? 'gap-8 lg:gap-12' : 'gap-8';

$card_wrapper_class = ($is_elegant) ? 'group text-center block' : 'book-card group block transition-transform duration-300 hover:scale-105';

$image_wrapper_class = ($is_elegant) ? 'overflow-hidden rounded bg-gray-100 shadow-md mb-6 aspect-[2/3]' : 'book-cover mb-4 rounded-lg overflow-hidden shadow-lg';

$image_class = ($is_elegant) ? 'object-cover w-full h-full transition-transform duration-500 group-hover:scale-105' : 'w-full h-auto';

$title_class = ($is_elegant) ? 'text-lg font-serif font-bold text-brand-dark group-hover:text-gray-600 transition-colors' : 'book-title text-xl font-bold text-center text-navy';

?>

<section class="alignfull block-<?php echo esc_attr($block_id); ?> <?php echo esc_attr($container_class); ?>"
    style="<?php echo esc_attr($styles); ?>">
    <div class="awt-container mx-auto px-6">
        <?php if (!empty($heading)): ?>
            <h2 class="<?php echo esc_attr($heading_class); ?>"
                style="<?php echo $heading_color ? 'color: ' . esc_attr($heading_color) . ';' : ''; ?>">
                <?php echo esc_html($heading); ?>
            </h2>
        <?php endif; ?>

        <?php if ($books_query->have_posts()): ?>
            <div class="grid <?php echo esc_attr($grid_class); ?> <?php echo esc_attr($grid_gap_class); ?>">
                <?php while ($books_query->have_posts()):
                    $books_query->the_post(); ?>
                    <div class="<?php echo esc_attr($card_wrapper_class); ?>">
                        <a href="<?php echo esc_url(get_permalink()); ?>" class="block">
                            <?php if (has_post_thumbnail()): ?>
                                <div class="<?php echo esc_attr($image_wrapper_class); ?>">
                                    <img src="<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>"
                                        alt="<?php echo esc_attr(get_the_title()); ?>" class="<?php echo esc_attr($image_class); ?>" />
                                </div>
                            <?php else: ?>
                                <div class="<?php echo esc_attr($image_wrapper_class); ?> bg-gray-200 flex items-center justify-center relative"
                                    style="<?php echo ($is_fun) ? 'height: 300px;' : ''; /* Aspect ratio handles height in elegant */ ?>">
                                    <span class="text-gray-500 absolute inset-0 flex items-center justify-center">No Image</span>
                                </div>
                            <?php endif; ?>

                            <h3 class="<?php echo esc_attr($title_class); ?>"
                                style="<?php echo $book_title_color ? 'color: ' . esc_attr($book_title_color) . ';' : ''; ?>">
                                <?php echo esc_html(get_the_title()); ?>
                            </h3>
                        </a>
                    </div>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="no-books-message text-center py-12">
                <p class="text-xl text-gray-600">
                    <?php echo esc_html__('No books found in RS Book Showcase.', 'author-website-templates'); ?>
                </p>
            </div>
        <?php endif; ?>

        <?php wp_reset_postdata(); ?>
    </div>
</section>

<?php
