<?php
namespace Newland\Toubiz\Sync\Neos\Service;

/*
 * This file is part of the "toubiz-brochures-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Newland\Toubiz\Api\Service\AbstractService;
use Newland\Toubiz\Sync\Neos\Domain\Model\BrochureOrder;
use function Safe\json_decode;

class BrochureOrderService extends AbstractService
{
    /**
     * @var string Base URI of API endpoint.
     */
    const DEFAULT_BASE_URI = 'http://prospektbestellung.toubiz.de/';

    /**
     * @var array
     * @Flow\InjectConfiguration(path="services.Toubiz/Brochures/Api.clients")
     */
    protected $clients;

    public function createOrder(string $client, string $baseUrl, BrochureOrder $order): array
    {
        try {
            if (!array_key_exists($client, (array) $this->clients)) {
                throw new InvalidConfigurationException(sprintf('Client %s is not configured.', $client), 1554455421);
            }
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
            ];
        }

        return $this->sendRequest($client, $baseUrl, $order);
    }

    protected function sendRequest(string $client, string $baseUrl, BrochureOrder $order): array
    {
        $redirectUri = $baseUrl . '/redirect-handler/toubiz_brochure/';
        $data = [
            'choice_salutation' => $order->getSalutation(),
            'choice_title' => '',
            'entry_firstname' => $order->getFirstName(),
            'entry_lastname' => $order->getLastName(),
            'entry_street' => $order->getStreet(),
            'entry_zip' => $order->getZip(),
            'entry_location' => $order->getCity(),
            'entry_country' => $order->getCountry(),
            'choice_resonanz' => $order->getReferredBy(),
            'choice_agb' => 1, // TODO Add checkbox in frontend
            'choice_language' => $order->getLanguage(),
            'order' => 1,
            'redirect' => 1,
            'order_ok' => $redirectUri,
            'order_fail' => $redirectUri,
            'count' => [],
        ];

        foreach ($order->getBrochures() as $brochure) {
            $data['count'][$brochure] = 1;
        }

        $response = $this->httpClient->request(
            'POST',
            $this->getUri($client),
            [
                'form_params' => $data,
                'http_errors' => false,
            ]
        );

        try {
            $data = json_decode($response->getBody(), true);
            if ($data['result']) {
                return $data['result'];
            }
            throw new \Exception('Invalid response data: result key not available');
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
            ];
        }
    }

    private function getUri(string $client): string
    {
        $parameters = [
            ':client' => $client,
        ];

        $uri = str_replace(
            array_keys($parameters),
            $parameters,
            self::DEFAULT_BASE_URI . ':client/default/index.php'
        );

        return $uri;
    }
}
