<?php

class Wiaas_Package_API {

    private static $namespace = 'wiaas';

    public static function init() {

        add_filter('woocommerce_rest_product_object_query', array(__CLASS__, 'filter_by_commercial_lead'), 10, 2);
    }

    public static function register_routes() {
        // TODO: Handle this when assigment of customer to commercial lead is done
        register_rest_route( self::$namespace, '/commercial-leads', array(
            'methods' => WP_REST_Server::READABLE,
            'callback' => array(__CLASS__, 'get_customer_commercial_leads'),
            'permission_callback' => 'is_user_logged_in'
        ) );
    }

    public static function get_customer_commercial_leads() {
        $commercial_leads = array();

        foreach (wiaas_get_commercial_leads() as $id => $name) {
            $commercial_leads[] = array(
                'id' => $id,
                'name' => $name
            );
        }

        return rest_ensure_response($commercial_leads);
    }

    public static function filter_by_commercial_lead($args, $request) {

        $catalogue_id = absint($request['cl_id']);

        $args['meta_query'] ?: array();

        $args['meta_query'][] = array(
            'key'     => '_wiaas_catalogue_'.$catalogue_id,
            'value'   =>  'yes',
        );

        return $args;
    }
}

Wiaas_Package_API::init();