<?php

namespace inpost_shipping\Model\Points;

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

class InpostPickupPoints
{
    /**
     * @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;
    }

    /**
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function syncPickupPoints(): array
    {
        try {
            $response = $this->guzzleClient
                ->request(
                    'GET',
                    $this->baseUri . '/v1/organizations/' . $this->idOrganization . '/dispatch_points',
                );
        } catch (ClientException $exception) {
            return [
                'error' => true,
                'message' => InpostHelper::decodeExceptionToArray($exception->getResponse()),
            ];
        }

        $decodedResponse = json_decode($response->getBody()->getContents(), 1);
        if (empty($decodedResponse['items'])) {
            return [
                'success' => true,
                'message' => 'Synchronization complete.',
            ];
        }

        return $this->updateOpencartPickupPoints($decodedResponse['items']);
    }

    /**
     * @param array $points
     *
     * @return array
     */
    protected function updateOpencartPickupPoints(array $points): array
    {
        $counter = 0;
        foreach ($points as $point) {
            $ocPoint = $this->ocRegistry->db->query("SELECT * FROM `".DB_PREFIX."inpost_shipping_pickup_points` WHERE name = '".$point['name']."'")->row;
            if (!empty($ocPoint)) {
                continue;
            }

            $sql = "INSERT INTO `".DB_PREFIX."inpost_shipping_pickup_points` SET 
                `name` = '".$point['name']."', 
                `hours_operation` = '".$point['office_hours']."', 
                `email` = '".$point['email']."', 
                `phone` = '".$point['phone']."', 
                `street` = '".$point['address']['street']."', 
                `housenumber` = '".$point['address']['building_number']."', 
                `postcode` = '".$point['address']['post_code']."', 
                `city` = '".$point['address']['city']."'";
            $this->ocRegistry->db->query($sql);
            $counter++;
        }

        return [
            'success' => true,
            'message' => 'Synchronization complete. Updated ' . $counter . ' points.',
        ];
    }
}