<?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\Admin\Settings;

use BookiFlex\Core\Admin\Field\SectionNotice;
use BookiFlex\Core\Service\ConfigurationService;
use Brick\Money\Currency;
use Carbon_Fields\Field;
use Brick\Money\ISOCurrencyProvider;

defined( 'ABSPATH' ) || exit;

/**
 * Settings fields configuration.
 *
 * Extracted from SettingsManager to separate UI configuration from business logic.
 */
final class SettingsFieldsConfig
{
    /**
     * Get ISO currencies for select field
     */
    public static function ISOCurrencies(): array
    {
        $provider   = ISOCurrencyProvider::getInstance();
        $currencies = $provider->getAvailableCurrencies();

        return array_map(fn (Currency $currency) => $currency->getName() . ' (' . $currency->getCurrencyCode() . ')', $currencies);
    }

    /**
     * General settings fields factory
     */
    public function generalSettingsFactory(): callable
    {
        $currencies = self::ISOCurrencies();

        return fn () => [
            Field::make('separator', 'bflex__localization_settings__separator',
                __('Localization Settings', 'bookiflex')),
            Field::make('select', SettingsManager::WIDGET_LANGUAGE,
                __('Widget Language', 'bookiflex'))
                ->set_autoload(true)
                ->set_options(ConfigurationService::SUPPORTED_WIDGET_LANGUAGES)
                ->set_default_value('auto')
                ->set_help_text(__('Language of the booking widget shown to guests. "Follow site language" uses the WordPress site locale. Translations are available for bundled languages only; other selections fall back to English.', 'bookiflex')),
            Field::make('select', SettingsManager::DEFAULT_CURRENCY,
                __('Default Currency', 'bookiflex'))
                ->set_autoload(true)
                ->set_options($currencies)
                ->set_default_value('USD')
                ->set_help_text(__('Default Currency', 'bookiflex')),
            Field::make('separator', 'bflex__check_in_out__separator',
                __('Check-in & Check-out Settings', 'bookiflex')),
            Field::make('text', SettingsManager::CHECK_IN_TIME,
                __('Check-in Time (from)', 'bookiflex'))
                ->set_width(50)
                ->set_autoload(true)
                ->set_attribute('type', 'time')
                ->set_required()
                ->set_default_value('14:00')
                ->set_help_text(__('The earliest time guests can check in. This is used for informational purposes and to calculate cancellation deadlines (e.g., 24h before check-in).', 'bookiflex')),
            Field::make('text', SettingsManager::CHECK_OUT_TIME,
                __('Check-out Time (until)', 'bookiflex'))
                ->set_width(50)
                ->set_autoload(true)
                ->set_attribute('type', 'time')
                ->set_required()
                ->set_default_value('12:00')
                ->set_help_text(__('The latest time guests should check out. These values are not enforced automatically but shown in booking details and guest communications.', 'bookiflex')),

            Field::make('separator', 'bflex__auto_confirmation__separator',
                __('Auto Confirmation Settings', 'bookiflex')),
            SectionNotice::make(
                'bflex__auto_confirmation__description',
                __('These settings define when a reservation is automatically marked as Confirmed.', 'bookiflex'),
                'https://bookiflex.com/support/knowledge-base/reservation-statuses/?utm_source=plugin&utm_medium=auto_confirmation&utm_campaign=documentation#how-auto-confirmation-works',
            ),
            Field::make('checkbox', SettingsManager::AUTO_CONFIRMATION_FOR_NON_PAYABLE_PAYMENT_TYPES,
                __('Auto Confirmation for Non-payable Payment Types', 'bookiflex'))
                ->set_default_value(false)
                ->set_help_text(__('If the selected Payment Type is <strong>NOT marked as Payable</strong>, the reservation will be confirmed automatically.<br/>Otherwise, it stays in <strong>Need confirmation</strong> until confirmed manually.', 'bookiflex')),
            Field::make('checkbox', SettingsManager::AUTO_CONFIRMATION_AFTER_PAYMENT_IS_PAID,
                __('Auto Confirmation After Payment is Paid', 'bookiflex'))
                ->set_default_value(true)
                ->set_help_text(__('If the reservation requires a payment and it is successfully paid (either automatically or manually marked as paid), the reservation will be confirmed automatically.<br/>Otherwise, it remains in <strong>Need confirmation</strong> status.', 'bookiflex')),
        ];
    }

