<?php

namespace PortalPeople\magento\services;

use GuzzleHttp\Client;
use Psr\Log\LoggerInterface;

class MagentoClient
{
    private $http;
    private $baseUrl;
    private $token;
    private $logger;

    public function __construct(string $baseUrl, string $accessToken, LoggerInterface $logger = null)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->token = $accessToken;
        $this->http = new Client(['base_uri' => $this->baseUrl, 'timeout' => 30]);
        $this->logger = $logger;
    }

    protected function headers(): array
    {
        return [
            'Authorization' => 'Bearer ' . $this->token,
            'Accept' => 'application/json'
        ];
    }

    /**
     * Fetch orders from Magento. Example: GET /rest/V1/orders?searchCriteria[pageSize]=50
     * @param array $query
     * @return array
     */
    public function getOrders(array $query = []): array
    {
        $uri = '/rest/V1/orders';
        if (!empty($query)) {
            $uri .= '?' . http_build_query($query);
        }
        $resp = $this->http->request('GET', $uri, ['headers' => $this->headers()]);
        $body = (string)$resp->getBody();
        $data = json_decode($body, true);
        return $data ?? [];
    }

    public function getOrder(int $id): array
    {
        $uri = "/rest/V1/orders/{$id}";
        $resp = $this->http->request('GET', $uri, ['headers' => $this->headers()]);
        return json_decode((string)$resp->getBody(), true) ?? [];
    }
}
