
{{-- View Constants --}}
<script>
  // Window Constnats
    @if ($has_otas)
        window.external_rooms = @json(
            $activated_otas->mapWithKeys(function ($ota) {
                return [
                    $ota->sample_name => $ota->external_rooms,
                ];
            })
        ); // Extract each Connection's Room Rates
    @endif

  // Render Functions
    const renderExpressPackageBlock = (duration, can_be_deleted = true) => `
        <div class="mb-2 d-flex justify-content-start align-items-center" id="express_package_${duration}_h_block" data-package="${duration}">
            {{-- Package Reference --}}
            <p class="mb-0 mr-2 fw-semi-bold" style="font-size: 1.1rem">
                &bull; <span class="harsi-color">
                    {{ __('entity_forms')['room_type']['package_prefix'] }}
                </span> ${duration} H
            </p>

            {{-- Delete Row Button --}}
            ${can_be_deleted ? `
                <button type="button" class="btn btn-outline-danger" style="transform: scale(0.85);" onclick="removeExpressPackage(this)">
                    <i class="fas fa-trash"></i>
                </button>
            ` : ""}

            {{-- Package Hour Reference --}}
            <input type="hidden" name="express_package[]" id="express_package_${duration}_h" value="${duration}">
        </div>
    `;

    const renderExpressSeasonBlock = (seasonId, duration, value) => `
        <div class="my-1 form-group d-flex align-items-center" data-package="${duration}">
            <label for="season_${seasonId}_express_${duration}" class="py-2 mb-0 text-center control-label w-25">
                ${duration} H
            </label>
            <input type="number" name="season_${seasonId}_express[]" id="season_${seasonId}_express_${duration}" required
                class="form-control" placeholder="0.00" value="${value}"
                onfocus="this.dataset.previous = this.value"
                step="0.01" min="0" onchange="formatDecimal(this); ensureSubInheritedPricing(${seasonId}, ${duration}, this)"
            />
        </div>
    `;

    const renderExpressPaxSeasonBlock = (seasonId, duration, px, value) => `
        <div class="px-2 mb-3" data-package="${duration}">
            <p class="mb-2 mr-2 fw-semi-bold" style="font-size: 1.1rem">
                {{ __('entity_forms')['room_type']['package_prefix'] }}
                <span class="harsi-color">${duration} H</span>
            </p>

            <div class="pl-2" id="season_${ seasonId }_express_${duration}_px_breakdown">
                ${renderExpressPaxPricing(seasonId, duration, px, value)}
            </div>
        </div>
    `;

    const renderExpressPaxPricing = (seasonId, duration, px, value) => `
        <div class="my-1 form-group d-flex align-items-center" data-express-px="${px}">
            <label for="season_${seasonId}_express_${duration}_pax_${px}" class="py-2 mb-0 text-center control-label w-25">
                ${px} px
            </label>
            <input type="number" name="season_${seasonId}_express_${duration}_pax[]" id="season_${seasonId}_express_${duration}_pax_${px}" required
                class="form-control" placeholder="0.00" step="0.01" min="0" value="${value}"
                onchange="formatDecimal(this)"
            />
        </div>
    `;

    const renderPaxPricingBlock = (seasonId, px, value) => `
        <div class="my-1 form-group d-flex align-items-center" data-px="${px}">
            <label for="season_${seasonId}_px_${px}" class="px-3 py-2 mb-0 text-center control-label w-25">
                ${px} px
            </label>
            <input type="number" name="season_${seasonId}_pxs[]" id="season_${seasonId}_px_${px}" required class="form-control"
                placeholder="${currencyPlaceHolder()}" step="0.01" min="0" value="${value}"
                onchange="formatDecimal(this)"
                />
        </div>
    `;

  // Default Structures
    const basic_default_season = `
        <div class="pt-2 mb-4 form-group row">
            <label for="season_1_price" class="text-center control-label col-5">{{ __('seeders')['seasons']['default_season'] }}</label>
            <div class="col-7">
                <input type="number" name="seasons_prices[]" id="season_1_price" required class="form-control"
                    placeholder="${currencyPlaceHolder()}" step="0.01" min="0" value="0.00"
                    onfocus="this.dataset.previous = this.value"
                    onchange="formatDecimal(this); ensureInheritedPricing(1, this)"
                />
            </div>
        </div>
    `;

    const basic_pax_pricing = `
        <div class="px-3 mb-3">
            <p class="pl-1 season_subtitle ">{{ __('seeders')['seasons']['default_season'] }}</p>
            <div id="season_1_px_breakdown" class="pl-4">
                ${renderPaxPricingBlock(1,1,"")}
            </div>
        </div>
    `;

    const basic_express_packages = renderExpressPackageBlock(1, false);

    const basic_express_pricing = `
        <div class="mb-3">
            <p class="season_subtitle">{{ __('seeders')['seasons']['default_season'] }}</p>
            <div id="season_1_express_breakdown" class="pl-2">
                ${renderExpressSeasonBlock(1, 1, "0.00")}
            </div>
        </div>
    `;

    const basic_pax_express_pricing = `
        <div class="mt-3 card-legends standard-rounded">
            <h3 class="pb-2 mb-3 text-center subtitle_form harsi-color pale-item border-bottom">
                {{ __('seeders')['seasons']['default_season'] }}
            </h3>

            <div id="season_1_pax_express_pricing_breakdown">
                ${renderExpressPaxSeasonBlock(1, 1, 1, "0.00")}
            </div>
        </div>
    `;
</script>