    /**
     * Contact settings fields factory
     */
    public function companySettingsFactory(): callable
    {
        return fn () => [
            Field::make('separator', 'bflex__property_information__separator',
                __('Company information', 'bookiflex')),
            SectionNotice::make(
                'bflex__property_information__description',
                __('Legal and contact details of the company operating the properties. Used in booking confirmations, invoices, and guest communication.', 'bookiflex'),
            ),
            Field::make('text', SettingsManager::NAME,
                __('Company name', 'bookiflex'))
                ->set_required()
                ->set_default_value(__('California Apartments', 'bookiflex'))
                ->set_help_text(__('Legal or trading name of your company.', 'bookiflex')),
            Field::make('text', SettingsManager::ADDRESS,
                __('Address', 'bookiflex'))
                ->set_required()
                ->set_default_value(__('California, Magic street', 'bookiflex'))
                ->set_help_text(__('Company office or registered address. Individual property addresses are set separately in property settings.', 'bookiflex')),
            Field::make('text', SettingsManager::PHONE,
                __('Phone Number', 'bookiflex'))
                ->set_default_value(__('+0 (222) 333-444-5', 'bookiflex'))
                ->set_attribute('type', 'tel')
                ->set_help_text(__('Company contact phone for general inquiries and guest support.', 'bookiflex')),
            Field::make('text', SettingsManager::EMAIL,
                __('Email', 'bookiflex'))
                ->set_required()
                ->set_default_value('info@bookiflex.com')
                ->set_attribute('type', 'email')
                ->set_help_text(__('Company contact email for general inquiries and guest support.', 'bookiflex')),
            Field::make('text', SettingsManager::LONGITUDE,
                __('Longitude', 'bookiflex'))
                ->set_default_value('')
                ->set_width(50)
                ->set_help_text(__('Geographic longitude of the company office. Used to display location on a map.', 'bookiflex')),
            Field::make('text', SettingsManager::LATITUDE,
                __('Latitude', 'bookiflex'))
                ->set_default_value('')
                ->set_width(50)
                ->set_help_text(__('Geographic latitude of the company office. Used to display location on a map.', 'bookiflex')),
        ];
    }

