<?php

namespace App\Classes\Modules\ServiceTypes\Services;

use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Models\SegmentConstant;

class FetchesServiceConfigurations
{

    /** @var FetchesConstant */
    private $fetchesConstant;

    /** @var FetchesServiceCurrenciesConfigurations */
    private $fetchesServiceCurrenciesConfigurations;

    /** @var FetchesServiceBankConfigurations */
    private $fetchesServiceBankConfigurations;

    /**
     * FetchesServiceConfigurations constructor.
     * @param FetchesConstant $fetchesConstant
     * @param FetchesServiceCurrenciesConfigurations $fetchesServiceCurrenciesConfigurations
     */
    public function __construct(FetchesConstant $fetchesConstant, FetchesServiceCurrenciesConfigurations $fetchesServiceCurrenciesConfigurations, FetchesServiceBankConfigurations $fetchesServiceBankConfigurations)
    {
        $this->fetchesConstant = $fetchesConstant;
        $this->fetchesServiceCurrenciesConfigurations = $fetchesServiceCurrenciesConfigurations;
        $this->fetchesServiceBankConfigurations = $fetchesServiceBankConfigurations;
    }


    public function execute(SegmentConstant $constant, string $type){

        return array_merge([
            'active' => (int) $constant->detail->is_active ?? false,
            'billable' => (int) $constant->detail->is_billable ?? false,
            'bank_id' => property_exists($constant->detail, 'bank_id') ? $constant->detail->bank_id : '',
            'bank_info' => property_exists($constant->detail, 'bank_id') ? $this->fetchesServiceBankConfigurations->execute($constant) : '',
            'currencies' => $this->fetchesServiceCurrenciesConfigurations->execute($constant)
        ], $this->addConfigurations($constant)->toArray());

    }

    private function addConfigurations(SegmentConstant $constant) {

        $configurations = collect(['service_charge', 'minimum_charge', 'tax', 'po_limit']);

        return $configurations->flatMap(function($configuration) use($constant) {
            if(!property_exists($constant->detail, $configuration)) return [];

            return [$configuration => [
                'type' => $constant->detail->$configuration->type,
                'value' =>  $configuration !== 'po_limit' ? $this->covertToDecimal($constant->detail->$configuration->value) : $constant->detail->$configuration->value
            ]];

        });

    }

    private function covertToDecimal($value){
        return number_format((float)$value, 2, '.', '');
    }

}