<?php
/**
 * AJAX Handler for Book List Load More and Filtering
 * 
 * Handles AJAX requests for loading more books in the Book List block
 * and filtering books in the Book Gallery block.
 * 
 * @package Author_Website_Templates
 * @since 1.0.0
 */

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

/**
 * Enqueue Load More Script
 */
function rswpthemes_awt_enqueue_load_more_script() {
    wp_enqueue_script(
        'awt-load-more',
        RSWPTHEMES_AWT_PLUGIN_URL . 'assets/js/load-more.js',
        array( 'jquery' ),
        RSWPTHEMES_AWT_VERSION,
        true
    );
    
    // Localize script with AJAX URL and nonce
    wp_localize_script( 'awt-load-more', 'awtLoadMore', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'awt_load_more_nonce' ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'rswpthemes_awt_enqueue_load_more_script' );

/**
 * AJAX Handler - Load More Books
 */
function rswpthemes_awt_load_more_books() {
    // Verify nonce
    check_ajax_referer( 'awt_load_more_nonce', 'nonce' );
    
    // Get query data from request
    $query_data = isset( $_POST['query_data'] ) ? json_decode( stripslashes( $_POST['query_data'] ), true ) : array();
    $current_page = isset( $_POST['current_page'] ) ? absint( $_POST['current_page'] ) : 1;
    
    // Sanitize query data
    $post_type = isset( $query_data['post_type'] ) ? sanitize_text_field( $query_data['post_type'] ) : 'book';
    $posts_per_page = isset( $query_data['posts_per_page'] ) ? absint( $query_data['posts_per_page'] ) : 5;
    $categories = isset( $query_data['categories'] ) ? sanitize_text_field( $query_data['categories'] ) : '';
    
    // Build query arguments
    $args = array(
        'post_type'      => $post_type,
        'posts_per_page' => $posts_per_page,
        'post_status'    => 'publish',
        'paged'          => $current_page + 1, // Next page
    );
    
    // 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 );
    
    // Get rendered HTML
    $html = '';
    if ( function_exists( 'rswpthemes_awt_render_book_list' ) ) {
        $html = rswpthemes_awt_render_book_list( $book_query );
    }
    
    // Prepare response
    $response = array(
        'success'   => true,
        'html'      => $html,
        'max_pages' => $book_query->max_num_pages,
    );
    
    wp_send_json( $response );
}
add_action( 'wp_ajax_awt_load_more_books', 'rswpthemes_awt_load_more_books' );
add_action( 'wp_ajax_nopriv_awt_load_more_books', 'rswpthemes_awt_load_more_books' );

/**
 * AJAX Handler - Filter Books (Gallery Block)
 */
function rswpthemes_awt_filter_books() {
    
    $paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $items_per_page = isset($_POST['items_per_page']) ? intval($_POST['items_per_page']) : 12;

    $args = array(
        'post_type'      => 'book',
        'posts_per_page' => $items_per_page,
        'paged'          => $paged,
        'post_status'    => 'publish',
        'tax_query'      => array('relation' => 'AND'),
        'meta_query'     => array('relation' => 'AND'),
    );

    // -- Search --
    if (!empty($_POST['search'])) {
        $args['s'] = sanitize_text_field($_POST['search']);
    }

    // -- Context Filter (Archive Page) --
    if (!empty($_POST['current_tax']) && !empty($_POST['current_term'])) {
        $args['tax_query'][] = array(
            'taxonomy' => sanitize_text_field($_POST['current_tax']),
            'field'    => 'term_id',
            'terms'    => intval($_POST['current_term']),
            'operator' => 'IN'
        );
    }

    // -- Taxonomy Filters --
    
    // Genres
    if (!empty($_POST['genres'])) {
        $genres = is_array($_POST['genres']) ? $_POST['genres'] : explode(',', $_POST['genres']);
        $args['tax_query'][] = array(
            'taxonomy' => 'book-category',
            'field'    => 'term_id',
            'terms'    => array_map('absint', $genres),
            'operator' => 'IN'
        );
    }

    // Authors
    if (!empty($_POST['authors'])) {
        $authors = is_array($_POST['authors']) ? $_POST['authors'] : explode(',', $_POST['authors']);
        $args['tax_query'][] = array(
            'taxonomy' => 'book-author',
            'field'    => 'term_id',
            'terms'    => array_map('absint', $authors),
            'operator' => 'IN'
        );
    }

    // Series
    if (!empty($_POST['series'])) {
        $series = is_array($_POST['series']) ? $_POST['series'] : explode(',', $_POST['series']);
        $args['tax_query'][] = array(
            'taxonomy' => 'book-series',
            'field'    => 'term_id',
            'terms'    => array_map('absint', $series),
            'operator' => 'IN'
        );
    }

    // -- Meta Filters --
    
    // Format
    if (!empty($_POST['formats'])) {
        $formats = is_array($_POST['formats']) ? $_POST['formats'] : explode(',', $_POST['formats']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_format',
            'value'   => array_map('sanitize_text_field', $formats),
            'compare' => 'IN'
        );
    }

    // Language
    if (!empty($_POST['languages'])) {
        $languages = is_array($_POST['languages']) ? $_POST['languages'] : explode(',', $_POST['languages']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_language',
            'value'   => array_map('sanitize_text_field', $languages),
            'compare' => 'IN'
        );
    }
    
    // Publisher
    if (!empty($_POST['publishers'])) {
        $publishers = is_array($_POST['publishers']) ? $_POST['publishers'] : explode(',', $_POST['publishers']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_publisher_name',
            'value'   => array_map('sanitize_text_field', $publishers),
            'compare' => 'IN'
        );
    }

    // ISBN
    if (!empty($_POST['isbn'])) {
        $isbn = sanitize_text_field($_POST['isbn']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_isbn',
            'value'   => $isbn,
            'compare' => 'LIKE'
        );
    }

    // Publish Year
    if (!empty($_POST['years'])) {
        $years = is_array($_POST['years']) ? $_POST['years'] : explode(',', $_POST['years']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_publish_year',
            'value'   => array_map('sanitize_text_field', $years),
            'compare' => 'IN'
        );
    }

    // Reading Age
    if (!empty($_POST['ages'])) {
        $ages = is_array($_POST['ages']) ? $_POST['ages'] : explode(',', $_POST['ages']);
        $args['meta_query'][] = array(
            'key'     => '_rsbs_book_reading_age',
            'value'   => array_map('sanitize_text_field', $ages),
            'compare' => 'IN'
        );
    }

    // Rating (>=)
    if (!empty($_POST['ratings'])) {
        $ratings = is_array($_POST['ratings']) ? $_POST['ratings'] : explode(',', $_POST['ratings']);
        $minRating = min($ratings); // e.g. if user checks 4 and 5, query for >= 4
        $args['meta_query'][] = array(
            'key'     => '_rsbs_average_book_rating',
            'value'   => $minRating,
            'compare' => '>=',
            'type'    => 'NUMERIC'
        );
    }
    
    // Price Range
    if (!empty($_POST['price'])) {
        $price_range = sanitize_text_field($_POST['price']);
        if (strpos($price_range, '+') !== false) {
             // Handle "20+"
             $val = intval(rtrim($price_range, '+'));
             $args['meta_query'][] = array(
                'key'     => '_rsbs_book_price',
                'value'   => $val,
                'compare' => '>=',
                'type'    => 'NUMERIC'
            );
        } else {
            // Handle "10-20"
            $range = explode('-', $price_range);
            if (count($range) === 2) {
                $args['meta_query'][] = array(
                    'key'     => '_rsbs_book_price',
                    'value'   => array(intval($range[0]), intval($range[1])),
                    'compare' => 'BETWEEN',
                    'type'    => 'NUMERIC'
                );
            }
        }
    }

    // Sorting
    if (!empty($_POST['sort'])) {
        $sort = sanitize_text_field($_POST['sort']);
        switch ($sort) {
            case 'price_asc':
                $args['meta_key'] = '_rsbs_book_price';
                $args['orderby'] = 'meta_value_num';
                $args['order'] = 'ASC';
                break;
            case 'price_desc':
                $args['meta_key'] = '_rsbs_book_price';
                $args['orderby'] = 'meta_value_num';
                $args['order'] = 'DESC';
                break;
            case 'rating_desc':
                $args['meta_key'] = '_rsbs_average_book_rating';
                $args['orderby'] = 'meta_value_num';
                $args['order'] = 'DESC';
                break;
            case 'date_desc':
            case 'newest':
            default:
                $args['orderby'] = 'date';
                $args['order'] = 'DESC';
                break;
        }
    }

    // Execute Query
    $query = new WP_Query($args);

    // Define SVGs
    $icon_star = '<svg class="w-3 h-3 text-yellow-400" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z"/></svg>';
    $icon_search = '<svg class="w-4 h-4 text-gray-400 absolute left-4 top-3.5" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M480 272C480 317.9 465.1 360.3 440 394.7L566.6 521.4C579.1 533.9 579.1 554.2 566.6 566.7C554.1 579.2 533.8 579.2 521.3 566.7L394.7 440C360.3 465.1 317.9 480 272 480C157.1 480 64 386.9 64 272C64 157.1 157.1 64 272 64C386.9 64 480 157.1 480 272zM272 416C351.5 416 416 351.5 416 272C416 192.5 351.5 128 272 128C192.5 128 128 192.5 128 272C128 351.5 192.5 416 272 416z"/></svg>';
    $icon_chevron_up = '<svg class="w-3 h-3 text-gray-400 transition-transform duration-200" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M297.4 169.4C309.9 156.9 330.2 156.9 342.7 169.4L534.7 361.4C547.2 373.9 547.2 394.2 534.7 406.7C522.2 419.2 501.9 419.2 489.4 406.7L320 237.3L150.6 406.6C138.1 419.1 117.8 419.1 105.3 406.6C92.8 394.1 92.8 373.8 105.3 361.3L297.3 169.3z"/></svg>';
    $icon_pen = '<svg class="w-3 h-3 text-gray-400" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"><path d="M432.5 82.3L382.4 132.4L507.7 257.7L557.8 207.6C579.7 185.7 579.7 150.3 557.8 128.4L511.7 82.3C489.8 60.4 454.4 60.4 432.5 82.3zM343.3 161.2L342.8 161.3L198.7 204.5C178.8 210.5 163 225.7 156.4 245.5L67.8 509.8C64.9 518.5 65.9 528 70.3 535.8L225.7 380.4C224.6 376.4 224.1 372.3 224.1 368C224.1 341.5 245.6 320 272.1 320C298.6 320 320.1 341.5 320.1 368C320.1 394.5 298.6 416 272.1 416C267.8 416 263.6 415.4 259.7 414.4L104.3 569.7C112.1 574.1 121.5 575.1 130.3 572.2L394.6 483.6C414.3 477 429.6 461.2 435.6 441.3L478.8 297.2L478.9 296.7L343.4 161.2z"/></svg>';
    $icon_cart = '<svg class="w-3 h-3" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M0 24C0 10.7 10.7 0 24 0H69.5c22 0 41.5 12.8 50.6 32h411c26.3 0 45.5 25 38.6 50.4l-41 152.3c-8.5 31.4-37 53.3-69.5 53.3H170.7l5.4 28.5c2.2 11.3 12.1 19.5 23.6 19.5H488c13.3 0 24 10.7 24 24s-10.7 24-24 24H199.7c-34.6 0-64.3-24.6-70.7-58.5L77.4 54.5c-.7-3.8-4-6.5-7.9-6.5H24C10.7 48 0 37.3 0 24zM128 464a48 48 0 1 1 96 0 48 48 0 1 1 -96 0zm336-48a48 48 0 1 1 0 96 48 48 0 1 1 0-96z"/></svg>'; 

    // Buffer HTML
    ob_start();
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            
            $book_id = get_the_ID();
            $price = get_post_meta($book_id, '_rsbs_book_price', true);
            $sale_price = get_post_meta($book_id, '_rsbs_book_sale_price', true);
            $display_price = $sale_price ? $sale_price : $price;
            $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 Badge
            $format_val = get_post_meta($book_id, '_rsbs_book_format', true);

            $display_price = str_replace('$', '', $display_price);
            ?>
            <div class="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">
                <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 z-10 left-4 bg-accent text-white text-[10px] font-bold px-2 py-1 rounded uppercase"><?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-2 flex justify-between items-center">
                        <span class="text-[10px] font-bold text-accent uppercase tracking-widest px-1 py-0.5 rounded"><?php echo esc_html($cat_name); ?></span>
                        <span class="text-sm font-bold text-primary"><?php echo $display_price ? '$' . esc_html($display_price) : 'Free'; ?></span>
                    </div>
                    <h3 class="text-xl font-serif font-bold text-primary mb-1 group-hover:text-accent transition">
                        <a href="<?php echo esc_url($permalink); ?>"><?php 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="text-xs font-bold text-secondary"><?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
                        // Main Buy Button
                        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>';
                        
                        // Additional Links
                        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="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">
                                <?php _e('View Details', 'author-website-templates'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
        wp_reset_postdata();
    } else {
        echo '<p class="col-span-3 text-center text-gray-500 py-12">'.__('No books found matching your criteria.', 'author-website-templates').'</p>';
    }
    $html = ob_get_clean();

    // Pagination Logic
    $pagination_type = isset($_POST['pagination_type']) ? sanitize_text_field($_POST['pagination_type']) : 'numbers';
    $total_pages = $query->max_num_pages;
    $pagination = '';

    if ($total_pages > 1) {
        if ($pagination_type === 'load_more') {
            // Load More Button Output
            $pagination .= '<div class="text-center w-full">';
            $pagination .= '<button id="awt-load-more-btn" data-page="1" class="px-8 py-3 bg-white border border-gray-200 text-primary font-bold uppercase text-xs rounded shadow-sm hover:border-accent hover:text-accent transition">';
            $pagination .= __('Load More Books', 'author-website-templates');
            $pagination .= '</button>';
            $pagination .= '</div>';
        } else {
            // Numeric Pagination Output
            $current = max(1, $paged);
            // Prev
            if ($current > 1) {
                $pagination .= '<button data-page="'.($current-1).'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 text-secondary hover:border-accent hover:text-accent transition font-bold text-sm"><svg class="w-2.5 h-2.5" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></button>';
            }
            // Pages
            for ($i = 1; $i <= $total_pages; $i++) {
                if ($i == $current) {
                    $pagination .= '<button class="w-10 h-10 flex items-center justify-center rounded bg-primary text-white font-bold text-sm">'.$i.'</button>';
                } else {
                    $pagination .= '<button data-page="'.$i.'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 text-secondary hover:border-accent hover:text-accent transition font-bold text-sm">'.$i.'</button>';
                }
            }
            // Next
            if ($current < $total_pages) {
                $pagination .= '<button data-page="'.($current+1).'" class="awt-page-link w-10 h-10 flex items-center justify-center rounded bg-white border border-gray-200 hover:border-accent text-primary hover:bg-primary hover:text-white transition font-bold text-sm"><svg class="w-2.5 h-2.5" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></button>';
            }
        }
    }

    wp_send_json_success([
        'html' => $html,
        'pagination' => $pagination, 
        'count' => $query->found_posts,
        'max_pages' => $query->max_num_pages,
        'current_page' => $paged
    ]);
}
add_action( 'wp_ajax_awt_filter_books', 'rswpthemes_awt_filter_books' );
add_action( 'wp_ajax_nopriv_awt_filter_books', 'rswpthemes_awt_filter_books' );