    /**
     * Rules settings fields factory
     */
    public function rulesSettingsFactory(): callable
    {
        return fn () => [
            Field::make('separator', 'bflex__policy__separator',
                __('Rules of living', 'bookiflex')),
            SectionNotice::make(
                'bflex__rules__description',
                sprintf('%s <strong>%s</strong>',
                    __('List the house rules guests must be aware of before completing their booking. Each rule is displayed as a separate item —', 'bookiflex'),
                    __('no checkbox, informational only.', 'bookiflex'),
                ),
                'https://bookiflex.com/support/knowledge-base/house-rules/?utm_source=plugin&utm_medium=rules_of_living&utm_campaign=documentation',
            ),
            Field::make('complex', SettingsManager::RULES_OF_LIVING, '')
                ->set_autoload(true)
                ->add_fields([
                    Field::make('text', 'text',
                        __('Rule', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_required(),
                ])
                ->setup_labels([
                    'plural_name'   => __('rules', 'bookiflex'),
                    'singular_name' => __('rule', 'bookiflex'),
                ])
                ->set_header_template("
                        <% if (text) { %>
                            <%- text %>
                        <% } %>
                    ")
                ->set_collapsed(true)
                ->set_max(10),
            Field::make('separator', 'bflex__agreements__separator',
                __('Agreements', 'bookiflex')),
            SectionNotice::make(
                'bflex__agreements__description',
                __('Legal or formal agreements that guests must accept before booking. Each agreement is shown as a checkbox on the final booking step and included in the confirmation email.', 'bookiflex'),
                'https://bookiflex.com/support/knowledge-base/agreements/?utm_source=plugin&utm_medium=agreements&utm_campaign=documentation',
            ),
            Field::make('complex', SettingsManager::AGREEMENTS, '')
                ->set_autoload(true)
                ->add_fields([
                    Field::make('text', 'name',
                        _x('Name', 'name of the agreement', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_required()
                        ->set_help_text(__('Internal name for managing the agreement. Not visible to the guest.', 'bookiflex')),
                    Field::make('text', 'url',
                        __('Url', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_required()
                        ->set_width(50)
                        ->set_attribute('type', 'url')
                        ->set_help_text(__('Link to the full agreement text (e.g., Terms & Conditions, Privacy Policy).', 'bookiflex')),
                    Field::make('text', 'anchor',
                        __('Anchor', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_required()
                        ->set_width(50)
                        ->set_help_text(__('Anchor', 'bookiflex')),
                    Field::make('checkbox', 'combined',
                        __('Combined', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_help_text(__('If enabled, this agreement <strong>will be grouped</strong> with others marked as "Combined" and shown with a single checkbox.', 'bookiflex')),
                    Field::make('checkbox', 'required',
                        __('Required', 'bookiflex'))
                        ->set_autoload(true)
                        ->set_help_text(__('If enabled, the guest <strong>must accept</strong> this agreement to complete the booking.', 'bookiflex')),
                ])
                ->setup_labels([
                    'plural_name'   => __('agreements', 'bookiflex'),
                    'singular_name' => __('agreement', 'bookiflex'),
                ])
                ->set_header_template("
                        <% if (name) { %>
                            <%- name %>
                        <% } %>
                    ")
                ->set_collapsed(true)
                ->set_max(10),
        ];
    }

    /**
     * Magic button settings fields factory
     */
    public function magicButtonFactory(): callable
    {
        return fn() => [
            Field::make('separator', 'bflex__widget_button__separator',
                __('Magic Button', 'bookiflex')),
            SectionNotice::make(
                'bflex__widget_button__description',
                __('This section allows you to enable a floating "Magic Button" on all pages of your site. When clicked, it opens a booking widget in a modal window, allowing visitors to quickly check availability and make a reservation — just like in modern SaaS platforms.', 'bookiflex'),
            ),

            Field::make('checkbox', SettingsManager::BOOKING_BUTTON_ACTIVE,
                __('Enabled', 'bookiflex'))
                ->set_autoload(true)
                ->set_help_text(__('Toggle to show or hide the Magic Button across the site.', 'bookiflex')),
            Field::make('text', SettingsManager::BOOKING_BUTTON_TEXT,
                __('Button Text', 'bookiflex'))
                ->set_width(50)
                ->set_autoload(true)
                ->set_default_value(__('Book Now', 'bookiflex'))
                ->set_attribute('maxLength', '30')
                ->set_help_text(__('Text that appears on the button (e.g., "Book Now", "Check Availability").', 'bookiflex')),
            Field::make('select', SettingsManager::BOOKING_BUTTON_POSITION,
                __('Position', 'bookiflex'))
                ->set_width(50)
                ->set_autoload(true)
                ->set_options([
                    'bottom-left' => __('Bottom left', 'bookiflex'),
                    'bottom-right' => __('Bottom right', 'bookiflex'),
                    'bottom-center' => __('Bottom center', 'bookiflex'),
                ])
                ->set_help_text(__('Select where to place the button on the screen.', 'bookiflex')),
            Field::make('color', SettingsManager::BOOKING_BUTTON_COLOR,
                __('Color', 'bookiflex'))
                ->set_autoload(true)
                ->set_default_value('#007bff')
                ->set_palette(['#007bff', '#28a745', '#dc3545', '#ffc107'])
                ->set_help_text(__('Choose a background color for the button to match your site\'s branding.', 'bookiflex')),
            Field::make('checkbox', SettingsManager::BOOKING_BUTTON_PULSE,
                __('Pulse', 'bookiflex'))
                ->set_autoload(true)
                ->set_default_value(true)
                ->set_help_text(__('Adds a subtle pulsing animation to draw attention to the button. Ideal for increasing conversions.', 'bookiflex')),
        ];
    }

    /**
     * Widget appearance settings fields factory
     */
    public function widgetAppearanceFactory(): callable
    {
        return fn () => [
            Field::make('separator', 'bflex__widget_appearance__separator',
                __('Widget Appearance', 'bookiflex')),
            SectionNotice::make(
                'bflex__widget_appearance__description',
                __('Paste CSS custom properties to customize the booking widget colors, fonts, and shape. Example: <code>--bflex-primary: #007bff; --bflex-surface: #fafaf7;</code>', 'bookiflex'),
                'https://bookiflex.com/support/knowledge-base/widget-theming/?utm_source=plugin&utm_medium=widget_appearance&utm_campaign=documentation',
            ),
            Field::make('textarea', SettingsManager::WIDGET_CSS_TOKENS,
                __('CSS Tokens', 'bookiflex'))
                ->set_rows(10)
                ->set_help_text(__('CSS custom properties applied globally to the booking widget. Leave empty to use the default theme.', 'bookiflex')),
        ];
    }

    /**
     * Bank account settings fields factory
     */
    public function bankAccountFactory(): callable
    {
        return fn () => [
            Field::make('separator', 'bflex__payment__separator',
                __('Bank account', 'bookiflex')),
            SectionNotice::make(
                'bflex__payment__description',
                __('Can be used for display in the interface and sending by email if the Payment type "Guest pays to your bank account" is selected.', 'bookiflex'),
                'https://bookiflex.com/support/knowledge-base/bank-account/?utm_source=plugin&utm_medium=bank_account&utm_campaign=documentation',
            ),
            Field::make('rich_text', SettingsManager::BANK_ACCOUNT, '')
                ->set_autoload(false),
        ];
    }
}
