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

declare(strict_types=1);

namespace BookiFlex\Core\Service;

use BookiFlex\Core\Admin\Settings\SettingsManager;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Core\Service\AccommodationType\AccommodationCapacityFinder;

defined( 'ABSPATH' ) || exit;

class ConfigurationService
{
    public const SUPPORTED_LANGUAGES = ['en', 'ru', 'pl'];

    public const SUPPORTED_WIDGET_LANGUAGES = [
        'auto'  => 'Follow site language',
        'en_US' => 'English',
        'ru_RU' => 'Русский',
        'pl_PL' => 'Polski',
//        'de_DE' => 'Deutsch',
//        'nl_NL' => 'Nederlands',
//        'it_IT' => 'Italiano',
//        'fr_FR' => 'Français',
    ];

    public function __construct(
        private readonly AccommodationCapacityFinder $capacityFinder
    ) {
    }

    public function getSiteUrl(): string
    {
        return get_option('siteurl');
    }

    public function getDefaultCurrency(): string
    {
        return carbon_get_theme_option(SettingsManager::DEFAULT_CURRENCY) ?? 'USD';
    }

    public function getWidgetLanguage(): string
    {
        $stored = carbon_get_theme_option(SettingsManager::WIDGET_LANGUAGE) ?? 'auto';
        if ($stored === 'auto' || empty($stored)) {
            return get_locale();
        }
        return $stored;
    }

    public function getCurrentLanguage(): string
    {
        $lang = substr((string) get_locale(), 0, 2) ?: 'en';
        return in_array($lang, self::SUPPORTED_LANGUAGES, true) ? $lang : 'en';
    }

    public function getCheckInTime(): string
    {
        return carbon_get_theme_option(SettingsManager::CHECK_IN_TIME) ?? '14:00';
    }

    public function getCheckOutTime(): string
    {
        return carbon_get_theme_option(SettingsManager::CHECK_OUT_TIME) ?? '12:00';
    }

    public function autoConfirmationForNonPayablePaymentTypes(): bool
    {
        return carbon_get_theme_option(SettingsManager::AUTO_CONFIRMATION_FOR_NON_PAYABLE_PAYMENT_TYPES) ?? false;
    }

    public function autoConfirmationAfterPaymentIsPaid(): bool
    {
        return carbon_get_theme_option(SettingsManager::AUTO_CONFIRMATION_AFTER_PAYMENT_IS_PAID) ?? true;
    }

    public function getHotelName(): string
    {
        return carbon_get_theme_option(SettingsManager::NAME) ?? '';
    }

    public function getMainEmail(): string
    {
        return carbon_get_theme_option(SettingsManager::EMAIL) ?? '';
    }

    public function getPhone(): string
    {
        return carbon_get_theme_option(SettingsManager::PHONE) ?? '';
    }

    public function getAddress(): array
    {
        return [
            'address'   => carbon_get_theme_option(SettingsManager::ADDRESS)   ?? '',
            'latitude'  => carbon_get_theme_option(SettingsManager::LATITUDE)  ?? '',
            'longitude' => carbon_get_theme_option(SettingsManager::LONGITUDE) ?? '',
        ];
    }

    public function getAgreements(): array
    {
        $agreements = carbon_get_theme_option(SettingsManager::AGREEMENTS);
        if (is_array($agreements) && !empty($agreements)) {
            return array_map(
                static function ($agreement) {
                    return [
                        'url'      => $agreement['url']      ?? '',
                        'name'     => $agreement['name']     ?? '',
                        'anchor'   => $agreement['anchor']   ?? '',
                        'combined' => $agreement['combined'] ?? false,
                        'required' => $agreement['required'] ?? false,
                    ];
                },
                $agreements
            );
        }

        return [];
    }

    public function getRulesOfLiving(): array
    {
        $rules = carbon_get_theme_option(SettingsManager::RULES_OF_LIVING);
        if (is_array($rules) && !empty($rules)) {
            return array_map(
                static function ($rule) {
                    return [
                        'text' => $rule['text'] ?? '',
                    ];
                },
                $rules
            );
        }

        return [];
    }

    public function getBankAccount(): string
    {
        return carbon_get_theme_option(SettingsManager::BANK_ACCOUNT) ?? '';
//        return apply_filters('the_content', carbon_get_theme_option(SettingsManager::BANK_ACCOUNT));
    }

    public function isBookingButtonActive(): bool
    {
        return (bool) (carbon_get_theme_option(SettingsManager::BOOKING_BUTTON_ACTIVE) ?? true);
    }

    public function getBookingButtonPosition(): string
    {
        return carbon_get_theme_option(SettingsManager::BOOKING_BUTTON_POSITION) ?? '';
    }

    public function getBookingButtonText(): string
    {
        return carbon_get_theme_option(SettingsManager::BOOKING_BUTTON_TEXT) ?? '';
    }

    public function getBookingButtonColor(): string
    {
        return carbon_get_theme_option(SettingsManager::BOOKING_BUTTON_COLOR) ?? '';
    }

    public function isBookingButtonPulse(): string
    {
        return carbon_get_theme_option(SettingsManager::BOOKING_BUTTON_PULSE) ? 'true' : 'false';
    }

    public function getChildAgePeriods(): array
    {
        $periods = carbon_get_theme_option(SettingsManager::CHILD_AGE_PERIODS) ?? [];
        return apply_filters('bflex_child_age_periods', $periods);
    }

    public function isChildrenSupportEnabled(): bool
    {
        if (!(bool) carbon_get_theme_option(SettingsManager::CHILDREN_ENABLED)) {
            return false;
        }

        return $this->hasValidChildAgePeriods();
    }

    private function hasValidChildAgePeriods(): bool
    {
        foreach ($this->getChildAgePeriods() as $period) {
            if (($period['from'] ?? '') !== '' && ($period['to'] ?? '') !== '') {
                return true;
            }
        }

        return false;
    }

    public function getChildrenGuestsConfig(): ?array
    {
        if (!$this->isChildrenSupportEnabled()) {
            return null;
        }

        $periods  = $this->getChildAgePeriods();
        $fromAges = array_filter(array_column($periods, 'from'), fn ($v) => $v !== '' && $v !== null);
        $toAges   = array_filter(array_column($periods, 'to'), fn ($v) => $v !== '' && $v !== null);

        return [
            'minAge'      => (int) min($fromAges),
            'maxAge'      => (int) max($toAges),
            'maxChildren' => (int) (carbon_get_theme_option(SettingsManager::CHILDREN_MAX_COUNT) ?? 4),
        ];
    }

    public function getMaxGuests(): int
    {
        return $this->capacityFinder->findMaxCapacity();
    }
}
