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

declare(strict_types=1);

namespace BookiFlex\Plugin\Admin\CPT;

use BookiFlex\Core\Admin\CPT\AccommodationType as BaseCPT;
use BookiFlex\Core\Admin\CPT\Event\AccommodationTypeGuestsBedFieldsBuilding;
use BookiFlex\Core\Admin\Field\SectionNotice;
use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Core\Model\AccommodationType\BookingUnitTypeInterface;
use BookiFlex\Core\Util\ProFeature;
use Carbon_Fields\Container;
use Carbon_Fields\Field;

defined( 'ABSPATH' ) || exit;

class AccommodationType extends BaseCPT
{
    public function register(PluginInterface $plugin): void
    {
        parent::register($plugin);
        // Re-register at priority 20 so carbon_get_theme_option() can find fields
        // registered by SettingsManager at the default priority 10.
        remove_action('carbon_fields_register_fields', [$this, 'registerMetaBoxes'], 5);
        $this->plugin->addAction('carbon_fields_register_fields', [$this, 'registerMetaBoxes'], 20);
        $this->customizeMenuOrder(
            __('Display order', 'bookiflex'),
            __('Controls the display order of this rental unit on the booking widget. Lower numbers appear first.', 'bookiflex')
        );
        $this->customizeExcerpt(
            __('Description', 'bookiflex'),
            __('A brief description of this unit. This text may be shown to guests during the booking process.', 'bookiflex')
        );
    }

