<script>window.alsendoMapConfig = {{ map_config_json|raw }};</script>
{% if poland_package_type_dimensions is defined %}
<script>window.alsendoPolandPackageTypeDimensions = {{ poland_package_type_dimensions|json_encode|raw }};</script>
{% endif %}
{{ header }}{{ column_left }}
<div id="content">

    {% include 'extension/alsendo/admin/view/template/partials/info_modal.twig' %}
    <div class="page-header">
        <div class="container-fluid">
            <h1>{{ heading_title }}</h1>
            <ol class="breadcrumb">
                {% for breadcrumb in breadcrumbs %}
                    <li class="breadcrumb-item"><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
                {% endfor %}
            </ol>
            <p>{{ configuration_subheader_text }}</p>
        </div>
    </div>

    <div class="container-fluid">

        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-globe"></i> {{ text_region_and_api_configuration }}</h3>
                    </div>
                    <div class="card-body">
                        <div id="alsendo-api-connection-success" style="display:none;">
                            <div class="alert alert-success mb-3" role="alert">
                                <i class="fas fa-check-circle"></i> {{ text_api_connection_success }}
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3 mb-2">
                                <div class="form-group">
                                    <label for="region-select" class="form-label">{{ text_select_region }}</label>
                                    <select id="region-select" class="form-control">
                                        <option value="">{{ text_select_region_default }}</option>
                                        {% for key, name in regions %}
                                            <option value="{{ key }}" {% if current_region == key %}selected{% endif %}>{{ name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-9">
                                <div id="api-config-poland" {% if current_region != 'poland' %}style="display: none;"{% endif %}>
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="app-id" class="form-label">{{ text_app_id }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="text" id="app-id" class="form-control" data-wrapper-config="poland" value="{{ current_app_id }}" placeholder="{{ text_app_id }}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="app-secret" class="form-label">{{ text_app_secret }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="password" id="app-secret" class="form-control" data-wrapper-config="poland" value="{{ current_app_secret }}" placeholder="{{ text_app_secret }}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="sandbox" class="form-label">{{ text_sandbox }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="checkbox" id="sandbox" class="form-check-input" data-wrapper-config="poland" value="1" {% if current_sandbox %}checked{% endif %}>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="api-config-romania" {% if current_region != 'romania' %}style="display: none;"{% endif %}>
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="token" class="form-label">{{ text_client_id }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="text" id="ro-client-id" class="form-control" data-wrapper-config="romania" value="{{ current_ro_client_id }}" placeholder="{{ text_client_id }}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="token" class="form-label">{{ text_client_secret }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="password" id="ro-client-secret" class="form-control" data-wrapper-config="romania" value="{{ current_ro_client_secret }}" placeholder="{{ text_client_secret }}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="ro-sandbox" class="form-label">{{ text_sandbox }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="checkbox" id="ro-sandbox" class="form-check-input" data-wrapper-config="romania" value="1" {% if current_ro_sandbox %}checked{% endif %}>
                                            </div>
                                        </div>
                                    </div>

                                    <p>{{ text_ecolet_register_app_here_text }} <a href="https://panel.ecolet.ro/en/account/oauth/clients" target="_blank">https://panel.ecolet.ro/en/account/oauth/clients</a></p>
                                    <p class="mb-0 pb-0">{{ text_ecolet_register_redirect_instruction_text }}</p>
                                    <p class="fw-semibold">{{ ecolet_register_link }}</p>
                                    {% if '/localhost' in ecolet_register_link or '/127.0.0.1' in ecolet_register_link %}
                                        <p style="color:#ff0000;" class="fw-bold">LOCALHOST DETECTED. For development, use 'https://google.com' for redirect URL when registering a new app. Once redirected to Google, 1) replace 'https://google.com' in the URL with the link above ^ 2) replace "?code" with "&code" and hit enter. </p>
                                    {% endif %}

                                    <div class="text-end">
                                        <button type="button" class="btn btn-outline-primary mt-2" id="ecolet-authorize-btn">{{ text_click_to_oauth_authorize }}</button>
                                    </div>
                                </div>

                                <div id="api-config-czechia" {% if current_region != 'czechia' %}style="display: none;"{% endif %}>
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="api-key" class="form-label">{{ text_api_key }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="password" id="api-key" class="form-control" data-wrapper-config="czechia" value="{{ current_api_key }}" placeholder="{{ text_api_key }}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <label for="cz-sandbox" class="form-label">{{ text_sandbox }}</label>
                                            </div>
                                            <div class="col-md-9">
                                                <input type="checkbox" id="cz-sandbox" class="form-check-input" data-wrapper-config="czechia" value="1" {% if current_cz_sandbox %}checked{% endif %}>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="api-config-empty" {% if current_region %}style="display: none;"{% endif %}>
                                    <p class="text-muted">{{ text_select_region_first }}</p>
                                </div>
                            </div>
                        </div>

                        <div class="text-end mt-3">
                            <button type="button" class="btn btn-primary" onclick="saveRegionAndApiKeys()">{{ text_save }}</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user"></i> {{ text_sender_address }}</h3>
                        <p>{{ text_sender_address_subheader }}</p>
                    </div>
                    <div class="card-body">
                        {% if sender_address_templates is defined %}
                            <div id="sender-form-container">
                                <div id="sender-address-form">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="sender_template_select" class="form-label">{{ text_select_template }}</label>
                                                <select id="sender_template_select" class="form-control" onchange="onSenderTemplateSelect()">
                                                    <option value="">{{ text_new_template }}</option>
                                                    {% for template in sender_address_templates %}
                                                        <option value="{{ template.id }}" {% if template.main %}selected{% endif %}>{{ template.company_name }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    {% if region == 'czechia' and address_book_list is defined and address_book_list|length > 0 %}
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="address_book_select" class="form-label">{{ text_address_from_address_book }}</label>
                                                <select id="address_book_select" class="form-control" onchange="onAddressBookSelect()">
                                                    <option value="">{{ text_select_address }}</option>
                                                    {% for id, address in address_book_list %}
                                                        <option value="{{ id }}" data-address="{{ address|json_encode|e('html_attr') }}" {% if sender_address_external_id_preselect is defined and sender_address_external_id_preselect|default('') == id|default('') %}selected{% endif %}>{{ address.firstname|default('') }} {{ address.surname|default('') }}{% if address.street|default('') %} - {{ address.street }}{% endif %}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    {% endif %}

                                    <div class="row mb-3" id="sender-address-type-container">
                                        <div class="col-md-8 col-12">
                                            <label class="form-label">{{ text_address_type }}</label>
                                            <div class="d-flex w-100 gap-2" role="group">
                                                <button type="button"
                                                        class="btn btn-outline-secondary combobox-btn w-50 {% if alsendo_order_details.data.sender.address_type == 'company' %}active{% endif %}"
                                                        data-group="sender-address-type" data-value="company"
                                                        data-on-select-show-element="company_name_container">
                                                    {{ text_address_type_company }}
                                                </button>
                                                <button type="button"
                                                        class="btn btn-outline-secondary combobox-btn w-50 {% if alsendo_order_details.data.sender.address_type == 'home' %}active{% endif %}"
                                                        data-group="sender-address-type" data-value="home"
                                                        data-on-select-hide-element="company_name_container">
                                                    {{ text_address_type_home }}
                                                </button>
                                            </div>
                                            <input type="hidden" name="sender_address_type" id="sender-address-type"
                                                   value="{{ alsendo_order_details.data.sender.address_type }}">
                                        </div>

                                    </div>

                                    <div class="row mb-3" id="company_name_container">
                                        <div class="col-md-6 col-12">
                                            <label for="company_name" class="form-label">{{ text_company_name }}</label>
                                            <input type="text" class="form-control" id="company_name">
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6 col-12">
                                            <label for="full_name" class="form-label">{{ text_full_name }}</label>
                                            <input type="text" class="form-control" id="full_name">
                                        </div>
                                    </div>

                                    {% if region == 'romania' %}
                                    <div class="row mb-3">
                                        <div class="col-md-6 col-12">
                                            <label for="street" class="form-label">{{ text_street }}</label>
                                            <input type="text" id="street" class="form-control">
                                        </div>
                                        <div class="col-md-6 col-12">
                                            <label for="building_number" class="form-label">{{ text_building_number }}</label>
                                            <input type="text" id="building_number" class="form-control" required>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-3 col-12">
                                            <label for="block" class="form-label">{{ text_address_block }}</label>
                                            <input type="text" id="block" class="form-control">
                                        </div>
                                        <div class="col-md-3 col-12">
                                            <label for="entrance" class="form-label">{{ text_address_entrance }}</label>
                                            <input type="text" id="entrance" class="form-control">
                                        </div>
                                        <div class="col-md-3 col-12">
                                            <label for="floor" class="form-label">{{ text_address_floor }}</label>
                                            <input type="text" id="floor" class="form-control">
                                        </div>
                                        <div class="col-md-3 col-12">
                                            <label for="apartment_number" class="form-label">{{ text_apartment_number }}</label>
                                            <input type="text" id="apartment_number" class="form-control">
                                        </div>
                                    </div>
                                    {% else %}
                                    <div class="row mb-3">
                                        <div class="col-md-6 col-12">
                                            <label for="street" class="form-label">{{ text_street }}</label>
                                            <input type="text" id="street" class="form-control">
                                        </div>
                                        <div class="col-md-3 col-12">
                                            <label for="building_number" class="form-label">{{ text_building_number }}</label>
                                            <input type="text" id="building_number" class="form-control" required>
                                        </div>
                                        <div class="col-md-3 col-12">
                                            <label for="apartment_number" class="form-label">{{ text_apartment_number }}</label>
                                            <input type="text" id="apartment_number" class="form-control">
                                        </div>
                                    </div>
                                    {% endif %}

                                    <div class="row mb-3">
                                        <div class=" form-group col-md-3 col-12">
                                            <label for="country" class="form-label">{{ text_country }}</label>
                                            <select id="country" class="form-control">
                                                <option value="">--</option>
                                                {% for iso, name in countries %}
                                                    <option value="{{ iso }}">{{ name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="form-group col-md-3 col-12">
                                            <label for="postal_code" class="form-label">{{ text_postal_code }}</label>
                                            <input type="text" id="postal_code" class="form-control" required>
                                        </div>
                                        <div class="form-group col-md-6 col-12">
                                            <label for="city" class="form-label">{{ text_city }}</label>
                                            <input type="text" id="city" class="form-control" required>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group mb-3">
                                                <label for="phone_number" class="form-label">{{ text_phone_number }}</label>
                                                <input type="text" id="phone_number" class="form-control" required>
                                            </div>
                                            <div class="form-group mb-3">
                                                <label for="email" class="form-label">{{ text_email }}</label>
                                                <input type="email" id="email" class="form-control" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="bank_account_number" class="form-label">{{ text_bank_account_number }}</label>
                                            <input type="text" id="bank_account_number" class="form-control">
                                        </div>
                                        {% if region == 'czechia' %}
                                            <div class="col-md-6">
                                                <label for="bank_code" class="form-label">{{ text_bank_code }}</label>
                                                <input type="text" id="bank_code" class="form-control">
                                            </div>
                                        {% endif %}
                                    </div>
                                    {% if region == 'czechia' %}
                                    <div class="row mb-3">
                                        <div class="col-md-12">
                                            <label for="additional_bank_account_number" class="form-label">{{ text_iban_bank_account_number }}</label>
                                            <input type="text" id="additional_bank_account_number" class="form-control">
                                        </div>
                                    </div>
                                    {% endif %}

                                    <div class="text-end mt-3">
                                        <input type="hidden" id="sender_template_id" value="">
                                        <input type="hidden" id="sender_external_id" value="">
                                        <button type="button" class="btn btn-outline-primary" id="set-sender-template-main" onclick="setMainTemplate('sender')">{{ text_save_template_as_main }}</button>
                                        <button type="button" class="btn btn-outline-primary" id="save-as-new-sender-template-btn" onclick="showTemplateNameModal('sender', 'new')">{{ text_save_as_new_template }}</button>
                                        <button type="button" class="btn btn-primary" id="update-sender-template-btn" onclick="showTemplateNameModal('sender', 'update')" style="display: none;">{{ text_update }}</button>
                                    </div>
                                </div>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-box"></i> {{ text_shipping_settings }}</h3>
                        <p>{{ text_shipping_settings_subheader }}</p>
                    </div>
                    <div class="card-body">
                        {% if shipping_settings_templates is defined %}
                        <div id="shipping-form-container">
                            <div id="shipping-settings-form">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group mb-3">
                                            <label for="template_select" class="form-label">{{ text_select_template }}</label>
                                            <select id="template_select" class="form-control" onchange="onTemplateSelect()">
                                                <option value="">{{ text_new_template }}</option>
                                                {% for template in shipping_settings_templates %}
                                                    <option value="{{ template.id }}" {% if template.main %}selected{% endif %}>{{ template.name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="package_type" class="form-label">{{ text_package_type }}</label>
                                            <select id="package_type" class="form-control" required>
                                                {% if region == 'romania' and romania_package_types is defined and romania_package_types|length > 0 %}
                                                    {% for pt in romania_package_types %}
                                                        <option value="{{ pt.id }}">{{ pt.name }}</option>
                                                    {% endfor %}
                                                {% elseif region == 'poland' and poland_package_types is defined and poland_package_types|length > 0 %}
                                                    {% for pt in poland_package_types %}
                                                        <option value="{{ pt.id }}">{{ pt.name }}</option>
                                                    {% endfor %}
                                                {% else %}
                                                    <option value="standard" selected>{{ text_package_standard }}</option>
                                                    <option value="non-standard">{{ text_package_non_standard }}</option>
                                                {% endif %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                {% if region == 'romania' %}
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="non_standard" value="1" {% if non_standard %}checked{% endif %}>
                                            <label for="non_standard" class="form-check-label">{{ text_shipment_packaging_non_standard }}</label>
                                        </div>
                                    </div>
                                </div>
                                {% endif %}

                                <div class="row mb-3">
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="width" class="form-label">{{ text_width }}</label>
                                            <div class="position-relative">
                                                <input type="number" id="width" class="form-control" required>
                                                <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="length" class="form-label">{{ text_length }}</label>
                                            <div class="position-relative">
                                                <input type="number" id="length" class="form-control" required>
                                                <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="height" class="form-label">{{ text_height }}</label>
                                            <div class="position-relative">
                                                <input type="number" id="height" class="form-control" required>
                                                <span class="position-absolute" style="right: 40px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="weight" class="form-label">{{ text_weight }}</label>
                                            <div class="position-relative">
                                                <input type="number" id="weight" class="form-control" required>
                                                <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">kg</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="cash_on_delivery" class="form-label">{{ text_cash_on_delivery }}</label>
                                            <div class="position-relative">
                                                <input type="number" step="0.01" id="cash_on_delivery" class="form-control">
                                                <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">{{ current_store_currency }}</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-4 col-sm-6 mb-2">
                                        <div class="form-group">
                                            <label for="declared_value" class="form-label">{{ text_declared_value }}</label>
                                            <div class="position-relative">
                                                <input type="number" step="0.01" id="declared_value" class="form-control">
                                                <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">{{ current_store_currency }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label for="shipment_content" class="form-label">{{ text_shipment_content }}</label>
                                            <select id="shipment_content" class="form-control">
                                                <option value="" disabled selected>{{ text_dropdown_select_default_option }}</option>
                                                {% for value,human_friendly_translated_tag_name in available_tags %}
                                                    <option value="{{ value }}">{{ human_friendly_translated_tag_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="form-group mt-2 shipment-content-custom-text-container" style="display: none;">
                                            <label for="default_content_custom_text" class="form-label">{{ text_shipment_content_custom_text }}</label>
                                            <input type="text" id="default_content_custom_text" name="default_content_custom_text" class="form-control" placeholder="{{ text_shipment_content_custom_text_placeholder }}">
                                        </div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label class="form-label">{{ text_pickup_type }}</label>
                                            <div class="d-flex flex-wrap gap-2 mt-2">
                                                {% for pickup_type in pickup_types %}
                                                    <button type="button"
                                                            class="btn btn-outline-secondary combobox-btn pickup-type-btn flex-fill text-center"
                                                            data-group="selected_pickup_type"
                                                            {% if pickup_type == 'SELF' %}
                                                                data-on-select-show-element="shipment-pickup-point-container"
                                                                data-on-select-hide-element="shipment-preferred-pickup-date-container"
                                                            {% elseif pickup_type == 'COURIER' %}
                                                                data-on-select-show-element="shipment-preferred-pickup-date-container"
                                                                data-on-select-hide-element="shipment-pickup-point-container"
                                                            {% else %}
                                                                data-on-select-hide-element="shipment-pickup-point-container,shipment-preferred-pickup-date-container"
                                                            {% endif %}
                                                            data-value="{{ pickup_type }}">
                                                        {{ pickup_type_labels[pickup_type] }}
                                                    </button>
                                                {% endfor %}
                                            </div>
                                            <input type="hidden" id="selected_pickup_type" value="">
                                        </div>
                                    </div>
                                </div>

                                <div class="text-end mt-3">
                                    <input type="hidden" id="shipping_template_id" value="">
                                    <button type="button" class="btn btn-outline-primary" id="set-shipment-template-main" onclick="setMainTemplate('shipping')">{{ text_save_template_as_main }}</button>
                                    <button type="button" class="btn btn-outline-primary" id="save-as-new-template-btn" onclick="showTemplateNameModal('shipping', 'new')">{{ text_save_as_new_template }}</button>
                                    <button type="button" class="btn btn-primary" id="update-shipping-template-btn" onclick="showTemplateNameModal('shipping', 'update')" style="display: none;">{{ text_update }}</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>


        {% if region != 'czechia' %}
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-cog"></i> {{ text_additional_settings }}</h3>
                        <p>{{ text_additional_settings_subheader }}</p>
                    </div>
                    <div class="card-body">

                        <div id="additional-settings-form">
                            <h5>{{ text_default_pickup_points }}</h5>
                            <div class="row mb-4">
                                <div class="col-12">
                                    {% for carrier in carriers %}
                                        <div class="form-group mb-3">
                                            <div class="row align-items-center">
                                                <div class="col-md-3">
                                                    <label for="{{ carrier.key }}_point" class="form-label">{{ carrier.label }}</label>
                                                </div>
                                                <div class="col-md-9">
                                                    <div class="input-group">
                                                        <input type="text"
                                                               id="{{ carrier.key }}_point_display"
                                                               class="form-control"
                                                               readonly
                                                               data-map-selector="{{ carrier.selector }}"
                                                               value="{% if carrier.default %}{{ carrier.default.code }} - {{ carrier.default.name }}{% else %}{{ text_point_not_selected }}{% endif %}">
                                                        <input type="hidden"
                                                               id="{{ carrier.key }}_point"
                                                               data-map-selector="{{ carrier.selector }}"
                                                               value="{% if carrier.default %}{{ carrier.default|json_encode|e('html_attr') }}{% endif %}">
                                                        <button class="btn btn-outline-primary"
                                                                type="button"
                                                                onclick="openPointMapWithStreet('{{ carrier.selector }}', ['{{ carrier.key }}'], 'POSTING', '{{ region }}')">
                                                            {{ text_select_point }}
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    {% endfor %}
                                </div>
                            </div>

                            <h5 class="mt-4">{{ text_default_pickup_hours }}</h5>
                            <div class="row mb-4">
                                {% set hours = 8..17 %}
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-5">
                                                <label for="pickup_hour_from" class="form-label">{{ text_pickup_hour_from }}</label>
                                            </div>
                                            <div class="col-md-7">
                                                <select id="pickup_hour_from" class="form-control">
                                                    <option value="">--</option>
                                                    {% for hour in hours %}
                                                        {% set formatted = '%02d:00'|format(hour) %}
                                                        <option value="{{ formatted }}" {% if additional_settings and additional_settings.pickup_hour_from == formatted %}selected{% endif %}>{{ formatted }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <div class="row align-items-center">
                                            <div class="col-md-5">
                                                <label for="pickup_hour_to" class="form-label">{{ text_pickup_hour_to }}</label>
                                            </div>
                                            <div class="col-md-7">
                                                <select id="pickup_hour_to" class="form-control">
                                                    <option value="">--</option>
                                                    {% for hour in hours %}
                                                        {% set formatted = '%02d:00'|format(hour) %}
                                                        <option value="{{ formatted }}" {% if additional_settings and additional_settings.pickup_hour_to == formatted %}selected{% endif %}>{{ formatted }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% if current_region == 'romania' %}
                            <h5>{{ text_declared_value_settings }}</h5>
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="auto_declared_value"
                                               {% if additional_settings and additional_settings.auto_declared_value %}checked{% endif %}>
                                        <label class="form-check-label" for="auto_declared_value">
                                            {{ text_auto_declared_value_label }}
                                        </label>
                                        <p class="text-muted small">
                                            {{ text_auto_declared_value_help_on }}<br>
                                            {{ text_auto_declared_value_help_off }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            {% if current_region == 'poland' %}
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="sameday_dispatch"
                                               {% if additional_settings and additional_settings.sameday_dispatch %}checked{% endif %}>
                                        <label class="form-check-label" for="sameday_dispatch">
                                            {{ text_sameday_dispatch_label }}
                                        </label>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <div class="text-end">
                                <button type="button" class="btn btn-primary" onclick="saveAdditionalSettings()">{{ text_save_additional_settings }}</button>
                            </div>
                        </div>


                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <div id="template-name-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 9999;">
        <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); min-width: 400px;">
            <h4>{{ text_template_name }}</h4>
            <div class="form-group mb-3">
                <label for="modal_template_name" class="form-label">{{ text_template_name }}</label>
                <input type="text" id="modal_template_name" class="form-control" required>
            </div>
            <div class="text-end">
                <button type="button" class="btn btn-primary" onclick="saveTemplateFromModal()">{{ text_save }}</button>
                <button type="button" class="btn btn-outline-primary" onclick="hideTemplateNameModal()">{{ text_cancel }}</button>
            </div>
        </div>
    </div>

</div>

<script>
    function saveRegionAndApiKeys() {
        var region = document.getElementById('region-select').value;

        if (!region) {
            return;
        }

        var data = {
            action: 'save_region_and_api_keys',
            region: region,
            user_token: '{{ user_token|e('js') }}'
        };

        var visibleInputs = [...document.querySelectorAll('[data-wrapper-config]')].filter(input => input.offsetParent !== null);

        visibleInputs.forEach(function(input) {
            if (input.type === 'checkbox') {
                data[input.id.replace(/-/g, '_')] = input.checked ? '1' : '';
            } else {
                data[input.id.replace(/-/g, '_')] = input.value;
            }
        });

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal('{{ success_region_saved|e('js') }}');
                    $('#hide-info-modal').one('click', function() {
                        location.reload();
                    });
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ error_saving_region|e('js') }}');
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        const successEl = document.getElementById('alsendo-api-connection-success');

        if (!successEl) {
            return;
        }

        $.ajax({
            url: '{{ api_connection_check_url|e('js') }}',
            type: 'GET',
            dataType: 'json',
            success: function (json) {
                if (json && json.success) {
                    successEl.style.display = '';
                }
            },
            error: function () {
                // silent fail: page should still work even if the check fails
            }
        });
    });

    function onRegionChange() {
        var region = document.getElementById('region-select').value;

        document.getElementById('api-config-poland').style.display = 'none';
        document.getElementById('api-config-romania').style.display = 'none';
        document.getElementById('api-config-czechia').style.display = 'none';
        document.getElementById('api-config-empty').style.display = 'none';

        if (region === 'poland') {
            document.getElementById('api-config-poland').style.display = 'block';
        } else if (region === 'romania') {
            document.getElementById('api-config-romania').style.display = 'block';
        } else if (region === 'czechia') {
            document.getElementById('api-config-czechia').style.display = 'block';
        } else {
            document.getElementById('api-config-empty').style.display = 'block';
        }
    }


    function initializeWrapper() {
        document.getElementById('wrapper-status').style.display = 'block';
        document.getElementById('status-content').innerHTML = '<i class="fas fa-spinner fa-spin"></i> {{ text_initializing_wrapper|e('js') }}';

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'initialize_wrapper',
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showWrapperSuccess(json.data);
                } else {
                    showWrapperError(json.error);
                }
            },
            error: function(xhr, status, error) {
                showWrapperError('{{ text_connection_failed|e('js') }}: ' + error);
            }
        });
    }

    function testWrapper() {
        document.getElementById('wrapper-status').style.display = 'block';
        document.getElementById('status-content').innerHTML = '<i class="fas fa-spinner fa-spin"></i> {{ text_testing_wrapper_connection|e('js') }}';

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'test_wrapper',
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showWrapperSuccess(json.data);
                } else {
                    showWrapperError(json.error);
                }
            },
            error: function(xhr, status, error) {
                showWrapperError('{{ text_test_failed|e('js') }}: ' + error);
            }
        });
    }

    function showWrapperSuccess(data) {
        document.getElementById('status-content').innerHTML =
            '<i class="fas fa-check-circle text-success"></i> ' + data.message;
        document.getElementById('wrapper-status').querySelector('.alert').className = 'alert alert-success';

        document.getElementById('connection-info').innerHTML =
            '<p><strong>{{ text_region_label|e('js') }}:</strong> ' + data.region + '</p>' +
            '<p><strong>{{ text_api_client|e('js') }}:</strong> ' + data.client_type + '</p>' +
            '<p><strong>{{ text_environment|e('js') }}:</strong> ' + data.environment + '</p>';

        if (data.stats) {
            document.getElementById('service-stats').innerHTML =
                '<p><strong>{{ text_total_services|e('js') }}:</strong> ' + data.stats.total_services + '</p>' +
                '<p><strong>{{ text_carriers|e('js') }}:</strong> ' + data.stats.unique_carriers + '</p>';

            if (data.services && data.services.length > 0) {
                var tbody = document.getElementById('services-tbody');
                tbody.innerHTML = '';
                data.services.forEach(function(service) {
                    var row = tbody.insertRow();
                    row.insertCell(0).innerHTML = service.id;
                    row.insertCell(1).innerHTML = service.name;
                    row.insertCell(2).innerHTML = '<span class="badge badge-primary">' + service.carrier + '</span>';
                    row.insertCell(3).innerHTML = service.type;
                });
                document.getElementById('services-table-card').style.display = 'block';
            }
        }

        document.getElementById('wrapper-details').style.display = 'block';
    }

    function showWrapperError(error) {
        document.getElementById('status-content').innerHTML =
            '<i class="fas fa-exclamation-circle text-danger"></i> ' + error;
        document.getElementById('wrapper-status').querySelector('.alert').className = 'alert alert-danger';
        document.getElementById('wrapper-details').style.display = 'none';
    }



    function clearSenderForm() {
        const formFields = ['company_name', 'full_name', 'street', 'building_number',
            'apartment_number', 'block', 'entrance', 'floor', 'postal_code', 'city', 'phone_number',
            'email', 'bank_account_number', 'bank_code', 'additional_bank_account_number', 'country'];

        formFields.forEach(field => {
            const element = document.getElementById(field);
            if (element) element.value = '';
        });

        document.getElementById('set-sender-template-main').disabled = true;
        document.getElementById('sender_template_id').value = '';
        const externalIdEl = document.getElementById('sender_external_id');
        if (externalIdEl) externalIdEl.value = '';
        const addressBookSelect = document.getElementById('address_book_select');
        if (addressBookSelect) addressBookSelect.value = '';
        setSenderFieldsReadonly(false);
    }

    function fillSenderForm(data) {
        const formFields = ['company_name', 'full_name', 'street', 'building_number',
            'apartment_number', 'block', 'entrance', 'floor', 'postal_code', 'city', 'phone_number',
            'email', 'bank_account_number', 'bank_code', 'additional_bank_account_number', 'sender-address-type', 'country'];

        const formFieldMappable = {
            'address_type': 'sender-address-type'
        };

        for (const [apiKey, elementId] of Object.entries(formFieldMappable)) {
            const element = document.getElementById(elementId);
            if (element && data[apiKey] !== undefined) {
                selectButtonComboboxByGroupAndValue(elementId, data[apiKey]);
            }
        }

        formFields.forEach(field => {
            const element = document.getElementById(field);
            if (element && data[field] !== undefined) {
                element.value = data[field] || '';
            }
        });

        const templateInput = document.getElementById('sender_template_id');
        if (templateInput) {
            templateInput.value = data.id;
        }

        document.getElementById('set-sender-template-main').disabled = (data.main === true);
        const externalIdEl = document.getElementById('sender_external_id');
        if (externalIdEl && data.external_id !== undefined) {
            externalIdEl.value = data.external_id || '';
        }
        const addressBookSelect = document.getElementById('address_book_select');
        if (addressBookSelect) {
            addressBookSelect.value = data.external_id || '';
        }
        setSenderFieldsReadonly(!!(data.external_id));
    }

    function setSenderFieldsReadonly(readonly) {
        const readonlyFields = ['company_name', 'full_name', 'street', 'building_number', 'apartment_number', 'block', 'entrance', 'floor', 'postal_code', 'city', 'phone_number', 'email'];
        const bgColor = '#e9ecef';
        readonlyFields.forEach(function(id) {
            const el = document.getElementById(id);
            if (el) {
                el.readOnly = readonly;
                el.style.backgroundColor = readonly ? bgColor : '';
            }
        });
        const bankEl = document.getElementById('bank_account_number');
        if (bankEl) {
            bankEl.readOnly = false;
            bankEl.style.backgroundColor = '';
        }
        const bankCodeEl = document.getElementById('bank_code');
        if (bankCodeEl) {
            bankCodeEl.readOnly = false;
            bankCodeEl.style.backgroundColor = '';
        }
        const countryEl = document.getElementById('country');
        if (countryEl) {
            countryEl.disabled = readonly;
            countryEl.style.backgroundColor = readonly ? bgColor : '';
        }
        const addressTypeContainer = document.getElementById('sender-address-type-container');
        if (addressTypeContainer) {
            addressTypeContainer.style.display = readonly ? 'none' : '';
        }
        const addressBookSelect = document.getElementById('address_book_select');
        if (addressBookSelect) addressBookSelect.disabled = false;
    }

    function onAddressBookSelect() {
        const select = document.getElementById('address_book_select');
        if (!select) return;
        const selected = select.options[select.selectedIndex];
        const externalIdEl = document.getElementById('sender_external_id');
        if (!selected || !selected.value) {
            if (externalIdEl) externalIdEl.value = '';
            setSenderFieldsReadonly(false);
            return;
        }
        if (externalIdEl) externalIdEl.value = selected.value;
        const addressStr = selected.getAttribute('data-address');
        if (!addressStr) return;
        try {
            const addr = JSON.parse(addressStr);
            const fullName = [addr.firstname || '', addr.surname || ''].filter(Boolean).join(' ').trim();
            const streetPart = (addr.street || '').trim();
            let street = streetPart;
            let buildingNumber = '1';
            const streetMatch = streetPart.match(/^(\d+[a-zA-Z]?)\s*(.*)$/);
            if (streetMatch) {
                buildingNumber = streetMatch[1];
                street = streetMatch[2].trim() || streetPart;
            }
            document.getElementById('company_name').value = addr.company || '';
            document.getElementById('full_name').value = fullName;
            const addressType = (addr.company || '').trim() ? 'company' : 'home';
            if (typeof selectButtonComboboxByGroupAndValue === 'function') {
                selectButtonComboboxByGroupAndValue('sender-address-type', addressType);
            }
            document.getElementById('street').value = street;
            document.getElementById('building_number').value = buildingNumber;
            document.getElementById('apartment_number').value = addr.flat || addr.apartment || '';
            document.getElementById('postal_code').value = addr.zip || '';
            document.getElementById('city').value = addr.city || '';
            document.getElementById('country').value = addr.country || '';
            document.getElementById('phone_number').value = addr.phone || '';
            document.getElementById('email').value = addr.email || '';
            document.getElementById('bank_account_number').value = '';
            const bankCodeEl = document.getElementById('bank_code');
            if (bankCodeEl) bankCodeEl.value = '';
            setSenderFieldsReadonly(true);
        } catch (e) {}
    }

    function getSenderFormData() {
        const externalIdEl = document.getElementById('sender_external_id');
        return {
            id: document.getElementById('sender_template_id').value,
            external_id: externalIdEl ? externalIdEl.value : '',
            company_name: document.getElementById('company_name').value,
            full_name: document.getElementById('full_name').value,
            street: document.getElementById('street').value,
            building_number: document.getElementById('building_number').value,
            apartment_number: document.getElementById('apartment_number').value,
            block: document.getElementById('block') ? document.getElementById('block').value : '',
            entrance: document.getElementById('entrance') ? document.getElementById('entrance').value : '',
            floor: document.getElementById('floor') ? document.getElementById('floor').value : '',
            postal_code: document.getElementById('postal_code').value,
            city: document.getElementById('city').value,
            country: document.getElementById('country').value,
            phone_number: document.getElementById('phone_number').value,
            email: document.getElementById('email').value,
            bank_account_number: document.getElementById('bank_account_number').value,
            bank_code: document.getElementById('bank_code') ? document.getElementById('bank_code').value : '',
            additional_bank_account_number: document.getElementById('additional_bank_account_number') ? document.getElementById('additional_bank_account_number').value : '',
            address_type: document.getElementById('sender-address-type').value
        };
    }

    function saveSenderTemplate(data) {
        data = data || getSenderFormData();

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'save_sender_template',
                ...data,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal(typeof json.success === 'string' ? json.success : '{{ success_sender_template_saved|e('js') }}');
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_saving_template|e('js') }}');
            }
        });
    }

    function updateSenderTemplate(data) {
        data = data || getSenderFormData();

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'update_sender_template',
                ...data,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal(typeof json.success === 'string' ? json.success : '{{ success_sender_template_updated|e('js') }}');
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_updating_template|e('js') }}');
            }
        });
    }



    var currentModalAction = '';
    var currentModalType = '';

    function onTemplateSelect() {
        const templateSelect = document.getElementById('template_select');
        const selectedTemplateId = templateSelect.value;

        if (selectedTemplateId) {
            loadTemplateData(selectedTemplateId);
            document.getElementById('save-as-new-template-btn').style.display = 'inline-block';
            document.getElementById('update-shipping-template-btn').style.display = 'inline-block';
            document.getElementById('shipping_template_id').value = selectedTemplateId;
        } else {
            clearShippingForm();
            document.getElementById('save-as-new-template-btn').style.display = 'inline-block';
            document.getElementById('update-shipping-template-btn').style.display = 'none';
            document.getElementById('shipping_template_id').value = '';
        }
    }

    function shouldAutoFillPolandPackageTypeDimensions() {
        if ('{{ region|e('js') }}' !== 'poland') return false;
        const templateSelect = document.getElementById('template_select');
        if (!templateSelect) return true;
        return !templateSelect.value;
    }

    function applyPolandPackageTypeDimensions() {
        if (!shouldAutoFillPolandPackageTypeDimensions()) return;
        const packageTypeSelect = document.getElementById('package_type');
        if (!packageTypeSelect) return;

        const dimsMap = window.alsendoPolandPackageTypeDimensions || {};
        const dims = dimsMap[packageTypeSelect.value] || null;
        if (!dims) return;

        const mapFieldToInput = {
            length: 'length',
            width: 'width',
            height: 'height',
            weight: 'weight'
        };

        for (const [field, inputId] of Object.entries(mapFieldToInput)) {
            const el = document.getElementById(inputId);
            if (!el) continue;
            const v = dims[field];
            if (v === null || v === undefined) {
                el.value = '';
            } else {
                el.value = v;
            }
        }
    }

    function onSenderTemplateSelect() {
        const templateSelect = document.getElementById('sender_template_select');
        const selectedTemplateId = templateSelect.value;

        if (selectedTemplateId) {
            loadSenderTemplateData(selectedTemplateId);
            document.getElementById('save-as-new-sender-template-btn').style.display = 'inline-block';
            document.getElementById('update-sender-template-btn').style.display = 'inline-block';
            document.getElementById('sender_template_id').value = selectedTemplateId;
        } else {
            clearSenderForm();
            document.getElementById('save-as-new-sender-template-btn').style.display = 'inline-block';
            document.getElementById('update-sender-template-btn').style.display = 'none';
            document.getElementById('sender_template_id').value = '';
        }
    }

    function clearShippingForm() {
        const formFields = ['package_type', 'length', 'width', 'height', 'weight', 'cash_on_delivery', 'declared_value', 'shipment_content', 'default_content_custom_text'];

        formFields.forEach(field => {
            const element = document.getElementById(field);
            if (element) {
                if (field === 'package_type') {
                    if ('{{ region|e('js') }}' === 'poland') {
                        element.value = element.options && element.options.length ? element.options[0].value : '';
                    } else {
                        element.value = 'standard';
                    }
                } else {
                    element.value = '';
                }
            }
        });
        const nonStandardEl = document.getElementById('non_standard');
        if (nonStandardEl) nonStandardEl.checked = false;

        document.getElementById('selected_pickup_type').value = '';
        document.getElementById('set-shipment-template-main').disabled = true;

        document.querySelectorAll('.pickup-type-btn').forEach(btn => {
            btn.classList.remove('active');
            btn.style.border = '';
        });

        document.getElementById('shipment_content').dispatchEvent(new Event('change'));
        applyPolandPackageTypeDimensions();
    }

    function loadTemplateData(templateId) {
        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'get_shipping_settings_template_data',
                id: templateId,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    fillShippingForm(json.data);
                } else if (json.error) {
                    console.log('{{ text_error_prefix|e('js') }}: ' + json.error);
                    showInfoModal('{{ text_error_prefix|e('js') }}: ' + json.error);
                }
            },
            error: function(xhr, status, error) {
                console.log('{{ text_error_loading_template_data|e('js') }}');
                showInfoModal('{{ text_error_loading_template_data|e('js') }}');
            }
        });
    }

    function loadSenderTemplateData(templateId) {
        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'get_template_data',
                id: templateId,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    fillSenderForm(json.data);
                } else if (json.error) {
                    console.log('Error: ' + json.error);
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                console.log('Error loading template data');
                showInfoModal('{{ text_error_loading_template_data|e('js') }}');
            }
        });
    }

    function fillShippingForm(data) {
        const formFields = ['package_type', 'length', 'width', 'height', 'weight', 'cash_on_delivery', 'declared_value', 'shipment_content', 'default_content_custom_text'];

        formFields.forEach(field => {
            const element = document.getElementById(field);
            if (element && data[field] !== undefined) {
                element.value = data[field];
            }
        });
        const nonStandardEl = document.getElementById('non_standard');
        if (nonStandardEl) nonStandardEl.checked = !!(data.non_standard);

        document.getElementById('shipping_template_id').value = data.id;
        document.getElementById('set-shipment-template-main').disabled = (data.main === true);
        document.getElementById('shipment_content').dispatchEvent(new Event('change'));

        if (data.pickup_type) {
            selectPickupType(data.pickup_type);
        }
    }

    function showTemplateNameModal(type, action) {
        currentModalType = type;
        currentModalAction = action;
        const modal = document.getElementById('template-name-modal');
        const templateNameInput = document.getElementById('modal_template_name');

        if (action === 'update') {
            if (type === 'shipping') {
                const selectedOption = document.getElementById('template_select').selectedOptions[0];
                if (selectedOption) {
                    templateNameInput.value = selectedOption.text;
                }
            } else if (type === 'sender') {
                const companyNameInput = document.getElementById('company_name');
                if (companyNameInput) {
                    templateNameInput.value = companyNameInput.value;
                }
            }
        } else {
            templateNameInput.value = '';
        }

        modal.style.display = 'block';
    }

    function setMainTemplate(type) {
        const ids = {
            sender: { el: 'sender_template_select', action: 'set_template_as_main' },
            shipping: { el: 'template_select', action: 'set_shipping_settings_template_as_main' }
        };
        const conf = ids[type];
        if (!conf) return;
        const selectedTemplate = document.getElementById(conf.el).value;
        if (!selectedTemplate) return;

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: { action: conf.action, id: selectedTemplate, user_token: '{{ user_token|e('js') }}' },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal(typeof json.success === 'string' ? json.success : '{{ success_template_set_as_main|e('js') }}');
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function() {
                showInfoModal('{{ text_error_setting_template_main|e('js') }}');
            }
        });
    }


    function hideTemplateNameModal() {
        document.getElementById('template-name-modal').style.display = 'none';
        currentModalAction = '';
    }

    function saveTemplateFromModal() {
        const templateName = document.getElementById('modal_template_name').value.trim();

        if (!templateName) {
            showInfoModal('{{ text_please_enter_template_name|e('js') }}');
            return;
        }

        if (currentModalType === 'shipping') {
            const data = getShippingFormData();
            data.name = templateName;

            if (currentModalAction === 'update') {
                updateShippingSettingsTemplate(data);
            } else {
                saveShippingSettingsTemplate(data);
            }
        } else if (currentModalType === 'sender') {
            const data = getSenderFormData();
            data.company_name = templateName;

            if (currentModalAction === 'update') {
                updateSenderTemplate(data);
            } else {
                saveSenderTemplate(data);
            }
        }

        hideTemplateNameModal();
    }

    function selectPickupType(pickupType) {
        document.querySelectorAll('.pickup-type-btn').forEach(btn => {
            btn.classList.remove('active');
            btn.style.border = '';
        });

        const selectedBtn = document.querySelector(`[data-value="${pickupType}"]`);
        if (selectedBtn) {
            selectedBtn.classList.add('active');
        }

        document.getElementById('selected_pickup_type').value = pickupType;
    }

    function getShippingFormData() {
        const nonStandardEl = document.getElementById('non_standard');
        return {
            id: document.getElementById('shipping_template_id').value,
            package_type: document.getElementById('package_type').value,
            length: document.getElementById('length').value,
            width: document.getElementById('width').value,
            height: document.getElementById('height').value,
            weight: document.getElementById('weight').value,
            cash_on_delivery: document.getElementById('cash_on_delivery').value,
            declared_value: document.getElementById('declared_value').value,
            shipment_content: document.getElementById('shipment_content').value,
            default_content_custom_text: document.getElementById('default_content_custom_text').value,
            pickup_type: document.getElementById('selected_pickup_type').value,
            non_standard: nonStandardEl ? (nonStandardEl.checked ? '1' : '0') : '0'
        };
    }

    function saveShippingSettingsTemplate(data) {
        data = data || getShippingFormData();

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'save_shipping_settings_template',
                ...data,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal('{{ success_shipping_template_saved|e('js') }}');
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_saving_template|e('js') }}');
            }
        });
    }

    function updateShippingSettingsTemplate(data) {
        data = data || getShippingFormData();

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'update_shipping_settings_template',
                ...data,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal('{{ success_shipping_template_updated|e('js') }}');
                } else if (json.error) {
                    showInfoModal(json.error);
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_updating_template|e('js') }}');
            }
        });
    }

    function saveAdditionalSettings() {
        var pickupHourFrom = document.getElementById('pickup_hour_from').value;
        var pickupHourTo = document.getElementById('pickup_hour_to').value;

        if (pickupHourFrom && pickupHourTo) {
            var from = new Date('2000-01-01 ' + pickupHourFrom);
            var to = new Date('2000-01-01 ' + pickupHourTo);

            if (from >= to) {
                showInfoModal('{{ error_pickup_hour_order|e('js') }}');
                return;
            }

            var diffHours = (to - from) / (1000 * 60 * 60);
            if (diffHours < 2) {
                showInfoModal('{{ error_pickup_hour_range|e('js') }}');
                return;
            }
        }

        var autoDeclaredValue = document.getElementById('auto_declared_value');
        var samedayDispatch = document.getElementById('sameday_dispatch');

        var data = {
            action: 'save_additional_settings',
            pickup_hour_from: pickupHourFrom,
            pickup_hour_to: pickupHourTo,
            user_token: '{{ user_token|e('js') }}',
            ...(autoDeclaredValue ? { auto_declared_value: autoDeclaredValue.checked ? 1 : 0 } : {}),
            ...(samedayDispatch ? { sameday_dispatch: samedayDispatch.checked ? 1 : 0 } : {})
        };

        var elements = {
            inpost_default_point: 'inpost_point',
            dhl_default_point: 'dhl_point',
            poczta_polska_default_point: 'poczta_polska_point',
            dpd_default_point: 'dpd_point',
            ups_default_point: 'ups_point',
            balikovna_default_point: 'balikovna_point', 
            gls_default_point: 'gls_point',
            ppl_default_point: 'ppl_point',
            zasilkovna_default_point: 'zasilkovna_point',
            sameday_default_point: 'sameday_point',
            fan_courier_default_point: 'fan_courier_point',
            cargus_default_point: 'cargus_point'
        };

        for (var key in elements) {
            var el = document.getElementById(elements[key]);
            if (el) {
                data[key] = el.value || '';
            }
        }

        console.log('Sending data:', data);

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal('{{ success_additional_settings_saved|e('js') }}');
                } else if (json.error) {
                    if (json.error === 'pickup_hour_from_must_be_earlier') {
                        showInfoModal('{{ error_pickup_hour_order|e('js') }}');
                    } else if (json.error === 'pickup_hour_range_too_small') {
                        showInfoModal('{{ error_pickup_hour_range|e('js') }}');
                    } else {
                        showInfoModal('{{ text_error_prefix|e('js') }}: ' + json.error);
                    }
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_saving_settings|e('js') }}');
            }
        });
    }

    function displayShippingMethods(methods) {
        const tbody = document.getElementById('shipping-methods-tbody');
        const tableContainer = document.getElementById('shipping-methods-table-container');
        const noMethodsDiv = document.getElementById('no-shipping-methods');

        tbody.innerHTML = '';

        if (methods.length === 0) {
            tableContainer.style.display = 'none';
            noMethodsDiv.style.display = 'block';
            return;
        }

        noMethodsDiv.style.display = 'none';
        tableContainer.style.display = 'block';

        methods.forEach(function(method) {
            const row = tbody.insertRow();

            // Shipping method name (editable)
            const nameCell = row.insertCell(0);
            nameCell.innerHTML = '<input type="text" class="form-control shipping-method-name" data-service-id="' + method.service_id + '" value="' + (method.custom_name || method.name) + '">';

            // Courier service (readonly)
            const serviceCell = row.insertCell(1);
            serviceCell.innerHTML = method.name;

            // Price (editable with PLN)
            const priceCell = row.insertCell(2);
            const priceValue = method.price || '';
            priceCell.innerHTML = '<div class="input-group"><input type="number" step="0.01" min="0" class="form-control shipping-method-price" data-service-id="' + method.service_id + '" value="' + priceValue + '"><span class="input-group-text">{{ text_pln_currency }}</span></div>';

            // Map (readonly checkbox)
            const mapCell = row.insertCell(3);
            mapCell.innerHTML = '<input type="checkbox" class="form-check-input" ' + (method.has_map ? 'checked' : '') + ' disabled>';

            // Remove button
            const actionCell = row.insertCell(4);
            actionCell.innerHTML = '<button type="button" class="btn btn-sm btn-danger" onclick="removeShippingMethod(\'' + method.service_id + '\')" title="{{ text_remove_shipping_method }}"><i class="fas fa-times"></i></button>';
        });
    }

    function updateShippingMethod(serviceId, customName, price) {
        const data = {
            action: 'update_shipping_method',
            service_id: serviceId,
            user_token: '{{ user_token|e('js') }}'
        };

        if (customName !== null) {
            data.custom_name = customName;
        }
        if (price !== null) {
            data.price = price;
        }

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(json) {
                if (!json.success) {
                    showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
                    console.log('Error: ' + (json.error || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.log('Error updating shipping method: ' + error);
            }
        });
    }

    function saveAllShippingMethods() {
        const nameInputs = document.querySelectorAll('.shipping-method-name');
        const priceInputs = document.querySelectorAll('.shipping-method-price');
        const methods = [];

        nameInputs.forEach(function(nameInput) {
            const serviceId = nameInput.getAttribute('data-service-id');
            const customName = nameInput.value.trim();
            const priceInput = document.querySelector('.shipping-method-price[data-service-id="' + serviceId + '"]');
            const price = priceInput ? priceInput.value : '';

            if (serviceId && customName) {
                methods.push({
                    service_id: serviceId,
                    custom_name: customName,
                    price: price
                });
            }
        });

        if (methods.length === 0) {
            console.log('No shipping methods to save');
            return;
        }

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'save_all_shipping_methods',
                methods: methods,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    showInfoModal('{{ success_shipping_methods_saved|e('js') }}');
                } else {
                    showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
            }
        });
    }

    function removeShippingMethod(serviceId) {
        if (confirm('{{ text_confirm_remove_shipping_method|e('js') }}')) {
            $.ajax({
                url: window.location.href,
                type: 'POST',
                data: {
                    action: 'remove_shipping_method',
                    service_id: serviceId,
                    user_token: '{{ user_token|e('js') }}'
                },
                dataType: 'json',
                success: function(json) {
                    if (json.success) {
                        showInfoModal('{{ success_shipping_method_removed|e('js') }}');
                    } else {
                        showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
                    }
                },
                error: function(xhr, status, error) {
                    showInfoModal('{{ text_error_saving_shipping_methods|e('js') }}');
                }
            });
        }
    }


    function showAddShippingMethodModal() {
        document.getElementById('add-shipping-method-modal').style.display = 'block';
        document.getElementById('services-loading').style.display = 'block';
        document.getElementById('services-selection').style.display = 'none';

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'get_all_services_for_selection',
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                document.getElementById('services-loading').style.display = 'none';

                if (json.success) {
                    displayServicesForSelection(json.services);
                    document.getElementById('services-selection').style.display = 'block';
                } else {
                    console.log('Error loading services: ' + (json.error || 'Unknown error'));
                    showInfoModal('{{ text_error_loading_services|e('js') }}: ' + (json.error || '{{ text_unknown_error|e('js') }}'));
                }
            },
            error: function(xhr, status, error) {
                document.getElementById('services-loading').style.display = 'none';
                console.log('Error loading services: ' + error);
            }
        });
    }

    function displayServicesForSelection(services) {
        const tbody = document.getElementById('services-selection-tbody');
        tbody.innerHTML = '';

        services.forEach(function(service) {
            const row = tbody.insertRow();

            // Service name
            const nameCell = row.insertCell(0);
            nameCell.innerHTML = service.name;

            // Map
            const mapCell = row.insertCell(1);
            mapCell.innerHTML = '<input type="checkbox" class="form-check-input" ' + (service.has_map ? 'checked' : '') + ' disabled>';

            // Active
            const activeCell = row.insertCell(2);
            activeCell.innerHTML = '<input type="checkbox" class="form-check-input service-checkbox" value="' + service.service_id + '" ' + (service.is_selected ? 'checked' : '') + '>';
        });
    }

    function hideAddShippingMethodModal() {
        document.getElementById('add-shipping-method-modal').style.display = 'none';
    }

    function saveServiceSelection() {
        const checkboxes = document.querySelectorAll('.service-checkbox:checked');
        const selectedServiceIds = Array.from(checkboxes).map(cb => cb.value);

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                action: 'save_service_selection',
                selected_service_ids: selectedServiceIds,
                user_token: '{{ user_token|e('js') }}'
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    hideAddShippingMethodModal();
                    showInfoModal('{{ success_service_selection_saved|e('js') }}');
                } else {
                    showInfoModal((json.error || '{{ text_unknown_error|e('js') }}'));
                }
            },
            error: function(xhr, status, error) {
                showInfoModal('{{ text_error_saving_settings|e('js') }}');
            }
        });
    }

    document.addEventListener('click', function(e) {
        var el = e.target;
        var btn = (el && el.id === 'hide-info-modal') ? el : (el && el.closest && el.closest('#hide-info-modal'));
        if (btn) {
            sessionStorage.setItem('alsendoScrollY', window.scrollY);
            location.reload();
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        var savedScroll = sessionStorage.getItem('alsendoScrollY');
        if (savedScroll !== null) {
            sessionStorage.removeItem('alsendoScrollY');
            window.scrollTo(0, parseInt(savedScroll, 10));
        }
        const regionSelect = document.getElementById('region-select');
        if (regionSelect) {
            regionSelect.addEventListener('change', onRegionChange);
        }

        const senderTemplateSelect = document.getElementById('sender_template_select');
        if (senderTemplateSelect && senderTemplateSelect.value) {
            onSenderTemplateSelect();
        }
        const addressBookSelect = document.getElementById('address_book_select');
        if (addressBookSelect && addressBookSelect.value) {
            onAddressBookSelect();
        }

        const shippingTemplateSelect = document.getElementById('template_select');
        if (shippingTemplateSelect && shippingTemplateSelect.value) {
            onTemplateSelect();
        }

        const packageTypeSelect = document.getElementById('package_type');
        if (packageTypeSelect) {
            packageTypeSelect.addEventListener('change', function() {
                applyPolandPackageTypeDimensions();
            });
        }

        applyPolandPackageTypeDimensions();

        document.getElementById('shipment_content').addEventListener('change', function () {
            const container = document.querySelector('.shipment-content-custom-text-container');
            if (this.value === 'custom_text') {
                container.style.display = 'block';
            } else {
                container.style.display = 'none';
            }
        });

        const ecoletAuthorizeBtn = document.getElementById('ecolet-authorize-btn');
        if (ecoletAuthorizeBtn) {
            ecoletAuthorizeBtn.addEventListener('click', function() {
                var roClientId = document.getElementById('ro-client-id');
                var roClientSecret = document.getElementById('ro-client-secret');
                var roSandbox = document.getElementById('ro-sandbox');
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    data: {
                        action: 'ecolet_authorize_url',
                        user_token: '{{ user_token|e('js') }}',
                        ro_client_id: roClientId ? roClientId.value : '',
                        ro_client_secret: roClientSecret ? roClientSecret.value : '',
                        ro_sandbox: roSandbox && roSandbox.checked ? '1' : ''
                    },
                    dataType: 'json',
                    success: function(json) {
                        if (json.error) {
                            showInfoModal(json.error);
                        } else if (json.url) {
                            window.open(json.url, '_blank');
                        }
                    },
                    error: function() {
                        showInfoModal('{{ error_saving_region|e('js') }}');
                    }
                });
            });
        }
    });

</script>
{{ footer }}
