<?php

namespace App\Classes\Modules\ServiceTypes\Services;


use App\Classes\Modules\Currencies\DataTransferObjects\RateObject;
use App\Classes\Modules\Currencies\Services\Rates\CreatesRateLog;
use App\Classes\Modules\ServiceTypes\DataTransferObjects\ServiceCurrenciesObject;
use App\Models\CurrencyRate;
use App\Models\ServiceType;

class UpdatesServiceCurrencyRates
{

    /** @var CreatesRateLog */
    private $createsRateLog;

    /**
     * UpdatesServiceCurrencyRates constructor.
     * @param CreatesRateLog $createsRateLog
     */
    public function __construct(CreatesRateLog $createsRateLog)
    {
        $this->createsRateLog = $createsRateLog;
    }


    /**
     * @param ServiceType $service
     * @param array $currencies
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(ServiceType $service, array $currencies){

        /** @var ServiceCurrenciesObject $currency */
        foreach ($currencies as $currency) {

            /** @var RateObject $rate */
            foreach ($currency->getRates() as $rate){
                if($rate->getSelling()['value'] > 0){
                    /** @var CurrencyRate $query */
                    $query = $service->rates()->updateOrCreate([
                        'currency_id' => $currency->getId(),
                        'payment_method_type' => $rate->getPaymentMethodType()
                    ], ['selling' => $rate->getSelling()['value']]);

                    $this->createsRateLog->execute($query);
                }

            }

        }
    }

}