<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Payment;

if (!defined('_PS_VERSION_')) {
    exit;
}

class PaymentLogoResolver
{
    private string $logoDir;

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

    /**
     * @param iterable<object> $methods
     */
    public function resolve(iterable $methods): ?string
    {
        foreach ($methods as $method) {
            $url = $method->paymentProvider->logoUrl ?? null;
            if (!is_string($url) || $url === '') {
                continue;
            }

            $localFile = $this->logoDir . basename($url);
            if (file_exists($localFile)) {
                return 'providers/' . basename($url);
            }

            $this->download($url, $localFile);
        }

        return $this->fallbackByProviderName($methods);
    }

    /**
     * Providers without a logoUrl still get the bundled artwork the front-end JS
     * (`addIcon`) used to inject — served via `PaymentOption::setLogo()` instead.
     *
     * @param iterable<object> $methods
     */
    private function fallbackByProviderName(iterable $methods): string
    {
        foreach ($methods as $method) {
            $name = strtolower((string) ($method->paymentProvider->id ?? $method->paymentProvider->name ?? ''));
            if (str_contains($name, 'payu')) {
                return 'payu_simplyin.svg';
            }
            if (str_contains($name, 'paynow')) {
                return 'paynow_simplyin.png';
            }
        }

        return 'simplyin_app_logo.svg';
    }

    protected function download(string $url, string $localFile): void
    {
        if (!str_starts_with(strtolower($url), 'https://')) {
            return;
        }
        $ch = curl_init($url);
        if ($ch === false) {
            return;
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
        curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && is_string($result) && strlen($result) <= 512 * 1024) {
            @file_put_contents($localFile, $result);
        }
    }
}
