<?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 Evp\Component\Money\Money;
use Paysera\PrestashopPayments\Exception\CallbackValidationException;

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

class MoneyConverter
{
    public function getAmountInCents(\Cart $cart): int
    {
        $money = $this->createMoneyFromCart($cart);

        $amountInMinorUnits = $money->getAmountInMinorUnits();

        if ($amountInMinorUnits === null) {
            throw new CallbackValidationException(sprintf('Unable to calculate amount in minor units for cart %d', $cart->id));
        }

        return $amountInMinorUnits;
    }

    public function getExpectedAmountFromOrder(\Order $order): int
    {
        $currencyCode = $this->getCurrencyCodeFromOrder($order);
        $money = new Money((string) $order->total_paid, $currencyCode);

        $amountInMinorUnits = $money->getAmountInMinorUnits();

        if ($amountInMinorUnits === null) {
            throw new CallbackValidationException(sprintf('Unable to calculate amount in minor units for order %d', (int) $order->id));
        }

        return $amountInMinorUnits;
    }

    public function getCurrencyCode(\Cart $cart): string
    {
        $currency = new \Currency($cart->id_currency);

        return (string) $currency->iso_code;
    }

    public function getCurrencyCodeFromOrder(\Order $order): string
    {
        $currency = new \Currency((int) $order->id_currency);

        return (string) $currency->iso_code;
    }

    public function createMoneyFromCart(\Cart $cart): Money
    {
        $total = (string) $cart->getOrderTotal(true, \Cart::BOTH);
        $currencyCode = $this->getCurrencyCode($cart);

        return new Money($total, $currencyCode);
    }
}
