<?php

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

class AIEO_DMM_Pricing_REST {

    
    private static $instance = null;

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

    private function __construct() {
        add_action('rest_api_init', array($this, 'register_routes'));
    }

    public function register_routes() {
        register_rest_route('aieo/v1', '/pricing/batch', array(
            'methods'             => \WP_REST_Server::CREATABLE, 
            'callback'            => array($this, 'handle_batch'),
            'permission_callback' => '__return_true',
            'args'                => array(
                'product_ids' => array(
                    'required' => true,
                    'type'     => 'array',
                    'items'    => array('type' => 'integer'),
                    'sanitize_callback' => static function ($value) {
                        if (!is_array($value)) { return array(); }
                        $out = array();
                        foreach ($value as $v) {
                            $i = (int) $v;
                            if ($i > 0) { $out[] = $i; }
                        }
                        
                        return array_slice(array_values(array_unique($out)), 0, 200);
                    },
                ),
            ),
        ));
    }

    
    public function handle_batch($req) {
        $ids = (array) $req->get_param('product_ids');
        if (empty($ids)) {
            return new \WP_REST_Response(array(
                'prices'   => (object) array(),
                'role_id'  => '',
                'currency' => function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '',
            ), 200);
        }

        $engine = class_exists('AIEO_DMM_Pricing_Engine')
            ? AIEO_DMM_Pricing_Engine::instance()
            : null;
        if (!$engine) {
            return new \WP_REST_Response(array(
                'prices'   => (object) array(),
                'role_id'  => '',
                'currency' => function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '',
                'note'     => 'pricing-engine-unavailable',
            ), 200);
        }

        $user_id  = get_current_user_id();
        $role_id  = $this->resolve_role_id($user_id);
        $currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : '';

        $prices = array();
        foreach ($ids as $pid) {
            $pid = (int) $pid;
            if ($pid <= 0) { continue; }

            $product = function_exists('wc_get_product') ? wc_get_product($pid) : null;
            if (!$product) { continue; }

            $regular = (float) $product->get_regular_price();
            $sale    = (float) $product->get_sale_price();
            $effective = (float) $engine->get_effective_price($pid, $user_id);

            $prices[(string) $pid] = array(
                'regular'   => $regular,
                'sale'      => $sale > 0 ? $sale : null,
                'effective' => $effective,
                'html'      => $this->build_price_html($product, $effective),
                'currency'  => $currency,
            );
        }

        return new \WP_REST_Response(array(
            'prices'   => empty($prices) ? (object) array() : $prices,
            'role_id'  => $role_id,
            'currency' => $currency,
        ), 200);
    }

    
    private function resolve_role_id($user_id) {
        if ($user_id <= 0) { return 'guest'; }
        $user = get_userdata($user_id);
        if (!$user || empty($user->roles)) { return 'subscriber'; }
        
        return (string) reset($user->roles);
    }

    
    private function build_price_html($product, $effective) {
        if (class_exists('AIEO_Recommendations_Cache')
            && method_exists('AIEO_Recommendations_Cache', 'build_clean_price_html')) {
            
            
            try {
                $out = AIEO_Recommendations_Cache::build_clean_price_html($product, $effective);
                if (is_string($out) && $out !== '') { return $out; }
            } catch (\Throwable $e) {
                
            }
        }
        if (function_exists('wc_price')) {
            return wc_price($effective);
        }
        return number_format((float) $effective, 2, '.', '');
    }
}