{{-- CRUD Interactions --}}
<script>
    $(document).ready(function() {
      // For  Create
        $('#create_record').click(function() {
            // Title
            @if ($has_otas)
                $('.modal_subtitle').text("{{ __('entity_forms')['common']['modal_title'] }}");
                $('.modal_title').text("{{ __('entities')['hotel']['room_type'] }}");
            @else
                $('.modal_title').text("{{ __('entity_forms')['common']['modal_title'] }}");
                $('.modal_subtitle').text("- {{ __('entities')['hotel']['room_type'] }} -");
            @endif

            // Tabs
            $('#tab_content').hide();
            $('#local_tab, #seasons_tab').tab('show');

            // Buttons
            $('#action_button').val("{{ __('common_actions')['add'] }}");

            // Modal Structure
            $('#tariffs, #pax_pricing_breakdown').empty();
            $('#room_type_form')[0].reset();
            $('#formModal').modal('show');

            // Dynamic Structures
            $(`#using_own_seasons`).prop('checked', false);

            $('#minimum_express_stay_block, #express_checkout_penalty_block, #express_pricing_tab_block, #pax_express_pricing_breakdown').hide();
            $('#pax_pricing_breakdown').show();

            $('#tariffs').html(basic_default_season);
            $('#pax_pricing_breakdown').html(basic_pax_pricing);
            resetExpressPricing();

            $('#pax_room_limit').val(1).trigger('change');
            $('#minimum_express_stay').val(1).trigger('change');
        });

      // For Edit
        $(document).on('click', '.edit', function() {
            let id = $(this).attr('id');
            $.ajax({
                url: `/room-types/${id}/edit`,
                dataType: "json",
                success: async function(html) {
                    $('#tariffs, #pax_pricing_breakdown').empty();

                    //* Control Data
                    const rt_data = html.data;
                    const rt_seasons = rt_data.tr_seasons;

                    //* Seed Form
                    $('#hidden_id, #hidden_type_id').val(rt_data.id);

                    $('#tr_name').val(rt_data.tr_name);
                    $('#pax_room_limit').val(rt_data.pax_room_limit);
                    $('#additional_pax_charge').val(rt_data.additional_pax_charge);
                    $('#minimum_express_stay').val(rt_data.minimum_express_stay);
                    $('#express_checkout_penalty').val(rt_data.express_checkout_penalty);

                    $(`#using_own_seasons`).prop('checked', !rt_seasons.using_default);
                    $(`#use_for_express`).prop('checked', rt_data.is_express_type);

                      // Dynamic Structures
                        $('#minimum_express_stay_block, #express_checkout_penalty_block, #express_pricing_tab_block, #pax_express_pricing_breakdown').toggle(rt_data.is_express_type);
                        $('#pax_pricing_breakdown').toggle(!rt_data.is_express_type);
                        $('#express_packages_breakdown').empty();

                      // Draw Season Configuration
                        globalTariffs(!rt_seasons.using_default, {minimum_stay: rt_data.minimum_express_stay});
                        seedDynamicEdits(rt_data);

                    //* Modify Modal
                    $('#tab_content').show();
                    $('#local_tab, #seasons_tab').tab('show');

                    @if ($has_otas)
                        //- Visual Changes
                        $('.modal_title').text(`{{ __('entities')['hotel']['room_type'] }} #${rt_data.id}`);
                        $('.modal_subtitle').text("{{ __('entity_forms')['common']['modal_title_2'] }}");

                        //- Fields Seeder
                        $(`input[id$="_room_type_reference"]`).val(rt_data.tr_name);
                        $(`select[id^="online_type_"]`).val("none").removeClass('error');

                        // Get AvailableRooms
                        await apiGet("{{ route('api.otas.availableExternalIds') }}", function (availability_data) {
                            // Draw AvailableRoom Options
                            Object.entries(availability_data ?? {}).forEach(([ota, available_rooms]) => {
                                let options = `<option value="none" selected>{{ __('neutral_words')['none'] }}</option>`;

                                available_rooms.forEach(ext_room => {
                                    const room_name = window.external_rooms[ota][ext_room].name;
                                    options += `<option value="${ext_room}">${room_name}</option>`;
                                });

                                $(`#online_type_${ota}`).html(options);
                            });

                            // ExternalRooms Select
                            const external_identifications = rt_data.external_identifications ?? {};
                            Object.entries(external_identifications).forEach(([ota_name, external_room]) => {
                                $(`#online_type_${ota_name}`).val(external_room ?? "none").trigger('change');
                            });

                        }, { type_to_exclude: rt_data.id });

                        // Extract Available Local Rooms
                        const linked_rooms = rt_data.rooms ?? [];
                        Object.entries(window.external_rooms).forEach(([ota_name]) => {
                            // Control Data
                            let available_summary = linked_rooms
                                .filter(room => (room.available_on_otas ?? []).includes(ota_name))
                                .map(room => room.room_name);

                            const available_quantity = available_summary.length;

                            // Seed Data
                            if (!available_quantity)
                                available_summary = ["{{ __('neutral_words')['none'] }}"];

                            $(`#availability_quantity_on_${ota_name}`).text(available_quantity);
                            $(`#availability_breakdown_on_${ota_name}`).text(`(${available_summary.join(", ")})`);
                        });

                    @else
                        // Visual Changes
                        $('.modal_title').text("{{ __('entity_forms')['common']['modal_title_2'] }}");
                        $('.modal_subtitle').text(`{{ __('entities')['hotel']['room_type'] }} #${rt_data.id}`);
                    @endif

                    $('#action_button').val("{{ __('common_actions')['update'] }}");
                    $('#formModal').modal('show');
                }

            })
        });

      // For Delete
        $(document).on('click', '.delete', function() {
            var id = $(this).attr('id');

            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['confirm_deletion'] }}",

                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['confirm_deletion'] }}",
                confirmButtonColor: `#0d6889`,

                showCancelButton: true,
                cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
                cancelButtonColor: `#c82333`
            }).then((result) => {
                if (result.value) {
                    $.ajax({
                        url: `/room-types/${id}/destroy`,
                        success:function(data) {
                            setTimeout(function(){
                                launchSwalToast(
                                    'success',
                                    "{{ __('common_responses_and_messages')['deleted_successfully'] }}"
                                );

                                $('#rooms_table').DataTable().ajax.reload(null, false);
                            }, 200);
                        }
                    });
                }
            });
        });

      // On Basic Submit
        $('#room_type_form').on('submit', function(event) {
            event.preventDefault();
                if (!validateRoomTypeForm()) return;

            const is_editing = $('#action_button').val() === translateAndReplace('common_actions.update');

            if (!is_editing) {
                $.ajax({
                    url: "{{ route('room-types.store') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function(data) {
                        // Messages
                        launchSwalToast(
                            'success',
                            "{{ __('common_responses_and_messages')['created_successfully'] }}",
                        );

                        // Visual Render
                        $('#room_type_form')[0].reset();
                        $('#formModal').modal('hide');
                        $('#tariffs, #pax_pricing_breakdown').empty();

                        // Reload Table
                        $('#rooms_table').DataTable().ajax.reload(null, false);
                    }
                })
            } else {
                $.ajax({
                    url: "{{ route('room-types.update') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function(data) {
                        // Messages
                        launchSwalToast(
                            'success',
                            "{{ __('common_responses_and_messages')['updated_successfully'] }}",
                        );

                        // Visual Render
                        $('#room_type_form')[0].reset();
                        $('#formModal').modal('hide');
                        $('#tariffs, #pax_pricing_breakdown').empty();

                        // Reload Table
                        $('#rooms_table').DataTable().ajax.reload(null, false);
                    }
                });
            }
        });

        @if ($has_otas)
            // On Submit Channels Configuration
            $('#channels_form').on('submit', function(event) {
                event.preventDefault();

                // Validate echa OTA Tab fields
                const form = this;
                const tabsAreValid = validateChannelsForm(form);
                    if (!tabsAreValid) return;

                // Send Request
                $.ajax({
                    url: "{{ route('otas.configureRoomType') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",

                    success: function(data) {
                        // Clean Errors
                        $(`select[id^="online_type_"]`).removeClass('error');

                        // Show Success Message
                        launchSwalToast(
                            'success',
                            "{{ __('common_responses_and_messages')['updating_data'] }}"
                        );
                    },

                    error: function(error) {
                        // Extract Erro Data
                        const error_data = error.responseJSON;
                        const {ota, conflict_room_id} = error_data;
                        const external_room = window.external_rooms[ota][conflict_room_id].name

                        // Show Tab && Input Errors
                        $(`#tab_OTA_${ota} a.nav-link`).tab('show');
                        $(`#online_type_${ota}`).addClass('error');

                        // Launch Error Message
                        Swal.fire({
                            type: 'error',
                            title: "{{ __('common_responses_and_messages')['rejected_action'] }}",
                            html: translateAndReplace(
                                `entity_forms.otas_connection.room_type_addon.warnings.type_already_assigned`,
                                { external_room, ota }
                            ),
                            confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
                        });
                    }
                });
            });
        @endif

      // On Close Modal
        $('#formModal').on('hide.bs.modal', function () {
            document.activeElement.blur();
        });

      // On Change Main Tabs
        $('#tab_content a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            const targetTab = $(e.target).attr('href');

            if (targetTab === "#channels") {
                $('#modal-dialog').addClass('modal-lg');
            } else {
                $('#modal-dialog').removeClass('modal-lg');
            }
        });

      // On Change Secondary Tabs
        $('#season_tab_content a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            const targetTab = $(e.target).attr('href');

            if (targetTab === "#express_pricing") {
                $('#modal-dialog').css("max-width", "46%");
            } else {
                $('#modal-dialog').css("max-width", "40%");
            }
        });
    });
