<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

class RestService
{

    public function __construct()
    {
        $this->init();
    }


    public function registerRoutes(): void
    {
        register_rest_route('fss/v1', '/orders', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'fsRestGetOrders'],
                'permission_callback' => fn() => true,
            ]
        ]);

        register_rest_route('fss/v1', '/version', [
            [
                'methods' => 'GET',
                'callback' => fn() => fsPluginVersion(),
                'permission_callback' => fn() => true
            ]
        ]);
    }

    public function fsRestGetOrders(): void
    {
        $redirect_url = get_rest_url(null, 'wc/v3/orders');
        if (defined("FSS_DOCKER")) {
            $redirect_url = str_replace('://localhost', '://fss-wordpress', $redirect_url);
        }
        $redirect_url = add_query_arg($_GET, $redirect_url);
        wp_redirect($redirect_url);
    }

    public function filterOrdersByMeta(array $args, $request): array
    {
        if (!isset($request['freya-sync-processed'])) {
            return $args;
        }

        $source_meta_query = array(
            'key' => 'freya-sync-processed',
            'value' => ''
        );

        if (isset($args['meta_query'])) {
            $args['meta_query']['relation'] = 'AND';
        } else {
            $args['meta_query'] = array();
        }
        $args['meta_query'][] = $source_meta_query;

        return $args;
    }

    public function init(): void
    {
        add_filter('woocommerce_rest_shop_order_object_query', [$this, 'filterOrdersByMeta'], 0, 2);
        add_action('rest_api_init', [$this, 'registerRoutes']);
    }
}
