<?php

namespace NewsletterBridge\Services\ImgCDN;

use Beeyev\Thumbor\Manipulations\Filter;
use Beeyev\Thumbor\Thumbor as ThumborPHP;

// use Beeyev\Thumbor\Manipulations\Fit;
// use Beeyev\Thumbor\Manipulations\Resize;

class Thumbor implements CDN {

    private string $baseUrl;
    private string $key;

    public function __construct(string $baseUrl, string $key) {
        $this->baseUrl = rtrim($baseUrl, '/') . '/';
        $this->key = $key;
    }

    public function getUrl(string $url = '', $args = []): string {
        if (empty($this->baseUrl) || empty($this->key) || empty($url)) {
            return $url;
        }

        if (!class_exists(ThumborPHP::class)) {
            return $url;
        }

        if (defined('WP_ENV') && WP_ENV === 'local') {
            return $url;
        }

        $width   = isset($args['width']) ? (int) $args['width'] : 0;
        $height  = isset($args['height']) ? (int) $args['height'] : 0;
        $quality = isset($args['quality']) ? (int) $args['quality'] : 85;
        $format  = isset($args['format']) && $args['format'] !== '' ? $args['format'] : 'webp';

        $normalizedUrl = str_replace(['http:/', 'https:/'], '', $url);

        $thumbor = new ThumborPHP($this->baseUrl, $this->key);

        if ($width > 0 || $height > 0) {
            $thumbor->resizeOrFit($width, $height);
        }

        $thumbor->addFilter(Filter::QUALITY, $quality > 0 ? $quality : 85);
        $thumbor->addFilter(Filter::FORMAT, $format);

        return $thumbor->get($normalizedUrl);
    }
}
