<?php

namespace NewsletterBridge\Services\ImgCDN;

class ImgProxyEnc extends ImgProxy implements CDN {

    public function __construct(string $baseUrl, string $key, string $salt) {
        parent::__construct($baseUrl, $key, $salt);
    }

    public function getUrl(string $sourceUrl, array $args = []): string {
        if (empty($sourceUrl) || !$this->isConfigured()) {
            return $sourceUrl;
        }

        $processingOptions = $this->getProcessingOptions($args);
        $format = isset($args['format']) && $args['format'] !== '' ? $args['format'] : 'webp';
        $encodedSource = $this->urlSafeBase64($sourceUrl);
        $path = "/{$processingOptions}/{$encodedSource}.{$format}";

        try {
            return $this->buildSignedUrl($path);
        } catch (\Throwable $e) {
            return $sourceUrl;
        }
    }

    private function urlSafeBase64(string $input): string {
        return rtrim(strtr(base64_encode($input), '+/', '-_'), '=');
    }
}
