<?php

declare(strict_types=1);

namespace BookiFlex\Extensions\Taxation\Provider;

use BookiFlex\Core\Contract\Adjustment\AdjustmentMode;
use BookiFlex\Core\Contract\Adjustment\AdjustmentStrategy;
use BookiFlex\Core\Contract\Adjustment\AdjustmentType;
use BookiFlex\Core\Contract\Taxation\TaxRuleProviderInterface;
use BookiFlex\Extensions\Taxation\Admin\TaxationSettings;
use BookiFlex\Extensions\Taxation\Models\TaxRule;

defined( 'ABSPATH' ) || exit;

/**
 * Accepts an object implementing TaxableInterface.
 * Determines the object type and selects the corresponding taxes.
 */
class TaxRuleProvider implements TaxRuleProviderInterface
{
    private function getVatTax(): ?TaxRule
    {
        $isActive  = carbon_get_theme_option(TaxationSettings::VAT_ENABLED)      ?? false;
        $rateValue = (float) (carbon_get_theme_option(TaxationSettings::VAT_RATE) ?? 0);
        $strategy  = carbon_get_theme_option(TaxationSettings::VAT_STRATEGY)     ?? TaxationSettings::INCLUSIVE;
        if (!$isActive) {
            return null;
        }

        return new TaxRule(
            __('VAT', 'bookiflex'),
            'accommodation_daily',
            $rateValue,
            'vat',
            AdjustmentType::Tax,
            AdjustmentMode::Percentage,
            AdjustmentStrategy::Inclusive->isEqual($strategy) ? AdjustmentStrategy::Inclusive : AdjustmentStrategy::Exclusive,
            false,
            null,
            null,
        );
    }

    /**
     * Returns an array of taxes for the specified entity types.
     *
     * @param string[] $types
     * @return Array<string, TaxRule>
     */
    public function getTaxesByEntityTypes(array $types = []): array
    {
        $taxes = [];

        if ($vat = $this->getVatTax()) {
            $taxes[] = $vat;
        }

        if (empty($types)) {
            return $taxes;
        }

        return array_filter($taxes, fn (TaxRule $tax) => in_array($tax->getEntityType(), $types));
    }
}
