<?php

namespace App\Classes\Modules\Transactions\Services;

use App\Models\SegmentConstant;

class CalculatesTransactionServiceCharge
{
    /** @var CalculatesTransactionTransferFee */
    private $calculatesTransactionTransferFee;

    /**
     * CalculatesTransactionServiceCharge constructor.
     * @param CalculatesTransactionTransferFee $calculatesTransactionTransferFee
     */
    public function __construct(CalculatesTransactionTransferFee $calculatesTransactionTransferFee)
    {
        $this->calculatesTransactionTransferFee = $calculatesTransactionTransferFee;
    }


    /**
     * @param float $amount
     * @param float $rate
     * @param SegmentConstant|null $service_charge
     * @return float
     */
    public function execute(float $amount, float $rate, ?SegmentConstant $service_charge)
    {

        if (!$service_charge) {
            return 0;
        }

        $transfer_fee = $this->calculatesTransactionTransferFee->execute(($amount * (1 / $rate)), $service_charge);
        if (isset($service_charge->detail->amount)) {
            return $service_charge->detail->amount->type === 'percentage' ? (($amount + $transfer_fee) * ((float) $service_charge->detail->amount->value / 100) * (1 / $rate)) :  (float) $service_charge->detail->amount->value;
        } else {
            return 0;
        }
    }
}
