<?php

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

class Niwa_AI_Woo_RAG_Provider implements Niwa_AI_RAG_Provider_Interface {
    public function name() {
        return 'woo_keyword';
    }

    public function search( $query, $constraints = array(), $limit = 4 ) {
        $results = array();

        if ( ! class_exists( 'Niwa_AI_Frontend_Product_Matcher' ) ) {
            return $results;
        }

        $products = Niwa_AI_Frontend_Product_Matcher::search_products( $query, max( 1, intval( $limit ) ) );

        foreach ( $products as $p ) {
            $name = $p->get_name();
            if ( $this->is_excluded( $name, $constraints ) ) {
                continue;
            }

            $is_variable = method_exists( $p, 'is_type' ) ? $p->is_type( 'variable' ) : false;
            $old_price   = method_exists( $p, 'get_regular_price' ) ? $p->get_regular_price() : '';
            $sale_price  = method_exists( $p, 'get_sale_price' ) ? $p->get_sale_price() : '';
            $badge       = '';
            if ( ! empty( $old_price ) && ! empty( $sale_price ) && floatval( $old_price ) > 0 && floatval( $sale_price ) > 0 ) {
                $pct = round( ( ( floatval( $old_price ) - floatval( $sale_price ) ) / floatval( $old_price ) ) * 100 );
                if ( $pct > 0 ) {
                    $badge = '-' . $pct . '%';
                }
            }

            $image_id = method_exists( $p, 'get_image_id' ) ? $p->get_image_id() : 0;
            $image    = $image_id ? wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' ) : '';

            $results[] = array(
                'id'         => $p->get_id(),
                'name'       => $name,
                'price'      => wc_price( $p->get_price() ),
                'oldPrice'   => ! empty( $old_price ) ? wc_price( $old_price ) : '',
                'image'      => $image,
                'url'        => get_permalink( $p->get_id() ),
                'hasOptions' => (bool) $is_variable,
                'badge'      => $badge,
                '_source'    => $this->name(),
                '_score'     => 0.1,
            );
        }

        return $results;
    }

    private function is_excluded( $name, $constraints ) {
        $name = mb_strtolower( (string) $name );
        $ex   = isset( $constraints['exclude_terms'] ) && is_array( $constraints['exclude_terms'] ) ? $constraints['exclude_terms'] : array();
        foreach ( $ex as $term ) {
            if ( '' !== $term && false !== mb_stripos( $name, $term ) ) {
                return true;
            }
        }
        return false;
    }
}
