<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Shortcode handler: Display recent items slider with optional prioritized items.
 */
function doosearchas_search_recent_slider_shortcode($atts) {
    $atts = shortcode_atts(array(
        'type'        => 'product',
        'limit'       => 10,
        'per_slide'   => 3,
        'priority_ids'=> '',
    ), $atts, 'doosearchas_recent_slider');
    ob_start();
    $items = doosearchas_search_get_recent_items($atts['type'], $atts['limit'], $atts['priority_ids']);
    if (empty($items)) {
        return '<p>No recent items found.</p>';
    }
    ?>
    <div id="doosearchas_s-recent-items" data-per-slide="<?php echo esc_attr($atts['per_slide']); ?>">
        <h4 class="doosearchas_s-recent-items-title"><?php esc_html_e('Recommended products ...', 'doosearch-ajax-search-for-woo'); ?></h4>
        <div class="doosearchas_s-slider-wrapper">
            <button class="doosearchas_s-slider-btn prev">&#10094;</button>
            <div class="doosearchas_s-slider">
                <?php foreach ($items as $item): ?>
                    <div class="doosearchas_s-slide-item">
                        <a href="<?php echo esc_url($item['link']); ?>">
                            <?php
                                $image_id = get_post_thumbnail_id($item['id']);
                                if ($image_id) {
                                    echo wp_get_attachment_image($image_id, 'medium', false, array('alt' => $item['name']));
                                } else {
                                    $placeholder_id = attachment_url_to_postid(wc_placeholder_img_src());
                                    if ($placeholder_id) {
                                        echo wp_get_attachment_image($placeholder_id, 'medium', false, array('alt' => $item['name']));
                                    } else {
                                        $placeholder_product_id = get_option('woocommerce_placeholder_image');
                                        $placeholder_product = wc_get_product($placeholder_product_id);
                                        if ($placeholder_product) {
                                            $fallback_id = wc_get_image_id($placeholder_product);
                                            echo wp_get_attachment_image($fallback_id, 'medium', false, array('alt' => $item['name']));
                                        } else {
                                            $fallback_url = wc_placeholder_img_src('medium');
                                            // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Fallback image not in Media Library
                                            echo '<img src="' . esc_url($fallback_url) . '" alt="' . esc_attr($item['name']) . '" class="attachment-medium size-medium wp-post-image" />';
                                        }
                                    }
                                }
                            ?>
                            <p><?php echo esc_html($item['name']); ?></p>
                        </a>
                        <p class="doosearchas_s_rp_price"><?php echo wp_kses_post(wc_price($item['price'])); ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
            <button class="doosearchas_s-slider-btn next">&#10095;</button>
        </div>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode('doosearchas_recent_slider', 'doosearchas_search_recent_slider_shortcode');
function doosearchas_search_get_recent_items($type = 'product', $limit = 10, $priority_ids = '') {
    $priority_ids_array = array_filter(array_map('intval', explode(',', $priority_ids)));
    $items = array();
    if (!empty($priority_ids_array)) {
        $priority_query = new WP_Query(array(
            'post_type'      => $type,
            'post__in'       => $priority_ids_array,
            'orderby'        => 'post__in',
            'posts_per_page' => count($priority_ids_array),
            'post_status'    => 'publish',
        ));
        if ($priority_query->have_posts()) {
            while ($priority_query->have_posts()) {
                $priority_query->the_post();
                $items[] = doosearchas_search_build_item_data(get_the_ID(), $type);
            }
            wp_reset_postdata();
        }
    }
    $remaining = $limit - count($items);
    if ($remaining > 0) {
        $recent_query = new WP_Query(array(
            'post_type'      => $type,
            'posts_per_page' => $remaining,
            'post_status'    => 'publish',
            'orderby'        => 'date',
            'order'          => 'DESC',
            // Exclude priority items to avoid duplicates in slider.
            // Using post__not_in is necessary here and expected to run on sites with limited post volume.
            'post__not_in'   => $priority_ids_array, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in
        ));
        if ($recent_query->have_posts()) {
            while ($recent_query->have_posts()) {
                $recent_query->the_post();
                $items[] = doosearchas_search_build_item_data(get_the_ID(), $type);
            }
            wp_reset_postdata();
        }
    }
    return $items;
}

/**
 * Build item data array for use in recent items slider.
 */
function doosearchas_search_build_item_data($post_id, $type = 'product') {
    $image_id = get_post_thumbnail_id($post_id);
    $image_url = $image_id ? wp_get_attachment_image_src($image_id, 'medium')[0] : (function_exists('wc_placeholder_img_src') ? wc_placeholder_img_src('medium') : '');
    $item = array(
        'id'    => $post_id,
        'name'  => get_the_title($post_id),
        'image' => $image_url,
        'link'  => get_permalink($post_id),
    );
    if ($type === 'product' && function_exists('wc_get_product')) {
        $product = wc_get_product($post_id);
        if ($product) {
            $item['price'] = $product->get_price();
        }
    }
    return $item;
}
