<?php

namespace inpost_shipping\Model\Shipment;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use inpost_shipping\Model\Helper\InpostHelper;

class InpostDispatchHandler
{
    /**
     * @var \GuzzleHttp\Client $guzzleClient
     */
    protected $guzzleClient;

    /**
     * @var string
     */
    protected $idOrganization;

    /**
     * @var string
     */
    protected $baseUri;

    /**
     * @var string
     */
    protected $apiKey;

    /**
     * @var \stdClass
     */
    protected $ocRegistry;

    public function __construct(
        Client $guzzleClient,
        string $idOrganization,
        string $baseUri,
        string $apiKey,
        $ocRegistry
    ) {
        $this->guzzleClient = $guzzleClient;
        $this->idOrganization = $idOrganization;
        $this->baseUri = $baseUri;
        $this->apiKey = $apiKey;
        $this->ocRegistry = $ocRegistry;
    }

    /**
     * @param array $request
     *
     * @return array
     */
    public function dispatchOrder(array $request): array
    {
        try {
            $sql = "SELECT * FROM `".DB_PREFIX."inpost_shipping_pickup_points` WHERE id_pickup_point = '".(int)$request['point']."'";
            $pointData = $this->ocRegistry->db->query($sql)->row;

            $idsQuery = [];
            foreach ($request['ids'] as $id) {
                $sql = "SELECT * FROM `" . DB_PREFIX . "inpost_shipping_shipments` WHERE id_shipment = '" . (int)$id . "'";
                array_push($idsQuery, $this->ocRegistry->db->query($sql)->row['idInpost']);
            }

            $requestData = [
                'shipments' => array_values($idsQuery),
                'name' => $pointData['name'],
                'phone' => $pointData['phone'],
                'email' => $pointData['email'],
                'address' => [
                    'street' => $pointData['street'],
                    'building_number' => $pointData['housenumber'],
                    'city' => $pointData['city'],
                    'post_code' => $pointData['postcode'],
                    'country_code' => 'PL',
                ],
            ];

            $response = $this->guzzleClient
                ->request(
                    'POST',
                    $this->baseUri . '/v1/organizations/' . $this->idOrganization . '/dispatch_orders?',
                    [
                        'json' => $requestData,
                    ],
                );
        } catch (ClientException $exception) {
            return [
                InpostHelper::decodeExceptionToArray($exception->getResponse()),
            ];
        }

        return json_decode($response->getBody()->getContents(), 1);
    }
}