<?php
/**
 * Template: AJAX search results.
 *
 * Available variables (injected by the handler):
 *   $categories      - categories array.
 *   $tags            - product tags array.
 *   $results         - products array.
 *   $recommendations - recommended / upsell products array.
 *   $term            - search term (for highlighting).
 *
 * @var array  $categories
 * @var array  $tags
 * @var array  $results
 * @var array  $recommendations
 * @var string $term
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }

/*
 * Sections are role="group" inside the listbox. Plain divs were invalid there -
 * a listbox may only contain options, or groups of options - so the
 * "Categories" / "Products" headings were dropped or mis-announced. The group
 * carries the heading as its label, and the visible title is hidden from
 * assistive tech so it is not said twice.
 */

$has_products = ! empty( $results );

/*
 * Paid sections resolve to false in the free build.
 *
 * Freemius removes this block, so the flags keep their initial value and every
 * section below stays closed. Gating here rather than at each section keeps one
 * marker instead of five, and the handler never fills these arrays in the free
 * build anyway - this makes that impossible rather than merely unlikely.
 */
$has_categories  = false;
$has_reco        = false;
$has_correction  = false;



// Display options.
$show_image          = glse_get_option( 'show_image' );
$show_price          = glse_get_option( 'show_price' );
// Row extras are paid too, and follow the same rule.
$show_sku            = false;
$show_rating         = false;
$show_category_count = false;



// Term for highlighting (sanitized upstream by handle_search, defensive cast).
$hl_term = sanitize_text_field( isset( $term ) ? (string) $term : '' );

// Kses whitelist for highlighted term (glse_highlight_term returns <mark>).
$glse_highlight_kses = [
    'mark' => [ 'class' => true ],
];

// Strict kses whitelist for WooCommerce price HTML (no iframe/embed/script).
$glse_price_kses = [
    'span'  => [ 'class' => true ],
    'bdi'   => [],
    'del'   => [],
    'ins'   => [],
    'small' => [ 'class' => true ],
];

if ( ! $has_categories && ! $has_products && ! $has_reco ) :
    /** Filter the "no results" HTML block.
     * @param string $html Default no-results markup.
     * @param string $term Search term. */
    echo wp_kses_post( (string) apply_filters( 'glse/results/no_results_html',
        '<div class="glse-no-results" role="presentation">' . esc_html__( 'No results found.', 'glance-live-search' ) . '</div>',
        $hl_term
    ) );

    
    ?>
<?php else : ?>

    <?php
    /*
     * Suggestions come first: they complete the phrase being typed, so they
     * belong next to the input, above anything that answers it. Each is an
     * option rather than a link - choosing one rewrites the query instead of
     * navigating away.
     */
    ?>

    <?php  ?>

    <?php if ( $has_products ) : ?>
        <?php
        /*
         * data-glse-search ties a click back to the exact search that produced
         * these rows. It is the only identifier the click handler needs: the
         * term and the product name already sit on that search row server-side,
         * so echoing them into every result was payload nobody read.
         */
        ?>
        <div class="glse-section glse-section-products" role="group" aria-label="<?php esc_attr_e( 'Products', 'glance-live-search' ); ?>"
             data-glse-search="<?php echo esc_attr( $search_id ?? '' ); ?>">
            <div class="glse-section-title" aria-hidden="true"><?php esc_html_e( 'Products', 'glance-live-search' ); ?></div>
            <?php foreach ( $results as $pos => $item ) : ?>
                <a href="<?php echo esc_url( $item['url'] ); ?>"
                   class="glse-result-item glse-result-product"
                   data-glse-id="<?php echo esc_attr( $item['id'] ); ?>"
                   data-glse-pos="<?php echo esc_attr( $pos ); ?>">

                    <?php if ( $show_image ) : ?>
                        <img
                            class="glse-result-img"
                            src="<?php echo esc_url( $item['image'] ); ?>"
                            alt="<?php echo esc_attr( $item['title'] ); ?>"
                            loading="lazy"
                        >
                    <?php endif; ?>

                    <div class="glse-result-info">
                        <span class="glse-result-title"><?php echo wp_kses( glse_highlight_term( $item['title'], $hl_term ), $glse_highlight_kses ); ?></span>
                        <?php  ?>
                    </div>

                    <?php if ( $show_price && isset( $item['price_html'] ) && '' !== $item['price_html'] ) : ?>
                    <div class="glse-result-price-block">
                        <span class="glse-result-price"><?php echo wp_kses( $item['price_html'], $glse_price_kses ); ?></span>
                    </div>
                    <?php endif; ?>

                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php  ?>

    <?php
    /*
     * "View all" appears whenever more matches exist than we displayed.
     * $total_found is exact while the result set fits the limit, and -1 past
     * it - the engine stops counting there so it can skip a COUNT(*) over the
     * whole match set on every keystroke. With no exact figure we simply drop
     * the number rather than print a misleading one.
     */
    $glse_more_exist  = ! empty( $has_more ) || ( isset( $total_found ) && $total_found > count( $results ) );
    $glse_exact_total = isset( $total_found ) && $total_found > 0 ? (int) $total_found : 0;
    ?>
    <?php if ( $has_products && isset( $search_url ) && $glse_more_exist ) : ?>
        <div class="glse-view-all" role="presentation" data-glse-search="<?php echo esc_attr( $search_id ?? '' ); ?>">
            <?php
            /*
             * Ce lien est suivi lui aussi, mais il ne compte pas comme une
             * reussite : demander la page complete signifie souvent que le
             * panneau n'a pas montre le bon produit. Le fondre dans le taux
             * flatterait le chiffre et masquerait ce signal.
             */
            ?>
            <a href="<?php echo esc_url( $search_url ); ?>" class="glse-view-all-link"
               data-glse-target="all"
               aria-label="<?php echo esc_attr(
                   $glse_exact_total
                       /* translators: 1: number of results, 2: search term */
                       ? sprintf( __( 'View all %1$d results for %2$s', 'glance-live-search' ), $glse_exact_total, $hl_term )
                       /* translators: %s: search term */
                       : sprintf( __( 'View all results for %s', 'glance-live-search' ), $hl_term )
               ); ?>">
                <?php
                if ( $glse_exact_total ) {
                    printf(
                        /* translators: %d: total number of products found */
                        esc_html( __( 'View all results (%d)', 'glance-live-search' ) ),
                        $glse_exact_total
                    );
                } else {
                    esc_html_e( 'View all results', 'glance-live-search' );
                }
                ?>
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
            </a>
        </div>
    <?php endif; ?>

<?php endif;
