<?php

declare(strict_types=1);

namespace External\HannahBundle\Util;

class InvoiceUtil
{
    private $configuration;

    public function __construct(Configuration $configuration)
    {
        $this->configuration = $configuration;
    }

    public function getInvoicePDFContent(string $invoiceNumber, ?string $language = null): ?string
    {
        return $this->sendRequest(
            $this->getInvoiceUrl($invoiceNumber, $language),
        );
    }

    private function getInvoiceUrl(string $invoiceNumber, ?string $language = null): string
    {
        $endpoint = $this->configuration->get('invoice.renderer.url');

        return $endpoint.'/invoice/'.$invoiceNumber.($language ? "?language={$language}" : '');
    }

    private function sendRequest(string $url): ?string
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($curl);

        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) != 200) {
            return null;
        }

        return $response;
    }
}