    public function registerMetaBoxes(): void
    {
        $overviewFields = [
            SectionNotice::make(
                'at_overview_html',
                __( 'Enter the basic details of your rental unit — location, size, and key amenities. This information helps guests understand the property before making a reservation.', 'bookiflex' ),
                'https://bookiflex.com/support/knowledge-base/creating-a-property/?utm_source=plugin&utm_medium=accommodation_type&utm_campaign=documentation#overview',
            ),
            Field::make('text', self::FIELD_ADDRESS, __('Address', 'bookiflex'))
                ->set_required()
                ->set_help_text(__('The full address of the property.', 'bookiflex')),
            Field::make('text', self::FIELD_LIVING_SPACE, __('Living space', 'bookiflex'))
                ->set_width(33)
                ->set_attribute('placeholder', __('e.g. 30 m², 250 ft², 45', 'bookiflex'))
                ->help_text(__('Specify the total living area of the rental unit (in square meters, square feet, or any unit you prefer). This information is often displayed on the unit page.', 'bookiflex')),
	        Field::make('text', self::FIELD_ROOMS_COUNT, __('Number of rooms', 'bookiflex'))
	             ->set_width(33)
	             ->set_attribute('type', 'number')
	             ->set_attribute('min', '1')
	             ->set_attribute('placeholder', __('e.g. 3', 'bookiflex'))
	             ->help_text(__('Total number of separate rooms in this rental unit (bedrooms, living room, kitchen, etc.).', 'bookiflex')),
	        Field::make('textarea', self::FIELD_KEY_AMENITIES, __('Key amenities', 'bookiflex'))
                ->set_rows(2)
                ->help_text(__('List the top 5–7 features of this rental unit, separated by commas. These will appear in previews and highlights. Example: "Sea view, Balcony, Kitchen, Free Wi-Fi, Parking"', 'bookiflex')),
	        Field::make('hidden', self::FIELD_ACCOMMODATION_CATEGORY, '')
	             ->set_default_value(BookingUnitTypeInterface::RENTAL_UNIT),
	        Field::make('hidden', self::FIELD_ACCOMMODATION_AVAILABLE_UNITS, '')
	             ->set_default_value(1),
        ];

        $guestsBedFields = [
            SectionNotice::make(
                'at_guests_bed_html',
                __( 'Configure the sleeping capacity and occupancy options for this rental unit. Each selected occupancy level can have its own price in the rate plan.', 'bookiflex' ),
                'https://bookiflex.com/support/knowledge-base/creating-a-property/?utm_source=plugin&utm_medium=accommodation_type&utm_campaign=documentation#guests-and-beds',
            ),
            Field::make('separator', 'bflex_main_placement_separator', __('Main placements', 'bookiflex')),

            Field::make('select', self::FIELD_MAIN_SLEEPING_CAPACITY, __('Main sleeping capacity', 'bookiflex'))
                ->set_width(50)
                ->set_options(array_combine(range(1, 10), range(1, 10)))
                ->set_default_value(2)
                ->help_text(__('Enter the total number of main sleeping places (e.g., 1 double bed = 2 places).', 'bookiflex')),

            Field::make('set', self::FIELD_MAIN_SLEEPING_ALLOWED_OCCUPANCY, __('Allowed occupancy', 'bookiflex'))
                ->set_width(50)
                ->set_options(array_combine(range(1, 10), range(1, 10)))
                ->help_text(__('Select how many guests can stay in this accommodation. Each selected option can have its own price. <strong>Only selected occupancy options will be available for booking and pricing.</strong>', 'bookiflex')),
        ];

        $event = new AccommodationTypeGuestsBedFieldsBuilding($guestsBedFields);
        $this->plugin->getEventDispatcher()->dispatch($event);
        $guestsBedFields = $event->fields;

        if (!$this->plugin->fs()->can_use_premium_code()) {
            $guestsBedFields[] = ProFeature::notice(
                'pro_notice_occupancy',
                __('Add <strong>extra beds for an additional fee</strong> and configure <strong>special child rates</strong>. Make your pricing flexible and guest-friendly.', 'bookiflex')
            );
        }

        Container::make('post_meta', 'at_short_code', __('Short code', 'bookiflex'))
            ->where('post_type', '=', self::POST_TYPE)
            ->set_context('side')
            ->add_fields([
                Field::make('text', self::FIELD_SHORT_CODE, '')
                    ->set_attribute('maxLength', '10')
                    ->set_attribute('readOnly', 'true')
                    ->set_attribute('placeholder', __('e.g. STD', 'bookiflex'))
                    ->help_text(__('A short identifier for this rental unit (generated automatically). For example: APT for Apartment, CAB for Cabin. This code may be used internally or in reports.', 'bookiflex')),
            ]);

        Container::make('post_meta', 'at_configuration', __('Configuration', 'bookiflex'))
            ->where('post_type', '=', self::POST_TYPE)
            ->set_layout('tabbed-vertical')
            ->add_tab(__('Overview', 'bookiflex'), $overviewFields)
            ->add_tab(__('Guests & beds', 'bookiflex'), $guestsBedFields)
            ->add_tab(__('Email information', 'bookiflex'), [
                SectionNotice::make(
                    'at_email_info_html',
                    __( 'Add contact details and check-in instructions sent to guests after booking. Map coordinates let you display an exact location on the confirmation.', 'bookiflex' ),
                    'https://bookiflex.com/support/knowledge-base/creating-a-property/?utm_source=plugin&utm_medium=accommodation_type&utm_campaign=documentation#email-information',
                ),
                Field::make('text', self::FIELD_PHONE, __('Phone Number', 'bookiflex'))
	                ->set_width(50)
                    ->set_attribute('type', 'tel')
                    ->set_help_text(__('For guest support and communication (if not specified, the default one will be used).', 'bookiflex')),
                Field::make('text', self::FIELD_EMAIL, __('Email', 'bookiflex'))
	                ->set_width(50)
                    ->set_attribute('type', 'email')
                    ->set_help_text(__('For guest support and communication (if not specified, the default one will be used).', 'bookiflex')),
                Field::make('textarea', self::FIELD_CHECKIN_INSTRUCTIONS, __('Check-in instructions', 'bookiflex'))
                    ->set_rows(4)
                    ->help_text(__('Important information sent to guests after booking confirmation. Include details like door codes, parking instructions, key pickup location, or check-in procedures specific to this rental unit.', 'bookiflex')),
                Field::make('separator', 'bflex_unit_address_separator', __('Map coordinates', 'bookiflex')),
                Field::make('text', self::FIELD_LONGITUDE, __('Longitude', 'bookiflex'))
                    ->set_width(50)
                    ->set_help_text(__('Used to display the property on a map.', 'bookiflex')),
                Field::make('text', self::FIELD_LATITUDE, __('Latitude', 'bookiflex'))
                    ->set_width(50)
                    ->set_help_text(__('Used to display the property on a map.', 'bookiflex')),
            ]);

        Container::make('post_meta', __('Gallery', 'bookiflex'))
            ->where('post_type', '=', self::POST_TYPE)
            ->add_fields([
                Field::make('media_gallery', self::FIELD_ACCOMMODATION_GALLERY, __('Gallery', 'bookiflex')),
            ]);
    }

}