</script>

{{-- Sample RoomTypes Behavior Functions --}}
<script>
  //* Toggle Interactions
    function globalTariffs(is_checked, {minimum_stay = null} = {}) {
      // Reset Structures
        $('#tariffs, #pax_pricing_breakdown, #express_pricing_breakdown, #pax_express_pricing_breakdown').empty();

      // Control Data
        const minimum_express_stay = parseInt($('#minimum_express_stay').val());
        let express_packages = [...new Set(
            $('#express_pricing').find('[data-package]').map((_,el)=>$(el).data('package')).get()
        )];
        express_packages = express_packages.filter(p => p !== minimum_express_stay);

      // Render structures
        if(is_checked){ // Per Stored Season
            apiGet("{{ route('api.season.ownSeasons') }}", function (data) {
              // Render Structures per Season
                if(data.length > 0){
                  // Render Season Structures
                    data.forEach(season => {
                      // Season Rates
                        let rate_structure = `
                            <div class="pt-2 mb-4 form-group row">
                                <label for="season_${season.id}_price" class="text-center control-label col-5"> ${ season.s_name } </label>
                                <div class="col-7">
                                    <input type="number" name="seasons_prices[]" id="season_${season.id}_price" required class="form-control"
                                        placeholder="${currencyPlaceHolder()}" step="0.01" min="0"
                                        onfocus="this.dataset.previous = this.value"
                                        onchange="formatDecimal(this); ensureInheritedPricing(${ season.id }, this)"
                                    />
                                </div>
                            </div>
                        `;
                        $('#tariffs').append(rate_structure);

                      // Express Rates
                        // Express Packages
                        let express_pricing_structure = `
                            <div class="mb-3">
                                <p class="season_subtitle">${ season.s_name }</p>
                                <div id="season_${ season.id }_express_breakdown" class="pl-2">
                                    ${renderExpressSeasonBlock(season.id, minimum_express_stay, "")}
                                </div>
                            </div>
                        `;
                        $('#express_pricing_breakdown').append(express_pricing_structure);

                        // Express Pax Pricing
                        let pax_express_pricing_structure = `
                            <div class="mt-3 card-legends standard-rounded">
                                <h3 class="pb-2 mb-3 text-center subtitle_form harsi-color pale-item border-bottom">
                                    ${ season.s_name }
                                </h3>

                                <div id="season_${ season.id }_pax_express_pricing_breakdown">
                                    ${renderExpressPaxSeasonBlock(season.id, minimum_express_stay, 1, "")}
                                </div>
                            </div>
                        `;
                        $('#pax_express_pricing_breakdown').append(pax_express_pricing_structure);

                        // Load Packages
                        express_packages.forEach(package_duration => {
                            $(`#season_${season.id}_express_breakdown`).append(renderExpressSeasonBlock(season.id, package_duration, ""));
                            $(`#season_${ season.id }_pax_express_pricing_breakdown`).append(renderExpressPaxSeasonBlock(season.id, package_duration, 1, ""));
                        });

                      // Pax Rates
                        let pax_pricing_structure = `
                            <div class="px-3 mb-3">
                                <p class="pl-1 season_subtitle ">${ season.s_name }</p>
                                <div id="season_${ season.id }_px_breakdown" class="pl-4">
                                    <div class="my-1 form-group d-flex align-items-center">
                                        <label for="season_${ season.id }_px_1" class="px-3 py-2 mb-0 text-center control-label w-25">
                                            1 px
                                        </label>
                                        <input type="number" name="season_${ season.id }_pxs[]" id="season_${ season.id }_px_1" required class="form-control"
                                            placeholder="${currencyPlaceHolder()}" step="0.01" min="0"
                                            onchange="formatDecimal(this)"
                                            />
                                    </div>
                                </div>
                            </div>
                        `;
                        $('#pax_pricing_breakdown').append(pax_pricing_structure);
                    });
                } else {
                    let html_structure = `<p class="pt-3 mb-4 text-center">{{ __('entity_forms')['room_type']['no_seasons'] }}</p>`;

                    $('#tariffs').append(html_structure);
                    $('#pax_pricing_breakdown').append(html_structure);
                    $('#express_pricing_breakdown').append(html_structure);
                    $('#pax_express_pricing_breakdown').append(html_structure);
                }

              // Triggers
                renderPaxPricing();
            });
        } else { // As Default
          // Default season rates
            $('#tariffs').append(basic_default_season);

          // Default express pricing
            if(minimum_stay) {
                $('#express_pricing_breakdown').html(`
                    <div class="mb-3">
                        <p class="season_subtitle">{{ __('seeders')['seasons']['default_season'] }}</p>
                        <div id="season_1_express_breakdown" class="pl-2">
                            ${renderExpressSeasonBlock(1, minimum_stay, "0.00")}
                        </div>
                    </div>
                `);
                $('#pax_express_pricing_breakdown').html(`
                    <div class="mt-3 card-legends standard-rounded">
                        <h3 class="pb-2 mb-3 text-center subtitle_form harsi-color pale-item border-bottom">
                            {{ __('seeders')['seasons']['default_season'] }}
                        </h3>

                        <div id="season_1_pax_express_pricing_breakdown">
                            ${renderExpressPaxSeasonBlock(1, minimum_stay, 1, "0.00")}
                        </div>
                    </div>
                `);
            } else {
                $('#express_pricing_breakdown').html(basic_express_pricing);
                $('#pax_express_pricing_breakdown').html(basic_pax_express_pricing);
            }

            express_packages.forEach(package_duration => {
                $(`#season_1_express_breakdown`).append(renderExpressSeasonBlock(1, package_duration, "0.00"));
                $(`#season_1_pax_express_pricing_breakdown`).append(renderExpressPaxSeasonBlock(1, package_duration, 1, ""));
            });

          // Default pax pricing
            $('#pax_pricing_breakdown').append(basic_pax_pricing);
            renderPaxPricing();
        }
    }

    async function seedDynamicEdits(room_type_data) {
      // Sample Controls
        const pax_limit = room_type_data.pax_room_limit;
        const minimum_express_stay = room_type_data.minimum_express_stay;

      // Structured Controls
        const rt_seasons = room_type_data.tr_seasons;
        const rt_pax_configuraron = room_type_data.tr_pax_seasons;
        const rt_express_configuraron = room_type_data.tr_express_seasons;

      // Seed Form
        if(rt_seasons.using_default){ // Seed with Default Config
            // Fill Global Rate
            $('#season_1_price').val((rt_seasons.default_season_price).toFixed(2));

            // Fill PAX rates
            for (let i = 0; i < pax_limit; i++) {
                let pax_quantity = i+1;
                let pax_quantity_data = rt_pax_configuraron.default_season_pax_pricing[i];
                let pricing = (pax_quantity_data && pax_quantity == pax_quantity_data.px_quantity)
                    ? pax_quantity_data.px_price
                    : 0.00;

                $(`#season_1_px_${pax_quantity}`).val((pricing).toFixed(2));
            }

            // Fill Express Pricing
            const express_packages = rt_express_configuraron.default_season_express_pricing ?? [];

            express_packages.forEach(pkg => {
                const duration = pkg.package_duration;
                const is_default_package = duration === minimum_express_stay;

                // Create package if missing
                if (!$(`input[name="express_package[]"][value="${duration}"]`).length) {
                    $('#express_packages_breakdown').append(renderExpressPackageBlock(duration, !is_default_package));

                    // Create pricing fields
                    if (!is_default_package) { // Avoid re-render default packages
                        $('#season_1_express_breakdown').append(renderExpressSeasonBlock(1, duration, "0.00"));
                        $('#season_1_pax_express_pricing_breakdown').append(renderExpressPaxSeasonBlock(1, duration, 1, "0.00"));
                    }
                }

                // Set package price
                $(`#season_1_express_${duration}`)
                    .val((pkg.package_price ?? 0).toFixed(2)).trigger('change');

                // Set express pax pricing
                renderPaxPricing();
                pkg.express_pax_pricing?.forEach(px => {
                    $(`#season_1_express_${duration}_pax_${px.px_quantity}`).val((px.px_price ?? 0).toFixed(2));
                });
            });

        } else{
            // Extract Own Season Configuration
            let other_seasons = rt_seasons.other_seasons;
            let pax_other_seasons = rt_pax_configuraron.other_seasons;
            let express_other_seasons = rt_express_configuraron.other_seasons;

            apiGet("{{ route('api.season.ownSeasons') }}", function (season_data) {
              // Remove deleted seasons from DB
                const season_names = season_data.map(season => season.s_name);
                other_seasons = other_seasons.filter(season => season_names.includes(season.season_name));
                pax_other_seasons = pax_other_seasons.filter(season => season_names.includes(season.season_name));
                express_other_seasons = express_other_seasons.filter(season => season_names.includes(season.season_name));

              // Remove known seasons by RoomType
                const other_season_names = other_seasons.map(season => season.season_name);
                season_data = season_data.filter(season => !other_season_names.includes(season.s_name));

              // Render known Seasons
                // Season Pricing
                other_seasons.forEach(season => {
                    $(`#season_${ season.season_id }_price`).val((season.season_price).toFixed(2));
                });

                // Pax Pricing
                pax_other_seasons.forEach(season => {
                    let season_pax_pricing = season.season_pax_pricing;

                    for (let i = 0; i < pax_limit; i++) {
                        let pax_quantity = i+1;
                        let pax_quantity_data = season_pax_pricing[i];
                        let pricing = (pax_quantity_data && pax_quantity == pax_quantity_data.px_quantity)
                            ? pax_quantity_data.px_price
                            : 0.00;

                        $(`#season_${ season.season_id }_px_${pax_quantity}`).val((pricing).toFixed(2));
                    }
                });

                // Express Pricing
                express_other_seasons.forEach(season => {
                    const season_id = season.season_id;

                    season.season_express_pricing.forEach(pkg => {
                        const duration = pkg.package_duration;
                        const is_default_package = duration === minimum_express_stay;

                        // Create package if missing
                        if (!$(`input[name="express_package[]"][value="${duration}"]`).length) {
                            $('#express_packages_breakdown').append(renderExpressPackageBlock(duration, !is_default_package));

                            // Create pricing fields for all seasons
                            $('[id^="season_"][id$="_express_breakdown"]').each(function(){
                                if (is_default_package) return; // Avoid re-render default packages

                                const sid = $(this).attr('id').match(/season_(\d+)_/)[1];
                                $(this).append(renderExpressSeasonBlock(sid, duration, "0.00"));
                            });

                            $('[id^="season_"][id$="_pax_express_pricing_breakdown"]').each(function(){
                                if (is_default_package) return; // Avoid re-render default packages

                                const sid = $(this).attr('id').match(/season_(\d+)_/)[1];
                                $(this).append(renderExpressPaxSeasonBlock(sid, duration, 1, "0.00"));
                            });
                        }

                        // Set package price
                        $(`#season_${season_id}_express_${duration}`)
                            .val((pkg.package_price ?? 0).toFixed(2)).trigger('change');

                        // Express Pax Pricing
                        renderPaxPricing();
                        pkg.express_pax_pricing?.forEach(px => {
                            $(`#season_${season_id}_express_${duration}_pax_${px.px_quantity}`)
                                .val((px.px_price ?? 0).toFixed(2));
                        });
                    });
                });

              // Render Unknown seasons
                season_data.forEach(season => {
                    $(`#season_${ season.id }_price`).val((0.00).toFixed(2));

                    for (let i = 0; i < pax_limit; i++){
                        let pax_quantity = i+1;
                        $(`#season_${ season.id }_px_${pax_quantity}`).val((0.00).toFixed(2));
                    }
                });
            });
        }
    }

  //* Form Validation
    function validateRoomTypeForm() {
      // Validate Name Section
        const {
            section_valid: name_block_valid,
            show_error_detected: show_name_error_detected,
            section_error_message: name_error_message
        } = sharedSectionValidator('general_data');
            if (!name_block_valid) {
                if (show_name_error_detected) showToast(name_error_message, "#C34808", "#78350F");
                return false;
            }

      // Validate Seasons Section
        const {
            section_valid: seasons_valid,
            show_error_detected: show_seasons_error_detected,
            section_error_message: seasons_error_message
        } = sharedSectionValidator('seasons');
            if (!seasons_valid) {
                if (show_seasons_error_detected) showToast(seasons_error_message, "#C34808", "#78350F");
                return false;
            }

      // Validate Express Pricing Section
        const {
            section_valid: express_valid,
            show_error_detected: show_express_error_detected,
            section_error_message: express_error_message
        } = sharedSectionValidator('express_pricing');
            if (!express_valid) {
                if (show_express_error_detected) showToast(express_error_message, "#C34808", "#78350F");
                return false;
            }

      // Validate PAX Section
        const {
            section_valid: pax_valid,
            show_error_detected: show_pax_error_detected,
            section_error_message: pax_error_message
        } = sharedSectionValidator('pax_pricing');
            if (!pax_valid) {
                if (show_pax_error_detected) showToast(pax_error_message, "#C34808", "#78350F");
                return false;
            }

        return true;
    }

  //* Express Hotel Functions
    // Functions
        function setTypeAsExpress({enable_section = false} = {}) {
          // Get Status
            const set_as_express = enable_section || $('#use_for_express').prop('checked');

          // Toggle Sections
            $('#minimum_express_stay_block, #express_checkout_penalty_block, #express_pricing_tab_block, #pax_express_pricing_breakdown').toggle(set_as_express);
            $('#seasons_tab').tab('show');

          // Affect Secondary Sections
            $('#pax_pricing_breakdown').toggle(!set_as_express);

          // Secondary Render
            resetExpressPricing();
            renderPaxPricing();
        }

        function syncDefaultExpressPricing() {
          //* Default Controls
            const $toggle_input = $("#minimum_express_stay");
            const previous_value = parseInt($toggle_input[0].dataset.previous);
            const minimum_express_stay = parseInt($toggle_input.val()) || 1;
                if (previous_value === minimum_express_stay) return;

            // Update Controls
            $toggle_input[0].dataset.previous = minimum_express_stay;

          //* Replace if package duration has been already defined (preserve values)
            if ($(`[data-package="${minimum_express_stay}"]`).length && previous_value) {
              // Preserve package data, and migrate to default package
                spreadExpressPricing(minimum_express_stay, previous_value,'[id$="_express_breakdown"]', 'input');
                spreadExpressPricing(minimum_express_stay, previous_value,'[id$="_pax_express_pricing_breakdown"]', 'input');

              // Remove package to avoid duplicated data
                $(`[data-package="${minimum_express_stay}"]`)
                    .not(`#express_package_${previous_value}_h_block`)
                    .remove();
            }

          //* Update Default Package
            // Update Package Reference
            const $default_package = $(`#express_package_${previous_value}_h_block`);
                $default_package.attr({"data-package": minimum_express_stay, "id": `express_package_${minimum_express_stay}_h_block`});
                $default_package.find("p").html(`&bull; <span class="harsi-color">{{ __('entity_forms')['room_type']['package_prefix'] }}</span> ${minimum_express_stay} H`);
                $default_package.find("input").attr("id", `express_package_${minimum_express_stay}_h`).val(minimum_express_stay);

            // Update Pricing Breakdown per Season
            $('[id$="_express_breakdown"]').find(`[data-package="${previous_value}"]`).each(function () {
              // Visual Controls
                const $package_block = $(this);
                const season_id = $package_block.closest('[id^="season_"]').attr('id').match(/season_(\d+)/)[1];
                const new_reference = `season_${season_id}_express_${minimum_express_stay}`;

              // Update packages identifier
                $package_block.attr("data-package", minimum_express_stay);
                $package_block.find("label")
                    .text(`${minimum_express_stay} H`).attr("for", new_reference);

              // Update Input ID
                $package_block.find("input").attr("id", new_reference);
            });

          //* Update Express Pax Pricing Structures
            $('[id$="_pax_express_pricing_breakdown"]').find(`[data-package="${previous_value}"]`).each(function () {
              // Visual Controls
                const $express_pax_block = $(this); // Package Group
                const season_id = $express_pax_block.closest('[id^="season_"]').attr('id').match(/season_(\d+)/)[1];
                const $express_pax_breakdown = $express_pax_block.find('[id$="_px_breakdown"]'); // Breakdown per Pax

              // Update Package Group
                $express_pax_block.attr("data-package", minimum_express_stay);
                $express_pax_block.find("p span").first().text(`${minimum_express_stay} H`);

              // Update Pax Breakdown
                $express_pax_breakdown.attr("id", `season_${season_id}_express_${minimum_express_stay}_px_breakdown`);
                $express_pax_breakdown.find("input").each(function () {
                    const px = $(this).closest('[data-express-px]').data('express-px');
                    const new_reference = `season_${season_id}_express_${minimum_express_stay}_pax_${px}`;

                    $(this).closest('.form-group').find('label').attr('for', new_reference);
                    $(this).attr({
                        name: `season_${season_id}_express_${minimum_express_stay}_pax[]`,
                        id: new_reference
                    });
                });
            });

          //* Remove records with minor values
            $('[data-package]').each(function () {
                const pkg = parseInt($(this).attr('data-package'));
                    if (pkg < minimum_express_stay) $(this).remove();
            });

          //* Rebuild Pax Pricing
            renderPaxPricing();
        }

        function spreadExpressPricing (
            minimum_express_stay, previous_value,   // Control Data
            container_selector, input_selector      // HTML Context
        ) {
            $(container_selector).each(function () {
              //* Default Controls
                const $container = $(this);
                const $existing = $container.find(`[data-package="${minimum_express_stay}"]`);
                const $previous = $container.find(`[data-package="${previous_value}"]`);
                    if (!$existing.length || !$previous.length) return;

              //* Migrate data to preserve to default input
                $existing.find(input_selector).each(function () {
                  // Control Data
                    const value = $(this).val();
                    const $px = $(this).closest('[data-express-px]');
                    const index = $px.length ? $px.data('express-px') : null;

                  // Sync Data
                    const $target = index !== null
                        ? $previous.find(`[data-express-px="${index}"] input`) // For Express Pax Pricing
                        : $previous.find("input"); // For Express Pricing

                    if ($target.length) $target.val(value);
                });
            });
        };

        async function addExpressPackage() {
          //  Extract Data
            const minimum_express_stay = parseInt($('#minimum_express_stay').val());
            let used_hours = $('input[name="express_package[]"]').map((_, el) => parseInt(el.value)).get();

          // Form Swal
            // Define Select Options
            let input_options = {};

            for (let i = (minimum_express_stay + 1); i <= 12; i++) {
                if (!used_hours.includes(i))
                    input_options[i] = `${i} H`;
            }

            // Launch swal
            const { value: package_duration } = await Swal.fire({
                type: "question",
                html: `
                    <h5 class="mt-2 harsi-color fw-semi-bold">
                        {{ __('entity_forms')['room_type']['package_duration'] }}:
                    </h5>
                `,

                showCancelButton: true,
                confirmButtonText: "{{ __('common_actions')['accept'] }}",
                cancelButtonText: "{{ __('common_actions')['cancel'] }}",

                input: 'select',
                inputOptions: input_options,
                inputValidator: (value) => {
                    return new Promise((resolve) => {
                        if (value) {
                            resolve()
                        } else {
                            resolve("{{ __('validation.required', ['attribute' => '']) }}")
                        }
                    })
                },
            });
                if (!package_duration) return; // Si el usuario cancela el Swal, abortamos todo el proceso

          // Draw New Fields
            // Render Package Identifier
            let inserted = false;
            const $express_packages = $('#express_packages_breakdown').find('[id^="express_package_"][id$="_h_block"]');

            $express_packages.each(function () {
                const package_value = parseInt($(this).attr('id').match(/(\d+)/)[0]);

                if (package_duration < package_value) {
                    $(this).before(renderExpressPackageBlock(package_duration));
                    inserted = true; return false;
                }
            });
                if (!inserted) $('#express_packages_breakdown').append(renderExpressPackageBlock(package_duration));

            // Render Package Pricing
            $('[id^="season_"][id$="_express_breakdown"]').each(function () {
              // Controls
                let inserted = false;
                const $container = $(this);
                const season_id = $container.attr('id').match(/season_(\d+)_/)[1];
                const season_default_price = $(`#season_${season_id}_price`).val() || "";

              // Add Season Package Pricing
                $container.find('[data-package]').each(function () {
                    const pkg = parseInt($(this).attr('data-package'));

                    if (package_duration < pkg) {
                        $(this).before(renderExpressSeasonBlock(season_id, package_duration, season_default_price));
                        inserted = true; return false;
                    }
                });

                if (!inserted) $container.append(renderExpressSeasonBlock(season_id, package_duration, season_default_price));
            });

            // Render Express Pax Pricing
            $('[id^="season_"][id$="_pax_express_pricing_breakdown"]').each(function () {
              // Controls
                let inserted = false;
                const $container = $(this);
                const season_id = $container.attr('id').match(/season_(\d+)_/)[1];
                const season_default_price = $(`#season_${season_id}_price`).val() || "";

              // Add Season Package Pricing
                $container.find('[data-package]').each(function () {
                    const pkg = parseInt($(this).attr('data-package'));

                    if (package_duration < pkg) {
                        $(this).before(renderExpressPaxSeasonBlock(season_id, package_duration, 1, season_default_price));
                        inserted = true; return false;
                    }
                });

                if (!inserted) $container.append(renderExpressPaxSeasonBlock(season_id, package_duration, 1, season_default_price));
                renderPaxPricing();
            });
        }

        function removeExpressPackage(btn) {
          // Control Data
            const package_duration = parseInt(
                $(btn).closest('[data-package]').attr('data-package')
            );

          // Remove Package inputs
            $(`[data-package="${package_duration}"]`).remove(); // Express Package Pricing

            launchSwalToast(
                'success',
                "{{ __('common_responses_and_messages')['deleted_successfully'] }}"
            );
        }

        function resetExpressPricing() {
          // Control Values
            const is_using_own_seasons = $(`#using_own_seasons`).prop('checked');

          // Render Changes
            $('#express_packages_breakdown').html(basic_express_packages); // Reset Package List

            if (is_using_own_seasons) { // Reset pricing per Season
              // Express pricing per Season
                $('#express_pricing_breakdown').find('[id^="season_"][id$="_express_breakdown"]')
                .each(function () {
                  // Render Controls
                    const $container = $(this);
                    const season_id = $container.attr('id').match(/season_(\d+)_express_breakdown/)[1];

                  // Reset pricing
                    $container.html(renderExpressSeasonBlock(season_id, 1, "0.00"));
                });

              // Express Pax pricing per Season
                $('#pax_express_pricing_breakdown').find('[id^="season_"][id$="_express_1_px_breakdown"]')
                .each(function () {
                  // Render Controls
                    const $container = $(this);
                    const season_id = $container.attr('id').match(/season_(\d+)_express_1_px_breakdown/)[1];

                  // Reset pricing
                    $container.html(renderExpressPaxPricing(season_id, 1, 1, "0.00"));
                });
            } else { // Default Season
                $('#express_pricing_breakdown').html(basic_express_pricing);
                $('#pax_express_pricing_breakdown').html(basic_pax_express_pricing);
            }

          // Spread Data
            $('#minimum_express_stay').val(1);
        }

  //* PAX Functions
    function renderPaxPricing() {
      // Quantity Controls
        const pax_room_limit = parseFloat($("#pax_room_limit").val()) || 1;

        /**
            Iterate on Pricing Breakdown per Season
            - Build Pax Pricing
            - Build Express Pax Pricing
        */
        $('#pax_pricing_breakdown').find('[id^="season_"][id$="_px_breakdown"]')
        .each(function () { // Use the Pax Pricing base price as the basis for rendering.
          //* Render Controls
            const $pax_container = $(this);
            const season_id = $pax_container.attr('id').match(/season_(\d+)_px_breakdown/)[1];
            const $pax_express_containers = $(`#season_${season_id}_pax_express_pricing_breakdown`).find(`[id^="season_${season_id}_express_"][id$="_px_breakdown"]`);

          //* Quantity SubControls
            const total_rendered = $pax_container.find(`input[name="season_${season_id}_pxs[]"]`).length;
            const season_price = $(`#season_${season_id}_price`).val() ?? 0.00;

          //* Fill empty fields
            // Pax Pricing
            $pax_container.find(`input[name="season_${season_id}_pxs[]"]`).each(function () {
                const current_value = $(this).val();
                if (current_value === "" || current_value === null)
                    $(this).val(season_price).trigger('change');
            });

            // Express Pax Pricing
            iteratePaxExpressBlocks($pax_express_containers, season_id, function ($sub_container, package_duration) {
                $sub_container.find(`input[name="season_${season_id}_express_${package_duration}_pax[]"]`).each(function () {
                    const current_value = $(this).val();
                    if (current_value === "" || current_value === null)
                        $(this).val(season_price);
                });
            });

          //* Pax Pricing Controls
            // Increment
            if (pax_room_limit > total_rendered) {
                for (let index = total_rendered; index < pax_room_limit; index++) {
                    const px_quantity = index + 1;
                    $pax_container.append(renderPaxPricingBlock(season_id, px_quantity, season_price));
                }
            }

            // Decrement until limit will be reached
            if (pax_room_limit < total_rendered) {
              // Remove Pax Pricing
                $pax_container.find('.form-group').each(function () {
                    const px = parseInt($(this).attr('data-px'));
                    if (px > pax_room_limit) $(this).remove();
                });
            }

          //* Express Pax Pricing Controls
            iteratePaxExpressBlocks($pax_express_containers, season_id, function ($sub_container, package_duration, total_express_rendered) {
              // Increment
                if (pax_room_limit > total_express_rendered) {
                    for (let index = total_express_rendered; index < pax_room_limit; index++) {
                        const px_quantity = index + 1;
                        $sub_container.append(renderExpressPaxPricing(season_id, package_duration, px_quantity, season_price));
                    }
                }

              // Decrement until limit will be reached
                if (pax_room_limit < total_express_rendered) {
                    $sub_container.find('.form-group').each(function () {
                        const px = parseInt($(this).attr('data-express-px'));
                        if (px > pax_room_limit) $(this).remove();
                    });
                }
            });

        });
    }

  //* Shared Functions
    function ensureInheritedPricing(season_id, element){
      // Shared Data
        const season_price = $(`#season_${season_id}_price`).val() ?? 0.00;
        const previous_season_value = element.dataset.previous;

      // Update Pax Pricing
        const $pax_container = $(`#season_${season_id}_px_breakdown`);
        $pax_container.find(`input[name="season_${season_id}_pxs[]"]`).each(function () {
            const current_value = $(this).val();
            if (current_value === "" || current_value === null || parseFloat(current_value) === parseFloat(previous_season_value))
                $(this).val(season_price);
        });

      // Update Express Packages Pricing
        const $express_container = $(`#season_${season_id}_express_breakdown`);
        $express_container.find(`input[name="season_${season_id}_express[]"]`).each(function () {
            const current_value = $(this).val();
            if (current_value === "" || current_value === null || parseFloat(current_value) === parseFloat(previous_season_value))
                $(this).val(season_price).trigger('change');
        });

      // Update Express Pax Pricing
        const $pax_express_container = $(`#season_${season_id}_pax_express_pricing_breakdown`);
        $pax_express_container.find(`input[name^="season_${season_id}_express_"][name$="_pax[]"]`).each(function () {
            const current_value = $(this).val();
            if (current_value === "" || current_value === null || parseFloat(current_value) === parseFloat(previous_season_value))
                $(this).val(season_price);
        });
    }

    function ensureSubInheritedPricing(season_id, duration, element){
      // Shared Data
        const express_package_price = $(`#season_${season_id}_express_${duration}`).val() ?? 0.00;
        const previous_season_value = element.dataset.previous;

      // Update Express Pax Pricing
        const $pax_express_container = $(`#season_${season_id}_pax_express_pricing_breakdown`);
        $pax_express_container.find(`input[name="season_${season_id}_express_${duration}_pax[]"]`).each(function () {
            const current_value = $(this).val();
            if (current_value === "" || current_value === null || parseFloat(current_value) === parseFloat(previous_season_value))
                $(this).val(express_package_price);
        });
    }

    function iteratePaxExpressBlocks($containers, season_id, callback) {
        $containers.each(function () {
          // Extract Package Duration
            const $pax_express_container = $(this);
            const extractor_regex = new RegExp(`season_${season_id}_express_(\\d+)_px_breakdown`);
            const package_duration = $pax_express_container.attr('id').match(extractor_regex)[1];

            const $sub_express_pax_container = $(`#season_${season_id}_express_${package_duration}_px_breakdown`);
            const total_rendered = $sub_express_pax_container.find(`input[name="season_${season_id}_express_${package_duration}_pax[]"]`).length;

          // Dynamic Actions
            callback($sub_express_pax_container, package_duration, total_rendered);
        });
    }
