<?php
namespace Eadesigndev\DPD\Model\Sources;

use Eadesigndev\Urgent\Model\Sources\AbstractSource;
use Magento\Framework\HTTP\ClientInterface;

#[\AllowDynamicProperties]
class PickupId extends AbstractSource
{
    public function __construct(
        private ClientInterface $client
    )
    {
        $this->client = $client;
    }

    public function getAvailable()
    {
        $this->client->setHeaders([
            'Content-Type' => 'application/json'
        ]);

        $this->client->post("https://api.dpd.ro/v1/client/contract", '{ "userName": "200924597", "password": "8578877683" }');
        $response = $this->client->getBody();

        if (empty($response)) {
            return [];
        }

        $response = json_decode($response, true);

        if (empty($response["clients"])) {
            return [];
        }

        return $this->_toOptionArray($response["clients"]);
    }

    public function _toOptionArray($items)
    {
        $returnThis = [];
        foreach ($items as $client) {
            $returnThis[(string) $client['clientId']] = $client['address']['fullAddressString'];
        }

        return $returnThis;
    }

    public function toOptionArray()
    {
        return $this->getAvailable();
    }
}