<?php
/**
 * Book List Block - Server-Side Render
 * 
 * @package Author_Website_Templates
 * @since 1.0.9
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Extract attributes
$posts_to_show = isset($attributes['postsToShow']) ? absint($attributes['postsToShow']) : 5;
$categories = isset($attributes['categories']) ? sanitize_text_field($attributes['categories']) : '';
$show_load_more = isset($attributes['showLoadMore']) ? (bool) $attributes['showLoadMore'] : true;
$load_more_text = isset($attributes['loadMoreText']) ? sanitize_text_field($attributes['loadMoreText']) : __('Load More Books', 'author-website-templates');
$block_id = isset($attributes['blockId']) ? sanitize_text_field($attributes['blockId']) : 'awt-book-list-' . wp_rand();
$book_list_style = isset($attributes['bookListStyle']) ? sanitize_text_field($attributes['bookListStyle']) : 'fun';

// Display Toggles
$show_category = isset($attributes['showCategory']) ? (bool) $attributes['showCategory'] : true;
$show_description = isset($attributes['showDescription']) ? (bool) $attributes['showDescription'] : true;
$show_buy_btn = isset($attributes['showBuyBtn']) ? (bool) $attributes['showBuyBtn'] : true;
$show_details_btn = isset($attributes['showDetailsBtn']) ? (bool) $attributes['showDetailsBtn'] : true;
$desc_source = isset($attributes['descSource']) ? sanitize_text_field($attributes['descSource']) : 'excerpt';

// Colors
$title_color = isset($attributes['titleColor']) ? $attributes['titleColor'] : '';
$desc_color = isset($attributes['descColor']) ? $attributes['descColor'] : '';
$cat_color = isset($attributes['catColor']) ? $attributes['catColor'] : '';

// Buy Button Colors
$btn_bg = isset($attributes['btnBg']) ? $attributes['btnBg'] : '';
$btn_text = isset($attributes['btnText']) ? $attributes['btnText'] : '';
$btn_border = isset($attributes['btnBorder']) ? $attributes['btnBorder'] : '';
$btn_hover_bg = isset($attributes['btnHoverBg']) ? $attributes['btnHoverBg'] : '';
$btn_hover_text = isset($attributes['btnHoverText']) ? $attributes['btnHoverText'] : '';
$btn_hover_border = isset($attributes['btnHoverBorder']) ? $attributes['btnHoverBorder'] : '';

// View Button Colors
$view_btn_bg = isset($attributes['viewBtnBg']) ? $attributes['viewBtnBg'] : '';
$view_btn_text = isset($attributes['viewBtnText']) ? $attributes['viewBtnText'] : '';
$view_btn_border = isset($attributes['viewBtnBorder']) ? $attributes['viewBtnBorder'] : '';
$view_btn_hover_bg = isset($attributes['viewBtnHoverBg']) ? $attributes['viewBtnHoverBg'] : '';
$view_btn_hover_text = isset($attributes['viewBtnHoverText']) ? $attributes['viewBtnHoverText'] : '';
$view_btn_hover_border = isset($attributes['viewBtnHoverBorder']) ? $attributes['viewBtnHoverBorder'] : '';

// Load More Button Colors
$loadmore_bg = isset($attributes['loadMoreBtnBg']) ? $attributes['loadMoreBtnBg'] : '';
$loadmore_text = isset($attributes['loadMoreBtnText']) ? $attributes['loadMoreBtnText'] : '';
$loadmore_hover_bg = isset($attributes['loadMoreBtnHoverBg']) ? $attributes['loadMoreBtnHoverBg'] : '';
$loadmore_hover_text = isset($attributes['loadMoreBtnHoverText']) ? $attributes['loadMoreBtnHoverText'] : '';

// Build query arguments
$args = array(
    'post_type' => 'book',
    'posts_per_page' => $posts_to_show,
    'post_status' => 'publish',
    'paged' => 1,
);

// Add category filter if specified
if (!empty($categories)) {
    $cat_ids = array_map('absint', explode(',', $categories));
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'book-category',
            'field' => 'term_id',
            'terms' => $cat_ids,
        ),
    );
}

// Run query
$book_query = new WP_Query($args);

// Prepare data attributes for AJAX
$query_data = array(
    'post_type' => 'book',
    'posts_per_page' => $posts_to_show,
    'categories' => $categories,
);

$container_class = 'awt-book-list-container awt-container container mx-auto px-6 py-24';
$container_class .= ($book_list_style === 'elegant') ? ' max-w-6xl space-y-24' : ' max-w-5xl space-y-20';

// Generate CSS Variables for Container
$css_variables = [
    '--awt-title-color' => $title_color,
    '--awt-desc-color' => $desc_color,
    '--awt-cat-color' => $cat_color,
    '--awt-btn-bg' => $btn_bg,
    '--awt-btn-text' => $btn_text,
    '--awt-btn-border' => $btn_border,
    '--awt-btn-hover-bg' => $btn_hover_bg,
    '--awt-btn-hover-text' => $btn_hover_text,
    '--awt-btn-hover-border' => $btn_hover_border,
    '--awt-view-btn-bg' => $view_btn_bg,
    '--awt-view-btn-text' => $view_btn_text,
    '--awt-view-btn-border' => $view_btn_border,
    '--awt-view-btn-hover-bg' => $view_btn_hover_bg,
    '--awt-view-btn-hover-text' => $view_btn_hover_text,
    '--awt-view-btn-hover-border' => $view_btn_hover_border,
    '--awt-loadmore-bg' => $loadmore_bg,
    '--awt-loadmore-text' => $loadmore_text,
    '--awt-loadmore-hover-bg' => $loadmore_hover_bg,
    '--awt-loadmore-hover-text' => $loadmore_hover_text,
];

$style_attr = '';
foreach ($css_variables as $var => $value) {
    if (!empty($value)) {
        $style_attr .= "{$var}: {$value}; ";
    }
}

// Global Scoped Styles (Applied to both styles, using vars)
$css_rules = [];

// Typography
if ($title_color) $css_rules[] = "#{$block_id} h3, #{$block_id} .awt-book-title { color: var(--awt-title-color) !important; }";
if ($desc_color) $css_rules[] = "#{$block_id} p, #{$block_id} .awt-book-desc { color: var(--awt-desc-color) !important; }";
if ($cat_color) $css_rules[] = "#{$block_id} span, #{$block_id} .awt-book-cat { color: var(--awt-cat-color) !important; }";

// Buy Button Colors
if ($btn_bg || $btn_text || $btn_border) {
    // Normal State
    $rule = "#{$block_id} .awt-btn-buy, #{$block_id} .btn-yellow {";
    if ($btn_bg) $rule .= "background-color: var(--awt-btn-bg) !important;";
    if ($btn_text) $rule .= "color: var(--awt-btn-text) !important;";
    if ($btn_border) $rule .= "border-color: var(--awt-btn-border) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

if ($btn_hover_bg || $btn_hover_text || $btn_hover_border) {
    // Hover State
    $rule = "#{$block_id} .awt-btn-buy:hover, #{$block_id} .btn-yellow:hover {";
    if ($btn_hover_bg) $rule .= "background-color: var(--awt-btn-hover-bg) !important;";
    if ($btn_hover_text) $rule .= "color: var(--awt-btn-hover-text) !important;";
    if ($btn_hover_border) $rule .= "border-color: var(--awt-btn-hover-border) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

// View Button Colors
if ($view_btn_bg || $view_btn_text || $view_btn_border) {
    // Normal State
    $rule = "#{$block_id} .awt-btn-view, #{$block_id} .btn-white {";
    if ($view_btn_bg) $rule .= "background-color: var(--awt-view-btn-bg) !important;";
    if ($view_btn_text) $rule .= "color: var(--awt-view-btn-text) !important;";
    if ($view_btn_border) $rule .= "border-color: var(--awt-view-btn-border) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

if ($view_btn_hover_bg || $view_btn_hover_text || $view_btn_hover_border) {
    // Hover State
    $rule = "#{$block_id} .awt-btn-view:hover, #{$block_id} .btn-white:hover {";
    if ($view_btn_hover_bg) $rule .= "background-color: var(--awt-view-btn-hover-bg) !important;";
    if ($view_btn_hover_text) $rule .= "color: var(--awt-view-btn-hover-text) !important;";
    if ($view_btn_hover_border) $rule .= "border-color: var(--awt-view-btn-hover-border) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

// Load More Button Colors
if ($loadmore_bg || $loadmore_text) {
    // Normal State
    $rule = "#{$block_id} .awt-load-more-btn {";
    if ($loadmore_bg) $rule .= "background-color: var(--awt-loadmore-bg) !important;";
    if ($loadmore_text) $rule .= "color: var(--awt-loadmore-text) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

if ($loadmore_hover_bg || $loadmore_hover_text) {
    // Hover State
    $rule = "#{$block_id} .awt-load-more-btn:hover {";
    if ($loadmore_hover_bg) $rule .= "background-color: var(--awt-loadmore-hover-bg) !important;";
    if ($loadmore_hover_text) $rule .= "color: var(--awt-loadmore-hover-text) !important;";
    $rule .= "}";
    $css_rules[] = $rule;
}

$style_block = '';
if (!empty($css_rules)) {
    $style_block = "<style>" . implode("\n", $css_rules) . "</style>";
}
?>

<?php echo $style_block; ?>
<div class="<?php echo esc_attr($container_class); ?>" id="<?php echo esc_attr($block_id); ?>"
    style="<?php echo esc_attr($style_attr); ?>"
    data-query="<?php echo esc_attr(wp_json_encode($query_data)); ?>" data-current-page="1"
    data-max-pages="<?php echo esc_attr($book_query->max_num_pages); ?>">
    <?php
    // Render book list based on style
    if ($book_list_style === 'elegant') {
        // Custom Loop for Elegant Style
        if ($book_query->have_posts()) {
            while ($book_query->have_posts()) {
                $book_query->the_post();

                // Get Book Details
                $book_id = get_the_ID();
                $permalink = get_permalink();
                $title = get_the_title();
                
                // Description Logic
                if ($desc_source === 'full') {
                    $description = get_the_content(); 
                    $description = wp_filter_nohtml_kses($description); // Basic cleanup
                    $description = strip_tags(get_the_content());
                    $description = wp_trim_words($description, 50, '...'); // Safe fallback
                } else {
                     $description = get_post_meta($book_id, '_rsbs_short_description', true);
                     if(!$description) $description = get_the_excerpt();
                }

                $thumbnail = get_the_post_thumbnail_url($book_id, 'large');

                // Get Category
                $terms = get_the_terms($book_id, 'book-category');
                $category = (!empty($terms) && !is_wp_error($terms)) ? $terms[0]->name : 'Fiction';

                // Get Buy Link (Custom Meta or Fallback)
                $buy_url = get_post_meta($book_id, 'awt_book_buy_url', true);
                if(!$buy_url) $buy_url = '#';

                // --- STYLE CLASSES START (Styles handled by CSS Vars above) ---

                // Category Classes
                $cat_classes = 'font-bold uppercase tracking-widest text-xs mb-2 block awt-book-cat';
                if (!$cat_color) $cat_classes .= ' text-slate-500';

                // Title Classes
                $title_classes = 'text-3xl md:text-4xl font-serif font-bold my-3 transition-colors awt-book-title';
                if (!$title_color) $title_classes .= ' text-slate-800 hover:text-slate-500';

                // Description Classes
                $desc_classes = 'text-lg mb-8 leading-relaxed font-light awt-book-desc';
                if (!$desc_color) $desc_classes .= ' text-slate-500';

                // Buy Button Classes
                $btn_buy_classes = 'inline-block px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border text-sm uppercase tracking-wider shadow-sm hover:shadow-md text-center awt-btn-buy';
                if (!$btn_bg) $btn_buy_classes .= ' bg-slate-900 hover:bg-slate-800'; 
                if (!$btn_text) $btn_buy_classes .= ' text-white';
                if (!$btn_border) $btn_buy_classes .= ' border-transparent';

                // View Details Button Classes
                $btn_view_classes = 'inline-block px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border text-sm uppercase tracking-wider text-center awt-btn-view';
                if (!$view_btn_bg) $btn_view_classes .= ' bg-white hover:bg-slate-800';
                if (!$view_btn_text) $btn_view_classes .= ' text-slate-800 hover:text-white';
                if (!$view_btn_border) $btn_view_classes .= ' border-slate-800';

                // --- STYLE CLASSES END ---

                ?>
                <article class="grid grid-cols-1 md:grid-cols-12 gap-12 items-center">
                    <div class="md:col-span-4 flex justify-center md:justify-start">
                        <a href="<?php echo esc_url($permalink); ?>" class="block w-full max-w-xs">
                            <?php if ($thumbnail): ?>
                                <img src="<?php echo esc_url($thumbnail); ?>" alt="<?php echo esc_attr($title); ?>"
                                    class="rounded shadow-xl w-full hover:scale-[1.02] transition-transform duration-500">
                            <?php else: ?>
                                <div class="bg-gray-200 rounded shadow-xl w-full h-64 flex items-center justify-center text-gray-400">No
                                    Cover</div>
                            <?php endif; ?>
                        </a>
                    </div>
                    <div class="md:col-span-8 text-center md:text-left">
                        <?php if($show_category): ?>
                        <span class="<?php echo esc_attr($cat_classes); ?>">
                            <?php echo esc_html($category); ?>
                        </span>
                        <?php endif; ?>

                        <a href="<?php echo esc_url($permalink); ?>">
                            <h3 class="<?php echo esc_attr($title_classes); ?>">
                                <?php echo esc_html($title); ?>
                            </h3>
                        </a>

                        <?php if($show_description): ?>
                        <p class="<?php echo esc_attr($desc_classes); ?>">
                            <?php echo wp_kses_post($description); ?>
                        </p>
                        <?php endif; ?>

                        <div class="flex flex-col sm:flex-row gap-4 justify-center md:justify-start">
                            <?php if($show_buy_btn): ?>
                            <a href="<?php echo esc_url($buy_url); ?>"
                                class="<?php echo esc_attr($btn_buy_classes); ?>"><?php esc_html_e('Buy Now', 'author-website-templates'); ?></a>
                            <?php endif; ?>
                            
                            <?php if($show_details_btn): ?>
                            <a href="<?php echo esc_url($permalink); ?>"
                                class="<?php echo esc_attr($btn_view_classes); ?>"><?php esc_html_e('View Details', 'author-website-templates'); ?></a>
                            <?php endif; ?>
                        </div>
                    </div>
                </article>
                
                <?php if ($book_query->current_post + 1 < $book_query->post_count): ?>
                    <hr class="border-gray-100">
                <?php endif; ?>
                <?php
            }
            wp_reset_postdata();
        } else {
            echo '<p>' . esc_html__('No books found.', 'author-website-templates') . '</p>';
        }

    } else {
        // Default "Fun" Style (using existing helper)
        if (function_exists('rswpthemes_awt_render_book_list')) {
            echo rswpthemes_awt_render_book_list($book_query);
        } else {
            echo '<p>' . esc_html__('Book list renderer not available.', 'author-website-templates') . '</p>';
        }
    }
    ?>
    <?php
    if ($show_load_more && $book_query->max_num_pages > 1): ?>
        <div class="text-center mt-12">
            <button id="awt-load-more-btn-<?php echo esc_attr($block_id); ?>" class="btn-fun btn-yellow awt-load-more-btn"
                data-container="#<?php echo esc_attr($block_id); ?>">
                <?php echo esc_html($load_more_text); ?>
            </button>
        </div>
    <?php endif; ?>
</div>