<?php
declare(strict_types=1);

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class WpcProductBundlesForWooCommerce
 *
 * Plugin Name: WPC Product Bundles for WooCommerce (Premium)
 * Plugin URI: https://wpclever.net/downloads/product-bundles/
 * Tested versions: 8.3.7
 */
class WpcProductBundlesForWooCommerce extends AbstractPlugin {

	private const PRICE_NUMBER_REGEX = '/\d{1,3}(?:[.,\s\x{00A0}]\d{3})*(?:[.,]\d+)?|\d+(?:[.,]\d+)?/u';

	public function init(): void {
		add_filter(
			'fibofilters/indexer/filters_source_query/select/price',
			[ $this, 'filter_select_price_sql' ],
			10,
			2
		);

		add_filter(
			'fibofilters/indexer/filters_source_query/data/unparsed',
			[ $this, 'filter_unparsed_data' ],
		);

		add_filter(
			'fibofilters/settings/load',
			[ $this, 'filter_settings_load' ],
			10,
			2
		);
	}

	/**
	 * Provide SQL for "price" source: prefer 'woosb_custom_price', fallback to '_price'.
	 *
	 * @param string $query       Original query.
	 * @param string $group_name  Group name.
	 */
	public function filter_select_price_sql( string $query, string $group_name ): string {
		global $wpdb;

		return $wpdb->prepare(
			", (SELECT COALESCE(
                    NULLIF( (SELECT meta_value FROM $wpdb->postmeta
                             WHERE post_id = posts.ID AND meta_key='woosb_custom_price'
                             LIMIT 1), '' ),
                    (SELECT meta_value FROM $wpdb->postmeta
                     WHERE post_id = posts.ID AND meta_key='_price'
                     LIMIT 1)
               )) AS %s",
			$group_name
		);
	}

	/**
	 * From raw "price" strings (e.g., "From $100 to $150" or "od 100zł do 150zł"),
	 * extract the first two numbers and store them as "a || b".
	 *
	 * @param array $data Data rows.
	 */
	public function filter_unparsed_data( array $data ): array {
		foreach ( $data as $row_key => $row ) {
			if ( ! isset( $row['price'] ) ) {
				continue;
			}

			$raw_price = (string) $row['price'];

			preg_match_all( self::PRICE_NUMBER_REGEX, $raw_price, $matches );
			$numbers = array_map( 'trim', $matches[0] ?? [] );

			if ( count( $numbers ) === 1 ) {
				$data[ $row_key ]['price'] = $numbers[0];
			} elseif ( count( $numbers ) >= 2 ) {
				$data[ $row_key ]['price'] = $numbers[0] . ' || ' . $numbers[1];
			} else {
				if ( function_exists( 'wc_get_product' ) && class_exists( 'WPCleverWoosb_Helper' ) ) {
					$product                   = wc_get_product( $row['ID'] );
					$data[ $row_key ]['price'] = \WPCleverWoosb_Helper::get_price( $product );
				}
			}
		}

		return $data;
	}

	public function filter_settings_load( $settings, $args ) {
		if ( $args !== 'filters_filters' || ! is_array( $settings ) ) {
			return $settings;
		}

		foreach ( $settings as $i => $filter ) {
			if (
				is_array( $filter )
				&& isset( $filter['source'] )
				&& $filter['source'] === 'price'
			) {
				$settings[ $i ]['logic'] = 'range-continuous';
			}
		}

		return $settings;
	}
}
