<?php

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

class AIEO_DMM_Role_Price_Filter {

    
    private static $instance = null;

    
    private $hooked = false;

    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    
    public function maybe_register() {
        add_action('plugins_loaded', array($this, 'register_if_needed'), 20);
    }

    
    public function register_if_needed() {
        if ($this->hooked) { return; }
        
        
        
        
        
        
        if ( defined( 'AIEO_RUNTIME_OWNS_AJAX' ) ) {
            $this->hooked = true; 
            return;
        }
        if (class_exists('OM_Role_Price_Handler')) {
            
            return;
        }
        if (!class_exists('AIEO_DMM_Pricing_Engine')) {
            
            return;
        }
        $this->hooked = true;

        
        add_filter('woocommerce_product_get_price',               array($this, 'filter_price'), 10, 2);
        add_filter('woocommerce_product_get_sale_price',          array($this, 'filter_price'), 10, 2);
        add_filter('woocommerce_product_variation_get_price',     array($this, 'filter_price'), 10, 2);
        add_filter('woocommerce_product_variation_get_sale_price',array($this, 'filter_price'), 10, 2);

        
        
        
        
        add_action('woocommerce_cart_loaded_from_session',  array($this, 'preload_cart_prices'), 5);
        add_action('woocommerce_before_calculate_totals',   array($this, 'preload_cart_prices'), 5);
    }

    
    public function preload_cart_prices() {
        if (!function_exists('WC') || !WC()->cart) { return; }
        if (!class_exists('AIEO_DMM_Pricing_Engine')) { return; }

        $ids = array();
        foreach (WC()->cart->get_cart() as $item) {
            if (!empty($item['product_id']))   { $ids[] = (int) $item['product_id']; }
            if (!empty($item['variation_id'])) { $ids[] = (int) $item['variation_id']; }
        }
        $ids = array_unique(array_filter($ids));
        if (!empty($ids)) {
            AIEO_DMM_Pricing_Engine::instance()->preload_role_prices($ids);
        }
    }

    
    public function filter_price($price, $product = null) {
        if (!$product || !is_a($product, 'WC_Product')) {
            return $price;
        }
        $pid = (int) $product->get_id();
        if ($pid <= 0) {
            return $price;
        }
        $role_price = AIEO_DMM_Pricing_Engine::instance()->get_role_price($pid);
        if ($role_price !== null && $role_price > 0) {
            return (float) $role_price;
        }
        return $price;
    }
}