</script>

{{-- OTAS Behavior Functions --}}
@if ($has_otas)
    <script>
      // Dynamic Interactions
        function validateChannelsForm(form) {
            // Obtenemos cada uno de los campos del Formulario
            const inputs = form.querySelectorAll('input, select');
            const $tab_box = $('#ota_tab_box'); // Contenedor de los NavTab
            const $container = $('#ota_tab_content'); // Contenedor de los Tab Panels

            for (const input of inputs) {
                // Ignora campos hidden, readonly o invisibles (por display: none o visibility: hidden)
                if (
                    input.hasAttribute('readonly')
                    || input.type === 'hidden'
                    || $(input).css('visibility') === 'hidden'
                    || $(input).css('display') === 'none'
                ) continue;

                if (!input.checkValidity()) { // Si el campo es incorrecto, o vació
                    const $tabPane = $(input).closest('#ota_tab_content .tab-pane'); // ¿Esta dentro de alguna de las Tabs de OTAS?

                    if ($tabPane.length) {
                        // Obtenemos el Id de su Tab y navegamos a ella
                        const tabId = $tabPane.attr('id');

                        // Desactivar SOLO tabs/panes dentro del contenedor
                        const $tabs   = $tab_box.find('[data-toggle="tab"], [data-bs-toggle="tab"]');
                        const $panes  = $container.find('.tab-pane');

                        $tabs.removeClass('active');
                        $panes.removeClass('show active');

                        // Activar la tab/pane correspondiente dentro del contenedor
                        $tabs.filter(`[href="#${tabId}"]`).addClass('active');
                        $container.find(`#${tabId}`).addClass('show active');

                        setTimeout(() => {
                            input.reportValidity();
                            input.focus();
                            input.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }, 100);
                    } else {
                        // Simplemente muestra el mensaje
                        input.reportValidity();
                        input.focus();
                        input.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }

                    return false;
                }
            }

            return true;
        }

        async function drawRatePlans(input, sample_ota) {
            const selected_value = input.value;
                if (["none"].includes(selected_value)) return;

            const room_rate_plans = window.external_rooms[sample_ota][selected_value].rate_plans;
            const rate_plans_quantity = Object.keys(room_rate_plans).length;

            let rate_plans_content = `
                <div class="flex-shrink-0 px-3 mb-4 text-center col-12 border-right">
                    <p class="empty-list-message">{{ __('entity_forms')['otas_connection']['common']['no_rate_plans'] }}</p>
                </div>
            `;

            if (rate_plans_quantity) {
                rate_plans_content = '';

                await Object.entries(room_rate_plans).forEach(([plan_id, plan_data]) => {
                    rate_plans_content += `
                        <div class="flex-shrink-0 px-3 col-6 border-right">

                            <div class="mb-3 input-group">
                                <input type="text" name="tariff_plan_name_${plan_id}" id="tariff_plan_name_${plan_id}"
                                    class="text-center form-control disabled-fields" readonly required
                                    value="${plan_data.name}">
                            </div>

                            <div class="mb-3 input-group">
                                <div class="input-group-prepend">
                                    <label {{-- for="tariff_plan_rate_${plan_id}" --}} class="input-group-text">
                                        {{ __('entity_fields')['reservation']['final_price'] }}
                                    </label>
                                </div>
                                <input type="number" {{-- name="tariff_plan_rate_${plan_id}" id="tariff_plan_rate_${plan_id}" --}} readonly required
                                    class="form-control" step="0.01"
                                    value="${plan_data.rate.toFixed(2)}"
                                    onchange="formatDecimal(this)">
                            </div>

                            <div class="mb-3 input-group">
                                <div class="input-group-prepend">
                                    <label {{-- for="tariff_plan_min_stay_${plan_id}" --}} class="px-1 input-group-text">
                                        {{ __('entity_forms')['otas_connection']['room_type_addon']['otas_data']['minimum_stay'] }}
                                    </label>
                                </div>
                                <input type="number" {{-- name="tariff_plan_min_stay_${plan_id}" id="tariff_plan_min_stay_${plan_id}" --}} readonly required
                                    class="form-control" step=".1" min="0" placeholder="0"
                                    value="${plan_data.minimum_stay}"
                                    onchange="formatInteger(this)">
                            </div>

                            <div class="mb-3 input-group">
                                <div class="input-group-prepend">
                                    <label {{-- for="tariff_plan_max_stay_${plan_id}" --}} class="px-1 input-group-text">
                                        {{ __('entity_forms')['otas_connection']['room_type_addon']['otas_data']['maximum_stay'] }}
                                    </label>
                                </div>
                                <input type="number" {{-- name="tariff_plan_max_stay_${plan_id}" id="tariff_plan_max_stay_${plan_id}" --}} readonly required
                                    class="form-control" step=".1" min="0" placeholder="0"
                                    value="${plan_data.maximum_stay}"
                                    onchange="formatInteger(this)">
                            </div>

                        </div>
                    `;
                });
            }

            const base_structure = `
                <div class="pl-2 d-flex align-items-start text-start">
                    <h5 class="pt-1 harsi-color" style="font-weight: 700">{{ __('entity_forms')['otas_connection']['room_type_addon']['otas_data']['rate_plans'] }}</h5>
                    {{--&nbsp;&nbsp;
                    <button type="button" class="mb-3 btn btn-outline-harsi">
                        <i class="fas fa-sync"></i>
                    </button>--}}
                </div>

                <div class="pt-2 pb-4">
                    <div class="overflow-auto row flex-nowrap justify-content-${rate_plans_quantity > 2 ? "start" : "center"}">
                        ${rate_plans_content}
                    </div>
                </div>
            `;

            // $(`#${sample_ota}_rate_plans_section`).html(base_structure); // TODO
        }

        function ensureToggleAction(ota_data) {
            const {id, name, sample_name, local_agency_id} = ota_data;
            const switch_id = `${sample_name}_is_active`;
            const checked = $(`#${switch_id}`).prop('checked');

            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['default_confirmation'] }}",
                html: translateAndReplace(
                    `entity_forms.otas_connection.connections.warnings.${checked ? 'disable_connection' : 'enable_connection'}`,
                    { ota: name }
                ),
                showCancelButton: true,
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
                cancelButtonText: "{{ __('common_actions')['cancel'] }}",
            }).then((response) => {
                if (response.dismiss) {
                    restoreToggleValue(switch_id);
                    return;
                }

                if (!checked) {  // Has the OTA in question been deactivated?

                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url:"{{ route('otas.update') }}",
                        method:"POST",
                        data: {
                            hidden_id: id,
                            toggle_control: false,
                            assigned_agency: local_agency_id,
                        },
                        success: function(data) {
                            launchSwalToast(
                                'success',
                                `{{ __('common_responses_and_messages')['update'] }}&nbsp;<b style="color:#12a15e">{{ __('common_responses_and_messages')['completed'] }}</b>`
                            );

                            // Hide Disconnected OTA (Tab and Content)
                            $(`#local_OTA_${sample_name}, #tab_OTA_${sample_name}`).prop('hidden', true);

                            // Show next OTA content or render empty message
                            defineChannelsContent();
                            return;
                        },

                        error: function(err) {
                            // Launch Error
                            launchSwalToast(
                                "error",
                                "{{ __('entity_forms')['otas_connection']['connections']['errors']['connection_not_updated'] }}"
                            );

                            // Restore toggle value
                            restoreToggleValue(switch_id);
                            return;
                        }
                    });


                }
            });
        }

      // Support Functions
        function defineChannelsContent() {
            // Get the ID of the tabs whose OTAs are still active.
            const enabled_otas = $("[id^='tab_OTA_']:visible");

            // If there is at least one active tab, we will display it.
            if (enabled_otas.length) {
                const associated_tab_reference = enabled_otas.first().find('a[data-toggle="tab"], a[data-bs-toggle="tab"]');

                if(associated_tab_reference.length)
                    associated_tab_reference.tab('show');
            } else { // Show Empty Message
                $('#otas_panel').html(`
                    <h3 class="my-3 text-center legend-titles ota-indications">
                        <i>{{ __('entity_forms')['otas_connection']['common']['no_active_channels'] }}</i>
                    </h3>
                `);
            }
        }
    </script>
