<?php
/**
 * Filter option building
 *
 * Handles building filter options (brands, price ranges, conditions) from
 * search results. This module centralizes the logic for extracting and merging
 * filter options from multiple pages of results.
 */

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

require_once PSFA_PLUGIN_DIR . 'src/core/search/functions.php';

/**
 * Build filter options from search results.
 *
 * Extracts brands, price ranges, and conditions from items, prioritizing
 * SearchRefinements from the API when available.
 *
 * @param array $items Product items from PA-API.
 * @param array|null $search_refinements SearchRefinements from API response.
 * @return array {
 *   @type array brands Available brand names
 *   @type float min_price Minimum price found
 *   @type float max_price Maximum price found
 *   @type array conditions Available condition values
 * }
 */
function psfa_build_filter_options($items, $search_refinements = null) {
    if (empty($items) || !is_array($items)) {
        return array(
            'brands' => array(),
            'min_price' => 0,
            'max_price' => 0,
            'conditions' => array(),
        );
    }

    return psfa_extract_filter_options($items, $search_refinements);
}

/**
 * Merge filter options from multiple result sets.
 *
 * Combines filter options from page 1 and page 2, taking the union of brands
 * and conditions, and the min/max of price ranges.
 *
 * @param array $options1 Filter options from first result set.
 * @param array $options2 Filter options from second result set.
 * @return array Merged filter options.
 */
function psfa_merge_filter_options($options1, $options2) {
    $merged = $options1;

    // Merge brands
    if (isset($options2['brands']) && is_array($options2['brands'])) {
        $merged['brands'] = array_unique(array_merge($merged['brands'] ?? array(), $options2['brands']));
        sort($merged['brands']);
    }

    // Merge conditions
    if (isset($options2['conditions']) && is_array($options2['conditions'])) {
        $merged['conditions'] = array_unique(array_merge($merged['conditions'] ?? array(), $options2['conditions']));
        sort($merged['conditions']);
    }

    // Update price range (take min of mins, max of maxes)
    if (isset($options2['min_price']) && $options2['min_price'] > 0) {
        if (!isset($merged['min_price']) || $merged['min_price'] == 0 || $options2['min_price'] < $merged['min_price']) {
            $merged['min_price'] = $options2['min_price'];
        }
    }

    if (isset($options2['max_price']) && $options2['max_price'] > 0) {
        if (!isset($merged['max_price']) || $merged['max_price'] == 0 || $options2['max_price'] > $merged['max_price']) {
            $merged['max_price'] = $options2['max_price'];
        }
    }

    return $merged;
}

/**
 * Build filter options from merged items and update price range.
 *
 * This is a convenience function that combines building filter options
 * from items and updating the price range from the merged item set.
 *
 * @param array $filter_options Existing filter options.
 * @param array $additional_items Additional items to extract options from.
 * @param array $all_items Combined items for price range calculation.
 * @return array Updated filter options.
 */
function psfa_build_filter_options_from_items($filter_options, $additional_items, $all_items = null) {
    $extended_options = psfa_build_filter_options($additional_items);
    
    // Merge brands and conditions
    $filter_options = psfa_merge_filter_options($filter_options, $extended_options);
    
    // Update price range from all items if provided
    if ($all_items !== null && !empty($all_items)) {
        $price_range = psfa_calculate_price_range($all_items);
        if ($price_range['min_price'] > 0) {
            $filter_options['min_price'] = $price_range['min_price'];
        }
        if ($price_range['max_price'] > 0) {
            $filter_options['max_price'] = $price_range['max_price'];
        }
    }
    
    return $filter_options;
}

/**
 * Build brand options from unfiltered category search.
 *
 * Fetches brand options from a category search without brand filter,
 * but respecting condition/merchant filters. This allows users to switch
 * brands without losing other filter context.
 *
 * @param string $category Category to search.
 * @param string $sort Sort option.
 * @param string $condition Condition filter.
 * @param string $merchant Merchant filter.
 * @return array Brand names.
 */
function psfa_build_brand_options_from_category($category, $sort, $condition, $merchant) {
    if (empty($category)) {
        return array();
    }

    global $psfa_cache_purpose;
    $psfa_cache_purpose = 'filter_options';
    $brand_result = psfa_fetch_and_merge_pages('', $category, $sort, '', $condition, $merchant, '', 0, 0, '', 0, 0);
    $psfa_cache_purpose = '';

    if (!empty($brand_result['error_message']) || empty($brand_result['merged_items'])) {
        return array();
    }

    $brand_options = psfa_build_filter_options(
        $brand_result['merged_items'],
        $brand_result['search_refinements']
    );

    return $brand_options['brands'] ?? array();
}

