<?php
get_header();
?>
<div class="container">
    <div class="archive-wrapper">
        <h2 class="section-title text-center">Direct From <span>Quarry Stone Supply</span></h2>

        <?php
        $taxonomies = array(
            'color_tags'    => 'color',
            'material_tags' => 'material',
            'finish_tags'   => 'finish'
        );

        if (!empty($taxonomies)) : ?>
            <form class="form-search-stone" action="<?php echo esc_url(get_post_type_archive_link('stone-product')); ?>" method="get">
                <div class="item-search">
                    <label for="search">Search</label>
                    <input type="text" name="search" id="search" placeholder="Type your text"
                           value="<?php echo esc_attr($_GET['search'] ?? ''); ?>" />
                </div>

                <?php foreach ($taxonomies as $tax_key => $taxonomy) :
                    $terms = get_terms(['taxonomy' => $tax_key, 'hide_empty' => true]);

                    if (!empty($terms)) : ?>
                        <div class="item-search">
                            <label for="<?php echo esc_attr($taxonomy); ?>">
                                <?php echo esc_html(get_taxonomy($tax_key)->labels->singular_name); ?>
                            </label>
                            <select name="<?php echo esc_attr($taxonomy); ?>" id="<?php echo esc_attr($taxonomy); ?>">
                                <option value="">Any</option>
                                <?php foreach ($terms as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>"
                                        <?php selected($_GET[$taxonomy] ?? '', $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>

                <button type="submit">Search</button>
            </form>
        <?php endif; ?>

        <?php
        $args = [
            'post_type'      => 'stone-product',
            'posts_per_page' => 10,
            'paged'          => 1,
        ];

        if (!empty($_GET['search'])) {
            $args['s'] = sanitize_text_field($_GET['search']);
        }
        $tax_query = [];
        
        foreach ($taxonomies as $tax_key => $taxonomy) {
            if (!empty($_GET[$taxonomy])) {
                $tax_query[] = [
                    'taxonomy' => $tax_key,
                    'field'    => 'slug',
                    'terms'    => sanitize_text_field($_GET[$taxonomy])
                ];
            }
        }
        
        if (!empty($tax_query)) {
            $args['tax_query'] = $tax_query;
        }

        $query = new WP_Query($args);

        if ($query->have_posts()) : ?>
            <div class="posts-list">
                <div class="items-list" id="stone-product-container">
                    <?php while ($query->have_posts()) : $query->the_post();
                        tdg_render_post_and_term_items('post', '', get_the_ID());
                    endwhile; ?>
                </div>
            </div>

            <?php if ($query->max_num_pages > 1) : ?>
                <div class="load-more-container text-center">
                    <button id="load-more" data-page="2" data-max="<?php echo esc_attr($query->max_num_pages); ?>">
                        Load More
                    </button>
                </div>
            <?php endif; ?>

        <?php else : ?>
            <p>No posts found.</p>
        <?php endif;

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
jQuery(document).ready(function($) {
    $("#load-more").on("click", function() {
        var button = $(this);
        var currentPage = parseInt(button.attr("data-page"));
        var maxPages = parseInt(button.attr("data-max"));
        var container = $("#stone-product-container");
    
        var search = $("#search").val();
        var color = $("#color").val();
        var material = $("#material").val();
        var finish = $("#finish").val();
    
        button.prop("disabled", true).text("Loading...");
    
        $.ajax({
            type: "POST",
            url: "<?php echo admin_url('admin-ajax.php'); ?>",
            data: {
                action: "load_more_stone_products",
                page: currentPage,
                search: search,
                color: color,
                material: material,
                finish: finish
            },
            success: function(response) {
                if ($.trim(response) !== "") {
                    container.append(response);
                    button.attr("data-page", currentPage + 1).prop("disabled", false).text("Load More");
    
                    if (currentPage + 1 > maxPages) {
                        button.hide();
                    }
                } else {
                    button.hide();
                }
            },
            error: function() {
                button.prop("disabled", false).text("Load More");
            }
        });
    });

});
</script>

<?php
get_footer();
?>