@endif

{{-- General Support Functions --}}
<script>
  // Support Functions
    function restoreToggleValue(switch_id) {
        const $switch = $(`#${switch_id}`);
        $switch.prop('checked', !$switch.prop('checked'));
    }

    function launchSwalToast(type, title) {
        Swal.fire({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 5000,
            // timerProgressBar: true,
            title,
            type,
        });
    }

    function showToast(text, gradient_from, gradient_to) {
        Toastify({
            text,
            duration: 4000,
            close: false,
            gravity: "bottom",
            position: "center",
            avatar: "{{ asset('images/toast-info-icon.png') }}",

            selector: document.body,
            offset: { x: 0, y: 24 },
            style: {
                background: `linear-gradient(to right, ${gradient_from}, ${gradient_to})`,
            },
        }).showToast();
    }

  // Formatters
    function formatDecimal(input) {
        const valor = parseFloat(input.value);

        if (isNaN(valor)) return;

        const result = parseFloat(valor.toFixed(2));
        const exceedsTwoDecimals = /\d\.\d{3,}/.test(valor);

        if (exceedsTwoDecimals) {
            input.value = Math.abs(result).toFixed(2);
        } else {
            input.value = Math.abs(result === 0 ? 0 : valor).toFixed(2);
        }

        return;
    }

    function formatInteger(input, {has_limit = false, limit = 365, default_quantity = 10, ceil_number = false} = {}) {
        // Ensure a valid number
        const raw = Number(input.value);
            if (!Number.isFinite(raw)) {
                input.value = has_limit ? default_quantity : 0;
                return;
            }

        // Round decimals
        let value = ceil_number ? Math.ceil(raw): Math.round(raw);

        // Defaults Managements
        if (value < 0) value = 0;
        if (value < input.min) value = input.min;
        if (has_limit && value > limit) value = limit;

        input.value = value;
    }

  // Form Controls
    function sharedSectionValidator(section_id) {
      // Control Variables
        const $section = $(`#${section_id}`);

        let is_valid = true;
        let section_error_message = "";
        let first_invalid = null;

        let $tabPane = $section.hasClass('tab-pane')
            ? $section : $section.closest('.tab-pane');

      // Check not disabled inputs
        $section.find('input, select, textarea')
        .filter(':not(:disabled):not([type="hidden"])')
        .each(function () {
            const el = this;

            // Limpia estados previos
            el.setCustomValidity && el.setCustomValidity('');
            $(el).removeClass('is-invalid');

            // Pequeño trim en campos de texto/email/tel para evitar espacios accidentales
            if ($(el).is('input[type="text"], input[type="email"], input[type="tel"]'))
                el.value = el.value.trim();

            // Usa validación nativa HTML5
            if (!el.checkValidity()) {
                is_valid = false;
                first_invalid = el;

                if (el.validity.patternMismatch && el.title)
                    section_error_message = el.title;
                else
                    section_error_message = el.validationMessage;

                $(el).addClass('is-invalid');
                return false;
            }
        });

      // Activate that tab were errors exists
        if (!is_valid && first_invalid && $tabPane.length) {
            const tabId = $tabPane.attr('id');
            const $tabTrigger = $(`a[data-toggle="tab"][href="#${tabId}"]`);

            if ($tabTrigger.length) $tabTrigger.tab('show');
        }

      // Report Errors
        if (!is_valid && first_invalid) {
            setTimeout(() => {
                first_invalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                first_invalid.focus({ preventScroll: true });
                first_invalid.reportValidity();
            }, 200);
        }

      // Return validations
        return {section_valid: is_valid, show_error_detected: true, section_error_message};
    }

</script>
