<?php

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

class AIEO_Ratings_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', '/ratings/batch', array(
            'methods'             => \WP_REST_Server::READABLE,
            'callback'            => array($this, 'handle_batch'),
            'permission_callback' => '__return_true',
            'args'                => array(
                'product_ids' => array(
                    'required' => true,
                    'sanitize_callback' => static function ($value) {
                        if (is_string($value)) {
                            $value = array_map('trim', explode(',', $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);
                    },
                ),
                'object_type' => array(
                    'required' => false,
                    'default'  => 'product',
                    'sanitize_callback' => static function ($v) {
                        $v = sanitize_key((string) $v);
                        return in_array($v, array('product', 'brand'), true) ? $v : 'product';
                    },
                ),
            ),
        ));
    }

    
    public function handle_batch($req) {
        $ids         = (array) $req->get_param('product_ids');
        $object_type = (string) $req->get_param('object_type');
        if (empty($ids) || !class_exists('AIEO_Ratings')) {
            return new \WP_REST_Response(array(
                'stats'       => (object) array(),
                'object_type' => $object_type,
                'currency'    => null,
            ), 200);
        }
        $stats = AIEO_Ratings::instance()->get_stats_batch($ids, $object_type);

        $out = array();
        foreach ($stats as $pid => $row) {
            $out[(string) $pid] = $row;
        }

        return new \WP_REST_Response(array(
            'stats'       => empty($out) ? (object) array() : $out,
            'object_type' => $object_type,
            'currency'    => null,
        ), 200);
    }
}
