<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service;

use Paysera\CheckoutSdk\Entity\Metadata;
use Paysera\CheckoutSdk\Entity\PaymentCountry;
use Paysera\CheckoutSdk\Entity\PaymentLink\Experience;
use Paysera\CheckoutSdk\Entity\PaymentLink\PayerInformation;
use Paysera\CheckoutSdk\Entity\PaymentLink\PaymentDetails;
use Paysera\CheckoutSdk\Entity\PaymentLink\Purchase as PaymentLinkPurchase;
use Paysera\CheckoutSdk\Entity\PaymentLinkCreateRequest;
use Paysera\CheckoutSdk\Entity\PaymentOrder\Purchase as PaymentOrderPurchase;
use Paysera\CheckoutSdk\Entity\PaymentOrderCreateRequest;
use Paysera\PrestashopPayments\Provider\UrlProvider;

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

class OrderConverter
{
    private MoneyConverter $moneyConverter;
    private UrlProvider $urlProvider;

    public function __construct(MoneyConverter $moneyConverter, UrlProvider $urlProvider)
    {
        $this->moneyConverter = $moneyConverter;
        $this->urlProvider = $urlProvider;
    }

    public function buildPaymentOrderRequest(\Cart $cart, \Order $order): PaymentOrderCreateRequest
    {
        $customer = new \Customer($cart->id_customer);

        return new PaymentOrderCreateRequest(
            new PaymentOrderPurchase(
                $this->buildOrderPurpose($customer, $order),
                $this->moneyConverter->getAmountInCents($cart),
                $this->moneyConverter->getCurrencyCode($cart),
            ),
            new Metadata(
                $this->urlProvider->getShopBaseUrl(),
                'PrestaShop',
                _PS_VERSION_,
                'Paysera Checkout',
                \PayseraPayments::VERSION,
            ),
            $this->urlProvider->create($cart),
            'prestashop'
        );
    }

    public function buildPaymentLinkRequest(\Cart $cart, \Order $order, string $paymentMethodKey = null, string $countryCode = null): PaymentLinkCreateRequest
    {
        $customer = new \Customer($cart->id_customer);

        return new PaymentLinkCreateRequest(
            sprintf('%s Payment (PrestaShop)', date('F')),
            new Experience(
                $this->getLanguageCode($cart),
                $paymentMethodKey !== null && $paymentMethodKey !== '' ? Experience::PAYMENT_FLOW_DIRECT : Experience::PAYMENT_FLOW_CHECKOUT,
            ),
            new PaymentLinkPurchase(
                $this->moneyConverter->getAmountInCents($cart),
            ),
            new Metadata(
                $this->urlProvider->getShopBaseUrl(),
                'PrestaShop',
                _PS_VERSION_,
                'Paysera Checkout',
                \PayseraPayments::VERSION,
            ),
            null,
            null,
            new PaymentDetails(
                key: $paymentMethodKey !== null && $paymentMethodKey !== '' ? $paymentMethodKey : null,
                purpose: $this->buildOrderPurpose($customer, $order),
                countryCode: $this->resolveCountryCode($countryCode),
            ),
            $this->buildPayerInformation($customer),
        );
    }

    private function buildOrderPurpose(\Customer $customer, \Order $order): string
    {
        $firstName = trim((string) $customer->firstname);

        if ($firstName !== '') {
            return sprintf('%d - %s', $order->id, $firstName);
        }

        return sprintf('%d', $order->id);
    }

    private function buildPayerInformation(\Customer $customer): ?PayerInformation
    {
        $email = (string) $customer->email;

        if ($email === '') {
            return null;
        }

        $firstName = (string) $customer->firstname;
        $lastName = (string) $customer->lastname;
        $fullName = trim($firstName . ' ' . $lastName);

        return new PayerInformation(
            $fullName !== '' ? $fullName : null,
            $email,
        );
    }

    private function resolveCountryCode(?string $countryCode): ?string
    {
        if (
            $countryCode === null
            || $countryCode === ''
            || $countryCode === PaymentCountry::ALL_COUNTRIES_CODE
            || $countryCode === PaymentCountry::OTHER_COUNTRIES_CODE
        ) {
            return null;
        }

        return $countryCode;
    }

    private function getLanguageCode(\Cart $cart): string
    {
        $language = new \Language($cart->id_lang);
        $isoCode = (string) $language->iso_code;

        return strtolower($isoCode);
    }
}
