<?php

declare(strict_types=1);

if (!class_exists('Essox2Splatky')) {
    require_once 'class.Essox2Splatky.php';
}

class Essox2Rozdeleni extends Essox2Splatky
{
    public static $name = 'Essox - rozdělení platby';

    public $class = 'Essox2Rozdeleni';

    protected int $splitParts = 4;

    protected $templateOrderView = 'payment.Essox2Rozdeleni.orderView.tpl';

    protected function getSpreadedInstalments(): bool
    {
        return true;
    }

    public function processStep_5()
    {
        return '';
    }

    public function getEssoxCalcDetail(Decimal $price): ?array
    {
        $priceVal = roundPrice($price, -1, 'DB', 0)->asFloat();

        if (!($this->config['productDetail'] ?? false) || $priceVal < ($this->config['minPrice'] ?? 2000) || $priceVal > ($this->config['maxPrice'] ?? 30000)) {
            return null;
        }

        return $this->splitPrice($price);
    }

    protected function splitPrice(Decimal $price): array
    {
        $part = $price->div(toDecimal($this->splitParts))->floor();

        return [
            'parts' => $this->splitParts,
            'price' => $part->asInteger(),
        ];
    }

    public function accept($totalPrice, $freeDelivery)
    {
        $price = $totalPrice->getPriceWithVat()->asFloat();
        if ($price <= 0 && $this->order) {
            $price = $this->order->total_price;
        }

        // price has to be lower than 30000 Kč according to the documentation
        return parent::accept($totalPrice, $freeDelivery) && $price <= 30000;
    }

    public static function getSettingsConfiguration(): array
    {
        $essoxConfig = parent::getSettingsConfiguration();
        $essoxConfig['fields']['maxPrice']['tooltip'] = 'Maximální částka u které tuto možnost zobrazit na detailu produktu. (max. 30000 Kč)';
        $essoxConfig['fields']['maxPrice']['placeholder'] = '30000';

        return $essoxConfig;
    }
}
