<?php
/**
 * Live WooCommerce product rankings for the customer-facing agent.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Frontend_Product_Ranking_Service {

	/** Return currently visible products ordered by WooCommerce sales totals. */
	public function get_bestsellers( $limit = 6 ) {
		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'wc_get_product' ) || ! class_exists( 'WP_Query' ) ) {
			return array();
		}

		$limit = max( 1, min( 6, intval( $limit ) ) );
		$query = new WP_Query(
			array(
				'post_type'              => 'product',
				'post_status'            => 'publish',
				'posts_per_page'         => max( 12, $limit * 3 ),
				'fields'                 => 'ids',
				'meta_key'               => 'total_sales',
				'orderby'                => 'meta_value_num date',
				'order'                  => 'DESC',
				'no_found_rows'          => true,
				'ignore_sticky_posts'    => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
			)
		);

		$results = array();
		foreach ( (array) $query->posts as $product_id ) {
			$product = wc_get_product( intval( $product_id ) );
			if ( ! $product || ! $product->is_visible() || ! $product->is_in_stock() ) {
				continue;
			}
			$total_sales = max( 0, intval( $product->get_total_sales() ) );
			if ( 0 === $total_sales ) {
				continue;
			}

			$results[] = array(
				'post_id'    => $product->get_id(),
				'title'      => $product->get_name(),
				'type'       => 'product',
				'url'        => $product->get_permalink(),
				'sales_rank' => count( $results ) + 1,
				'total_sales' => $total_sales,
				'card_eligible' => true,
				'source'     => 'woo_sales_rank',
			);
			if ( count( $results ) >= $limit ) {
				break;
			}
		}

		wp_reset_postdata();
		return $results;
	}
}
