<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

class RestService
{

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


    public function registerRoutes()
    {
        register_rest_route('fss/v1', '/getOrders', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'fsRestGetOrders'],
                'permission_callback' => [$this, 'permissionCheck'],
            ]
        ]);
    }

    public function fsRestGetOrders()
    {
        $meta_query[] = [
            'relation' => 'AND',
            ['key' => 'freya-sync-processed', 'compare' => '=', 'value' => ''],
        ];

        $args = [
            'meta_query' => $meta_query,
            'status' => array('wc-completed', 'wc-processing'),
            'limit' => 10000,
            'paged' => 1,
            'return' => 'ids',
            'orderby' => 'date',
            'order' => 'DESC',
        ];

        // $order = wc_get_order( $order_id );\
        // return wc_get_is_paid_statuses();
        return wc_get_order_statuses();

        $ordersIds = wc_get_orders($args);

        $ordersResult = array();

        foreach ($ordersIds as $id) {
            $ordersResult[] = wc_get_order($id);
        }

        return $ordersResult;
    }

    public function permissionCheck()
    {
        return true;
    }

    public function filterOrdersByMeta($args, $request)
    {
        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';
            $args['meta_query'][] = $source_meta_query;
        } else {
            $args['meta_query'] = array();
            $args['meta_query'][] = $source_meta_query;
        }

        return $args;
    }

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