<?php
/**
 * BookiFlex Cart Extension
 *
 * @package    BookiFlex
 * @subpackage Cart
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\Cart\Service;

use BookiFlex\Core\Contract\Adjustment\AdjustmentStrategy;
use BookiFlex\Core\Contract\Taxation\TaxRuleProviderInterface;
use BookiFlex\Core\Service\ConfigurationService;

defined( 'ABSPATH' ) || exit;

class CartInitService
{
    public function __construct(
        private readonly ConfigurationService $config,
        private readonly ?TaxRuleProviderInterface $taxRuleProvider = null,
    ) {
    }

    public function getSettings(): array
    {
        return array_merge([
            'hotelInfo' => [
                'name'    => $this->config->getHotelName(),
                'address' => $this->config->getAddress(),
                'phone'   => $this->config->getPhone(),
                'email'   => $this->config->getMainEmail(),
            ],
            'baseCurrency' => $this->config->getDefaultCurrency(),
            'hotelRules'   => [
                'rules'      => $this->config->getRulesOfLiving(),
                'agreements' => $this->config->getAgreements(),
            ],
            'policies' => [
                'arrivalPolicy' => [
                    'checkInTime'  => $this->config->getCheckInTime(),
                    'checkOutTime' => $this->config->getCheckOutTime(),
                ],
            ],
            'widget' => [
                'locale' => substr($this->config->getWidgetLanguage(), 0, 2),
            ],
            'taxes' => $this->getTaxes(),
        ], $this->getAdditionalSettings());
    }

    /**
     * @return array<int, array{name: string, rate: float, included: bool}>
     */
    private function getTaxes(): array
    {
        if ($this->taxRuleProvider === null) {
            return [];
        }

        return array_values(array_map(
            static fn ($rule) => [
                'name'     => $rule->getName(),
                'rate'     => $rule->getRate(),
                'included' => $rule->getStrategy() === AdjustmentStrategy::Inclusive,
            ],
            $this->taxRuleProvider->getTaxesByEntityTypes(),
        ));
    }

    /**
     * Hook for child classes to inject extra settings (e.g. Pro extensions).
     *
     * @return array<string, mixed>
     */
    protected function getAdditionalSettings(): array
    {
        return [];
    }
}
