<?php

namespace SoftminalB2B\Http\Controllers;

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

use SoftminalB2B\Models\Group;

/**
 * Search endpoints backing the admin pickers (product, customer, category).
 * Kept deliberately small: no writes, tight result caps.
 */
class LookupController extends Controller
{
    private const LIMIT = 20;

    public function products(\WP_REST_Request $request, $params = [])
    {
        $search = sanitize_text_field((string) $request->get_param('search'));

        $args = [
            'status' => 'publish',
            'limit'  => self::LIMIT,
        ];

        if ($search !== '') {
            $args['s'] = $search;
        }

        $results = [];

        foreach (wc_get_products($args) as $product) {
            $results[] = [
                'id'    => $product->get_id(),
                'name'  => $product->get_name(),
                'sku'   => $product->get_sku(),
                'price' => html_entity_decode(wp_strip_all_tags(wc_price((float) $product->get_regular_price()))),
                'type'  => $product->get_type(),
            ];
        }

        return $this->success(['products' => $results]);
    }

    public function customers(\WP_REST_Request $request, $params = [])
    {
        $search = sanitize_text_field((string) $request->get_param('search'));

        $args = [
            'number'  => self::LIMIT,
            'orderby' => 'display_name',
            'order'   => 'ASC',
        ];

        if ($search !== '') {
            $args['search']         = '*' . $search . '*';
            $args['search_columns'] = ['user_login', 'user_email', 'display_name'];
        }

        // Only customers without a group, when the caller is filling a group.
        if ($request->get_param('ungrouped')) {
            $args['meta_query'] = [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                'relation' => 'OR',
                ['key' => Group::USER_META_KEY, 'compare' => 'NOT EXISTS'],
                ['key' => Group::USER_META_KEY, 'value' => '', 'compare' => '='],
            ];
        }

        $query   = new \WP_User_Query($args);
        $results = [];

        foreach ($query->get_results() as $user) {
            $groupId = (int) get_user_meta($user->ID, Group::USER_META_KEY, true);
            $group   = $groupId ? Group::find($groupId) : null;

            $results[] = [
                'id'         => (int) $user->ID,
                'name'       => $user->display_name,
                'email'      => $user->user_email,
                'group_id'   => $groupId ?: null,
                'group_name' => $group ? $group->name : null,
            ];
        }

        return $this->success(['customers' => $results]);
    }

    public function terms(\WP_REST_Request $request, $params = [])
    {
        $taxonomy = $request->get_param('taxonomy') === 'product_tag' ? 'product_tag' : 'product_cat';
        $search   = sanitize_text_field((string) $request->get_param('search'));

        $terms = get_terms([
            'taxonomy'   => $taxonomy,
            'hide_empty' => false,
            'number'     => self::LIMIT,
            'search'     => $search !== '' ? $search : '',
        ]);

        $results = [];

        if (!is_wp_error($terms)) {
            foreach ($terms as $term) {
                $results[] = [
                    'id'    => (int) $term->term_id,
                    'name'  => $term->name,
                    'count' => (int) $term->count,
                ];
            }
        }

        return $this->success(['terms' => $results]);
    }
}
