{{ header }}{{ column_left }}

{% set order_details = order_details|default({}) %}
{% set sender = order_details.sender|default({}) %}
{% set shippingAddress = order_details.shippingAddress|default({}) %}
{% set packageDetails = order_details.packageDetails|default({}) %}
{% set shipment = order_details.shipment|default({}) %}

{% set is_any_service = not order_info.shipping_method.alsendo_service_id|default(false) %}

<div id="content">
    <input type="hidden" id="error-pickup-hour-range" value="{{ error_pickup_hour_range }}">
    <input type="hidden" id="error-pickup-date-past" value="{{ error_choose_preferred_pickup_date_not_past }}">

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

    <div class="container-fluid">
        <div class="card">
            <div class="card-header">
                <h3>{{ text_order_details }}</h3>
            </div>
            <div class="card-body">
                <form id="alsendo-order-form" method="post">
                    
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>{{ text_sender_address }}</h5>
                        </div>
                        <div class="card-body">
                            {% if current_region == 'czechia' %}
                            <input type="hidden" name="sender_external_id" id="sender-external-id" value="{{ sender.externalId|default('') }}">
                                {% if address_book_list is defined and address_book_list|length > 0 %}
                                <div class="row mb-3">
                                    <div class="col-md-12">
                                        <label for="sender-address-book-select" class="form-label">{{ text_address_from_address_book }}</label>
                                        <select id="sender-address-book-select" class="form-control" onchange="onOrderFormAddressBookSelect()">
                                            <option value="">{{ text_dropdown_select_default_option }}</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|default('')) == (id|default('')) %}selected{% endif %}>{{ address.firstname|default('') }} {{ address.surname|default('') }}{% if address.street|default('') %} - {{ address.street }}{% endif %}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                {% endif %}
                            {% endif %}

                            {% if sender_address_templates is defined and sender_address_templates|length > 0 %}
                            {% set sender_template_id_preselect = sender.sender_template_id|default(sender.senderTemplateId|default(null)) %}
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="sender-address-template-select" class="form-label">{{ text_sender_address_template }}</label>
                                    <select id="sender-address-template-select" class="form-control" name="sender_template_id">
                                        <option value="">-</option>
                                        {% for template in sender_address_templates %}
                                            <option value="{{ template.id }}" {% if sender_template_id_preselect is not null and sender_template_id_preselect != 0 and sender_template_id_preselect == template.id %}selected{% endif %}>{{ template.company_name|default(template.full_name)|default('')|default('Template' ~ template.id) }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                            {% endif %}

                            <div class="row mb-3" id="sender-address-type-container">
                                <div class="col-md-12">
                                    <label class="form-label">{{ text_address_type }}</label>
                                    <div class="btn-group w-100" role="group">
                                        <button
                                                type="button"
                                                class="btn btn-outline-secondary combobox-btn {% if (sender.addressType|default('')) == 'company' %}active{% endif %}"
                                                data-group="sender-address-type"
                                                data-value="company"
                                                data-on-select-show-element="company_name_container">
                                            {{ text_company }}
                                        </button>
                                        <button
                                                type="button"
                                                class="btn btn-outline-secondary combobox-btn {% if (sender.addressType|default('')) == 'home' %}active{% endif %}"
                                                data-group="sender-address-type"
                                                data-value="home"
                                                data-on-select-hide-element="company_name_container">
                                            {{ text_home_address_type }}
                                        </button>
                                    </div>
                                    <input type="hidden" name="sender_address_type" id="sender-address-type" value="{{ sender.addressType|default('') }}">
                                </div>
                            </div>
                            
                            <div class="row mb-3" id="company_name_container">
                                <div class="col-md-12">
                                    <label for="sender-company-name" class="form-label">{{ text_company_name }}</label>
                                    <input type="text" class="form-control" id="sender-company-name" name="sender_company_name" value="{{ sender.companyName|default('') }}">
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="sender-full-name" class="form-label">{{ text_full_name }}</label>
                                    <input type="text" class="form-control" id="sender-full-name" name="sender_full_name" value="{{ sender.fullName|default('') }}">
                                </div>
                            </div>
                            
                            {% if current_region == 'romania' %}
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="sender-street" class="form-label">{{ text_street }}</label>
                                    <input type="text" class="form-control" id="sender-street" name="sender_street" value="{{ sender.street|default('') }}">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="sender-house-number" class="form-label">{{ text_house_number }}</label>
                                    <input type="text" class="form-control" id="sender-house-number" name="sender_house_number" value="{{ sender.houseNumber|default('') }}">
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-3 mb-2">
                                    <label for="sender-block" class="form-label">{{ text_address_block }}</label>
                                    <input type="text" class="form-control" id="sender-block" name="sender_block" value="{{ sender.block|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="sender-entrance" class="form-label">{{ text_address_entrance }}</label>
                                    <input type="text" class="form-control" id="sender-entrance" name="sender_entrance" value="{{ sender.entrance|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="sender-floor" class="form-label">{{ text_address_floor }}</label>
                                    <input type="text" class="form-control" id="sender-floor" name="sender_floor" value="{{ sender.floor|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="sender-apartment-number" class="form-label">{{ text_apartment_number }}</label>
                                    <input type="text" class="form-control" id="sender-apartment-number" name="sender_apartment_number" value="{{ sender.apartmentNumber|default('') }}">
                                </div>
                            </div>
                            {% else %}
                            <div class="row mb-3">
                                <div class="col-md-4 mb-2">
                                    <label for="sender-street" class="form-label">{{ text_street }}</label>
                                    <input type="text" class="form-control" id="sender-street" name="sender_street" value="{{ sender.street|default('') }}">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="sender-house-number" class="form-label">{{ text_house_number }}</label>
                                    <input type="text" class="form-control" id="sender-house-number" name="sender_house_number" value="{{ sender.houseNumber|default('') }}">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="sender-apartment-number" class="form-label">{{ text_apartment_number }}</label>
                                    <input type="text" class="form-control" id="sender-apartment-number" name="sender_apartment_number" value="{{ sender.apartmentNumber|default('') }}">
                                </div>
                            </div>
                            {% endif %}

                            <div class="row mb-3">
                                <div class="col-md-4 mb-2">
                                    <label for="sender-country" class="form-label">{{ text_country }}</label>
                                    <select class="form-control" id="sender-country" name="sender_country">
                                        <option value="">--</option>
                                        {% for iso, name in countries %}
                                            <option value="{{ iso }}" {% if (sender.country|default('')) == iso %}selected{% endif %}>{{ name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="sender-postal-code" class="form-label">{{ text_postal_code }}</label>
                                    <input type="text" class="form-control" id="sender-postal-code" name="sender_postal_code" value="{{ sender.postalCode|default('') }}">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="sender-city" class="form-label">{{ text_city }}</label>
                                    <input type="text" class="form-control" id="sender-city" name="sender_city" value="{{ sender.city|default('') }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="sender-phone-number" class="form-label">{{ text_phone_number }}</label>
                                    <input type="text" class="form-control" id="sender-phone-number" name="sender_phone_number" value="{{ sender.phoneNumber|default('') }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="sender-email" class="form-label">{{ text_email }}</label>
                                    <input type="text" class="form-control" id="sender-email" name="sender_email" value="{{ sender.email|default('') }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="sender-bank-account-number" class="form-label">{{ text_bank_account_number }}</label>
                                    <input type="text" class="form-control" id="sender-bank-account-number" name="sender_bank_account_number" value="{{ sender.bankAccountNumber|default('') }}">
                                </div>
                                {% if current_region == 'czechia' %}
                                <div class="col-md-6 mb-2">
                                    <label for="sender-bank-code" class="form-label">{{ text_bank_code }}</label>
                                    <input type="text" class="form-control" id="sender-bank-code" name="sender_bank_code" value="{{ sender.bankCode|default('') }}">
                                </div>
                                {% endif %}
                            </div>
                            {% if current_region == 'czechia' %}
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="sender-additional-bank-account-number" class="form-label">{{ text_iban_bank_account_number }}</label>
                                    <input type="text" class="form-control" id="sender-additional-bank-account-number" name="sender_additional_bank_account_number" value="{{ sender.additionalBankAccountNumber|default('') }}">
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>{{ text_shipping_address }}</h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">{{ text_address_type }}</label>
                                    <div class="btn-group w-100" role="group">
                                        {% set shipping_address_type = shippingAddress.addressType|default('home') %}
                                        <button
                                                type="button"
                                                class="btn btn-outline-secondary combobox-btn {% if shipping_address_type == 'company' %}active{% endif %}"
                                                data-group="shipping-address-type"
                                                data-value="company"
                                                data-on-select-show-element="shipping-company-row">
                                            {{ text_company }}
                                        </button>
                                        <button
                                                type="button"
                                                class="btn btn-outline-secondary combobox-btn {% if shipping_address_type == 'home' %}active{% endif %}"
                                                data-group="shipping-address-type"
                                                data-value="home"
                                                data-on-select-hide-element="shipping-company-row">
                                            {{ text_home_address_type }}
                                        </button>
                                    </div>
                                    <input type="hidden" name="shipping_address_type" id="shipping-address-type" value="{{ shipping_address_type }}">
                                </div>
                            </div>
                            
                            <div class="row mb-3" id="shipping-company-row" {% if shipping_address_type == 'home' %}style="display: none;"{% endif %}>
                                <div class="col-md-12">
                                    <label for="shipping-company-name" class="form-label">{{ text_company_name }}</label>
                                    <input type="text" class="form-control" id="shipping-company-name" name="shipping_company_name" value="{{ shippingAddress.companyName|default(order_info.shipping_company) }}">
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-first-name" class="form-label">{{ text_first_name }}</label>
                                    <input type="text" class="form-control" id="shipping-first-name" name="shipping_first_name" value="{{ order_info.shipping_firstname }}">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-last-name" class="form-label">{{ text_last_name }}</label>
                                    <input type="text" class="form-control" id="shipping-last-name" name="shipping_last_name" value="{{ order_info.shipping_lastname }}">
                                </div>
                            </div>


                            {% if current_region == 'romania' %}
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-street" class="form-label">{{ text_street }}</label>
                                    <input type="text" class="form-control" id="shipping-street" name="shipping_street" value="{{ shippingAddress.street|default(order_info.shipping_address_1) }}">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-number" class="form-label">{{ text_address_number }}</label>
                                    <input type="text" class="form-control" id="shipping-number" name="shipping_number" value="{{ shippingAddress.houseNumber|default('') }}">
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-3 mb-2">
                                    <label for="shipping-block" class="form-label">{{ text_address_block }}</label>
                                    <input type="text" class="form-control" id="shipping-block" name="shipping_block" value="{{ shippingAddress.block|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="shipping-entrance" class="form-label">{{ text_address_entrance }}</label>
                                    <input type="text" class="form-control" id="shipping-entrance" name="shipping_entrance" value="{{ shippingAddress.entrance|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="shipping-floor" class="form-label">{{ text_address_floor }}</label>
                                    <input type="text" class="form-control" id="shipping-floor" name="shipping_floor" value="{{ shippingAddress.floor|default('') }}">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="shipping-apartment" class="form-label">{{ text_apartment_number }}</label>
                                    <input type="text" class="form-control" id="shipping-apartment" name="shipping_apartment" value="{{ shippingAddress.apartmentNumber|default(order_info.shipping_address_2) }}">
                                </div>
                            </div>
                            {% else %}
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-address-one" class="form-label">{{ text_address_one }}</label>
                                    <input type="text" class="form-control" id="shipping-street" name="shipping_address_one" value="{{ shippingAddress.street|default(order_info.shipping_address_1) }}">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="shipping-address-two" class="form-label">{{ text_address_two }}</label>
                                    <input type="text" class="form-control" id="shipping-address-two" name="shipping_address_two" value="{{ shippingAddress.apartmentNumber|default(order_info.shipping_address_2) }}">
                                </div>
                            </div>
                            {% endif %}


                            <div class="row mb-3">
                                <div class="col-md-4 mb-2">
                                    <label for="shipping-country" class="form-label">{{ text_country }}</label>
                                    <select class="form-control" id="shipping-country" name="shipping_country">
                                        <option value="">--</option>
                                        {% for iso, name in countries %}
                                            <option value="{{ iso }}" {% if (shippingAddress.getCountryIsoCode()|default(order_info.shipping_iso_code_2)) == iso %}selected{% endif %}>{{ name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="shipping-postal-code" class="form-label">{{ text_postal_code }}</label>
                                    <input type="text" class="form-control" id="shipping-postal-code" name="shipping_postal_code" value="{{ shippingAddress.postalCode|default(order_info.shipping_postcode) }}">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="shipping-city" class="form-label">{{ text_city }}</label>
                                    <input type="text" class="form-control" id="shipping-city" name="shipping_city" value="{{ shippingAddress.city|default(order_info.shipping_city) }}">
                                </div>
                            </div>


                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="shipping-phone-number" class="form-label">{{ text_phone_number }}</label>
                                    <input type="text" class="form-control" id="shipping-phone-number" name="shipping_phone_number" value="{{ shippingAddress.phoneNumber|default(order_info.telephone) }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="shipping-email" class="form-label">{{ text_email }}</label>
                                    <input type="text" class="form-control" id="shipping-email" name="shipping_email" value="{{ shippingAddress.email|default(order_info.email) }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="shipping-pickup-point-display" class="form-label">{{ text_delivery_point }}</label>
                                    <input
                                            data-map-selector="shipping-pickup-point"
                                            type="text"
                                            style="background-color: #f1f1f1;"
                                            class="form-control"
                                            id="shipping-pickup-point-display"
                                            name="shipping_pickup_point_display"
                                            readonly
                                            value="{{ order_details.shippingAddress.getDeliveryPointText() }}"
                                    >
                                    <input
                                            data-map-selector="shipping-pickup-point"
                                            type="hidden"
                                            name="shipping_pickup_point"
                                            id="shipping-pickup-point"
                                            value="{% if order_details.shippingAddress.deliveryPoint %}{{ order_details.shippingAddress.deliveryPoint|json_encode|e("html_attr") }}{% endif %}">
                                </div>
                                <div class="d-flex justify-content-end align-items-center gap-2">
                                    {% if order_details.shipment.shipmentPickupPoint is defined and order_details.shipment.shipmentPickupPoint is not null and order_details.shipment.shipmentPickupPoint != '' %}
                                    <button type="button" id="shipping-pickup-point-delete-btn" class="btn btn-outline-danger btn-sm">{{ text_delete_pickup_point }}</button>
                                    {% endif %}
                                    {% set has_service = order_details.shipment.serviceId is defined and order_details.shipment.externalServiceId is defined and map_operators_by_service_id[order_details.shipment.externalServiceId] is defined %}
                                    {% set is_any_service = order_details.shipment.serviceId == '0' %}

                                    <p
                                            id="shipping-pickup-point-select-btn"
                                            {% if has_service %}
                                                data-map-operator="{{ map_operators_by_service_id[order_info.shipping_method.external_service_id] }}"
                                            {% endif %}
                                            style="cursor:pointer; color: #1e91cf; margin:0; {% if not has_service and not is_any_service %}display:none;{% endif %}"
                                            type="button"
                                    >
                                        {{ text_select_pickup_point_from_map }}
                                    </p>
                                </div>
                            </div>


                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>{{ text_package }}</h5>
                        </div>
                        <div class="card-body">
                            <div class="single-packages-section-container">
                                {% for package in (packageDetails.packages)|default([]) %}
                                    {% set pkg_index = loop.index0 %}
                                    <div class="single-package-container">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="package-header"></h5>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <label class="form-label">{{ text_package_template }}</label>
                                                <select class="form-control package-template" name="package_template_id[]">
                                                    <option value="">-</option>
                                                    {% for template in shipping_settings_templates %}
                                                        <option value="{{ template.id }}"
                                                                {% if package.templateId == template.id %}
                                                                    selected
                                                                {% endif %}
                                                        >{{ template.name }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-3 mb-2">
                                                <label class="form-label">{{ text_width }}</label>
                                                <div class="position-relative">
                                                    <input type="number" class="form-control package-width" name="package_width[]" value="{{ package.packageWidth|default('') }}" step="0.01">
                                                    <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-2">
                                                <label class="form-label">{{ text_length }}</label>
                                                <div class="position-relative">
                                                    <input type="number" class="form-control package-length" name="package_length[]" value="{{ package.packageLength|default('') }}" step="0.01">
                                                    <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-2">
                                                <label class="form-label">{{ text_height }}</label>
                                                <div class="position-relative">
                                                    <input type="number" class="form-control package-height" name="package_height[]" value="{{ package.packageHeight|default('') }}" step="0.01">
                                                    <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">cm</span>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-2">
                                                <label class="form-label">{{ text_weight }}</label>
                                                <div class="position-relative">
                                                    <input type="number" class="form-control package-weight" name="package_weight[]" value="{{ package.packageWeight|default('') }}" step="0.01">
                                                    <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">kg</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <label class="form-label">{% if current_region == 'romania' and romania_package_types is defined and romania_package_types|length > 0 %}{{ text_package_type }}{% elseif current_region == 'poland' and poland_package_types is defined and poland_package_types|length > 0 %}{{ text_package_type }}{% else %}{{ text_shipment_packaging_standard }}{% endif %}</label>
                                                {% if current_region == 'romania' and romania_package_types is defined and romania_package_types|length > 0 %}
                                                {% set package_type_ro = default_package_type_ro|default(romania_package_types[0].id) %}
                                                {% for pt in romania_package_types %}{% if package.packageShipmentPackaging == pt.id %}{% set package_type_ro = pt.id %}{% endif %}{% endfor %}
                                                <div class="btn-group w-100" role="group">
                                                    {% for pt in romania_package_types %}
                                                    <button type="button" class="btn btn-outline-secondary silent-change combobox-btn {% if package_type_ro == pt.id %}active{% endif %}"
                                                            data-group="package-shipment-packaging-{{ pkg_index }}" data-value="{{ pt.id }}">{{ pt.name }}</button>
                                                    {% endfor %}
                                                </div>
                                                <input type="hidden" class="package-shipment-packaging" id="package-shipment-packaging-{{ pkg_index }}" name="package_shipment_packaging[]" value="{{ package_type_ro }}">
                                                {% elseif current_region == 'poland' and poland_package_types is defined and poland_package_types|length > 0 %}
                                                {% set package_type_pl = default_package_type_pl|default(poland_package_types[0].id) %}
                                                {% for pt in poland_package_types %}{% if package.packageShipmentPackaging == pt.id %}{% set package_type_pl = pt.id %}{% endif %}{% endfor %}
                                                <select class="form-control package-shipment-packaging" name="package_shipment_packaging[]" id="package-shipment-packaging-{{ pkg_index }}">
                                                    {% for pt in poland_package_types %}
                                                    <option value="{{ pt.id }}" {% if package_type_pl == pt.id %}selected{% endif %}>{{ pt.name }}</option>
                                                    {% endfor %}
                                                </select>
                                                {% else %}
                                                {% set package_type = (package.packageShipmentPackaging|default('')) == 'standard' ? 'standard' : 'non-standard' %}
                                                <div class="btn-group w-100" role="group">
                                                    <button type="button" class="btn btn-outline-secondary silent-change combobox-btn {% if package_type == 'standard' %}active{% endif %}"
                                                            data-group="package-shipment-packaging-{{ pkg_index }}" data-value="standard">{{ text_shipment_packaging_standard }}</button>
                                                    <button type="button" class="btn btn-outline-secondary silent-change combobox-btn {% if package_type == 'non-standard' %}active{% endif %}"
                                                            data-group="package-shipment-packaging-{{ pkg_index }}" data-value="non-standard">{{ text_shipment_packaging_non_standard }}</button>
                                                </div>
                                                <input type="hidden" class="package-shipment-packaging" id="package-shipment-packaging-{{ pkg_index }}" name="package_shipment_packaging[]" value="{{ package_type }}">
                                                {% endif %}
                                            </div>
                                        </div>
                                        {% if current_region == 'romania' %}
                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <div class="form-check">
                                                    <input type="hidden" name="package_non_standard[{{ pkg_index }}]" value="0">
                                                    <input type="checkbox" class="form-check-input package-non-standard" name="package_non_standard[{{ pkg_index }}]" value="1"{% if package.nonStandard|default(false) %} checked{% endif %}>
                                                    <label class="form-check-label">{{ text_shipment_packaging_non_standard }}</label>
                                                </div>
                                            </div>
                                        </div>
                                        {% endif %}
                                    </div>
                                {% endfor %}
                            </div>

                            {% if current_region == 'poland' %}
                            <div class="mb-2 ml-0">
                                <button type="button" class="btn btn-link text-decoration-none add-another-package-button">+ {{ text_add_another_package }}</button>
                            </div>
                            {% endif %}

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="package-content" class="form-label">{{ text_package_content }}</label>
                                    <input type="text" class="form-control silent-change" id="package-content" name="package_content" value="{{ packageDetails.packageContent|default('') }}">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="package-cod" class="form-label">{{ text_cash_on_delivery }}</label>
                                    <div class="position-relative">
                                        <input type="number" class="form-control" id="package-cod" name="package_cod" value="{{ (packageDetails.codValue ? packageDetails.codValue.toFloat() : '')|default('') }}" step="0.01">
                                        <span class="position-absolute" style="right: 30px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;">{{ current_store_currency }}</span>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="package-declared-value" class="form-label">{{ text_declared_value }}</label>
                                    <div class="position-relative">
                                        <input type="number" class="form-control" id="package-declared-value" name="package_declared_value" value="{{ (packageDetails.declaredValue ? packageDetails.declaredValue.toFloat() : '')|default('') }}" step="0.01">
                                        <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="row mb-3">
                                <div class="col-12">
                                    <div class="form-group">
                                        <label class="form-label">{{ text_pickup_type }}</label>
                                        <div class="d-flex w-100 mt-2" style="gap:0.5em;">
                                            {% set count = pickup_types|length %}
                                            {% 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' or pickup_type == 'self' %}
                                                            data-on-select-show-element="shipment-pickup-point-container"
                                                        {% elseif pickup_type == 'COURIER' or pickup_type == 'courier' %}
                                                            data-on-select-hide-element="shipment-pickup-point-container"
                                                        {% else %}
                                                            data-on-select-hide-element="shipment-pickup-point-container"
                                                        {% endif %}
                                                        data-value="{{ pickup_type }}">
                                                    {{ pickup_type_labels[pickup_type] }}
                                                </button>
                                            {% endfor %}
                                        </div>
                                        <input type="hidden" id="selected_pickup_type" name="selected_pickup_type" value="{{ packageDetails.pickupType|default('') }}">
                                    </div>
                                </div>
                            </div>

                            {% if current_region == 'czechia' %}
                            <div class="row mb-3 d-none" id="ship-via-pickup-point-container" data-ship-via-pickup-point-allowed="{{ ship_via_pickup_point_allowed ? '1' : '0' }}">
                                <div class="col-12">
                                    <div class="form-check">
                                        <input type="hidden" name="ship_via_pickup_point" value="0">
                                        <input type="checkbox" class="form-check-input" id="ship_via_pickup_point" name="ship_via_pickup_point" value="1"{% if ship_via_pickup_point_allowed and packageDetails.shipViaPickupPoint|default(false) %} checked{% endif %}{% if not ship_via_pickup_point_allowed %} disabled{% endif %}>
                                        <label class="form-check-label" for="ship_via_pickup_point">{{ text_ship_via_pickup_point }}</label>
                                    </div>
                                </div>
                            </div>
                            <div class="row mb-3 d-none">
                                <div class="col-12">
                                    <div class="form-check">
                                        <input type="hidden" name="pickup_request" value="0">
                                        <input type="checkbox" class="form-check-input" id="pickup_request" name="pickup_request" value="1"{% if packageDetails.pickupRequest|default(false) %} checked{% endif %}>
                                        <label class="form-check-label" for="pickup_request">{{ text_pickup_request }}</label>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-header">
                            <h5>{{ text_shipment }}</h5>
                        </div>
                        <div class="card-body">
                            <p>{{ text_shipping_method }}: {{ order_info.shipping_method.name }}</p>


                            {% if order_info.shipping_method.alsendo_service_id %}
                            <p>{{ text_courier_service }}: {{ order_info.shipping_method.courier_service_name }}</p>
                            {% endif %}




                            <div id="get-a-quote-container" style="display:block;">
                                <p class="d-inline" style="margin-right: 0.6em;">{{ text_price }}: </p>
                                <button style="all:unset; cursor:pointer; color: #1e91cf" type="button" id="get-quote-button">{{ text_get_a_quote }}</button>
                            </div>

                            <div class="row mb-2 mt-2" id="courier-services-container" style="display: none;">
                                <div>
                                    <div id="courier-services-container-inner" style="display:flex;flex-wrap:wrap;gap:1em;">
                                    </div>

{#                                    {% if is_any_service == true %}#}
                                        <div class="row mb-4" id="shipment-preferred-pickup-date-container" style="display: none;">
                                            <div class="my-2">
                                                <div class="row align-items-end">
                                                    <div class="col-md-6">
                                                        <label for="shipment-preferred-pickup-date" class="form-label">{{ text_choose_preferred_pickup_date }}</label>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="shipment-preferred-pickup-hour-from" class="form-label">{{ text_choose_preferred_pickup_hours }}</label>
                                                    </div>
                                                </div>
                                                <div class="row align-items-end">
                                                    <div class="col-md-6">
                                                        <input type="date" class="form-control" id="shipment-preferred-pickup-date" name="shipment_preferred_pickup_date" value="{{ shipment.preferredPickupDate ? shipment.preferredPickupDate|date('Y-m-d') : 'now'|date('Y-m-d') }}">
                                                    </div>
                                                    {% set hours = 8..17 %}

                                                    {% set preferredHourFrom = shipment.preferredPickupHourFrom ?: default_pickup_hour_from %}
                                                    {% set preferredHourTo = shipment.preferredPickupHourTo ?: default_pickup_hour_to %}

                                                    <div class="col-md-2">
                                                        <select id="shipment-preferred-pickup-hour-from" name="shipment_preferred_pickup_hour_from" class="form-control">
                                                            {% for hour in hours %}
                                                                {% set formatted = '%02d:00'|format(hour) %}
                                                                <option value="{{ formatted }}" {% if formatted == preferredHourFrom %}selected{% endif %}>{{ formatted }}</option>
                                                            {% endfor %}
                                                        </select>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <select id="shipment-preferred-pickup-hour-to" name="shipment_preferred_pickup_hour_to" class="form-control">
                                                            {% for hour in hours %}
                                                                {% set formatted = '%02d:00'|format(hour) %}
                                                                <option value="{{ formatted }}" {% if formatted == preferredHourTo or ((preferredHourTo is not defined or preferredHourTo is empty) and loop.last) %}selected{% endif %}>{{ formatted }}</option>
                                                            {% endfor %}
                                                        </select>
                                                    </div>

                                                </div>
                                            </div>
                                        </div>
{#                                    {% endif %}#}
                                    <input type="hidden" id="shipment-selected-service" name="shipment_selected_service" value="{% if order_info.shipping_method.alsendo_service_id %}{{ order_info.shipping_method.alsendo_service_id }}{% endif %}">


                                </div>
                            </div>
                            <div class="row mb-4" id="shipment-pickup-point-container" style="display: none;">
                                <div>
                                    <div class="col-md-12">
                                        <label for="shipment-pickup-point-display" class="form-label">{{ text_shipping_point }}</label>
                                        <input
                                                data-map-selector="shipment-pickup-point"
                                                type="text"
                                                style="background-color: #f1f1f1;"
                                                class="form-control"
                                                id="shipment-pickup-point-display"
                                                name="shipment_pickup_point_display"
                                                readonly
                                                value="{{ shipment.shipmentPickupPointDisplay|default('') }}"
                                        >
                                        <input
                                            data-map-selector="shipment-pickup-point"
                                            type="hidden"
                                            name="shipment_pickup_point"
                                            id="shipment-pickup-point"
                                            value="{% if shipment.shipmentPickupPoint %}{{ shipment.shipmentPickupPoint|json_encode|e("html_attr") }}{% endif %}"
                                        >
                                    </div>
                                    <div class="text-end">
                                        <button
                                                id="shipment-pickup-point-select-btn"
                                                data-map-operator="{{ sender_dropoff_map_operator|default('') }}"
                                                style="all:unset; cursor:pointer; color: #1e91cf"
                                                type="button"
                                        >{{ text_select_pickup_point_from_map }}</button>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 text-end">
                                    <input type="hidden" value="{{ order_id }}" name="order_id" id="order-id">
                                    <button type="button" class="btn btn-link text-decoration-none" id="save-order-details-btn">{{ text_save_order_details }}</button>
                                    <button type="submit" class="btn btn-primary" id="order-shipment-btn">{{ button_order_shipment }}</button>
                                </div>
                            </div>
                        </div>
                    </div>

                <input type="hidden" id="initial-service-id" value="{{ shipment.serviceId|default('') }}" form="none">
                <input type="hidden" id="user-token" value="{{ user_token }}" form="none">
                </form>
            </div>
        </div>
    </div>
</div>

<script>
window.alsendoMapConfig = {{ map_config_json|raw }};
var CURRENT_REGION = '{{ current_region|default('')|e('js') }}';
var ALSENDO_AUTO_DECLARED_VALUE = {{ auto_declared_value ? 'true' : 'false' }};
var ALSENDO_ORDER_TOTAL = {{ order_total|default(0) }};
var ALSENDO_TEXT_PRICE_NA = "{{ text_price_na|default('Price N/A')|e('js') }}";
var ALSENDO_TEXT_NO_QUOTE_AVAILABLE = "{{ text_no_quote_available_for_order_parameters|e('js') }}";

function setOrderFormSenderFieldsReadonly(readonly) {
    var readonlyIds = ['sender-company-name', 'sender-full-name', 'sender-street', 'sender-house-number', 'sender-apartment-number', 'sender-block', 'sender-entrance', 'sender-floor', 'sender-postal-code', 'sender-city', 'sender-phone-number', 'sender-email'];
    var bgColor = '#e9ecef';
    readonlyIds.forEach(function(id) {
        var el = document.getElementById(id);
        if (el) {
            el.readOnly = readonly;
            el.style.backgroundColor = readonly ? bgColor : '';
        }
    });
    var countryEl = document.getElementById('sender-country');
    if (countryEl) {
        countryEl.disabled = readonly;
        countryEl.style.backgroundColor = readonly ? bgColor : '';
    }
    var bankEl = document.getElementById('sender-bank-account-number');
    if (bankEl) {
        bankEl.readOnly = false;
        bankEl.style.backgroundColor = '';
    }
    var bankCodeEl = document.getElementById('sender-bank-code');
    if (bankCodeEl) {
        bankCodeEl.readOnly = false;
        bankCodeEl.style.backgroundColor = '';
    }
    var typeContainer = document.getElementById('sender-address-type-container');
    if (typeContainer) {
        typeContainer.style.display = readonly ? 'none' : '';
    }
}

function handleSenderAddressTemplateChange() {
    var selectEl = document.getElementById('sender-address-template-select');
    if (!selectEl) return;
    var templateId = selectEl.value;
    if (!templateId) return;
    $.ajax({
        url: 'index.php?route=extension/alsendo/module/alsendo&user_token={{ user_token|e('js') }}',
        type: 'POST',
        data: { action: 'get_template_data', id: templateId, user_token: '{{ user_token|e('js') }}' },
        dataType: 'json',
        success: function(json) {
            if (json.success && json.data) {
                var d = json.data;
                var externalIdEl = document.getElementById('sender-external-id');
                if (externalIdEl) externalIdEl.value = '';
                document.getElementById('sender-company-name').value = d.company_name || '';
                document.getElementById('sender-full-name').value = d.full_name || '';
                document.getElementById('sender-street').value = d.street || '';
                document.getElementById('sender-house-number').value = d.building_number || '';
                document.getElementById('sender-apartment-number').value = d.apartment_number || '';
                var blockEl = document.getElementById('sender-block');
                if (blockEl) blockEl.value = d.block || '';
                var entranceEl = document.getElementById('sender-entrance');
                if (entranceEl) entranceEl.value = d.entrance || '';
                var floorEl = document.getElementById('sender-floor');
                if (floorEl) floorEl.value = d.floor || '';
                document.getElementById('sender-postal-code').value = d.postal_code || '';
                document.getElementById('sender-city').value = d.city || '';
                document.getElementById('sender-country').value = d.country || '';
                document.getElementById('sender-phone-number').value = d.phone_number || '';
                document.getElementById('sender-email').value = d.email || '';
                document.getElementById('sender-bank-account-number').value = d.bank_account_number || '';
                var bankCodeEl = document.getElementById('sender-bank-code');
                if (bankCodeEl) bankCodeEl.value = d.bank_code || '';
                var additionalBankEl = document.getElementById('sender-additional-bank-account-number');
                if (additionalBankEl) additionalBankEl.value = d.additional_bank_account_number || '';
                var addressType = (d.address_type || 'company') === 'company' ? 'company' : 'home';
                document.getElementById('sender-address-type').value = addressType;
                if (typeof selectButtonComboboxByGroupAndValue === 'function') {
                    selectButtonComboboxByGroupAndValue('sender-address-type', addressType);
                }
                var companyContainer = document.getElementById('company_name_container');
                if (companyContainer) companyContainer.style.display = addressType === 'company' ? '' : 'none';
                setOrderFormSenderFieldsReadonly(false);
            }
        }
    });
}

function onOrderFormAddressBookSelect() {
    var select = document.getElementById('sender-address-book-select');
    if (!select) return;
    var selected = select.options[select.selectedIndex];
    var externalIdEl = document.getElementById('sender-external-id');
    if (!selected || !selected.value) {
        if (externalIdEl) externalIdEl.value = '';
        setOrderFormSenderFieldsReadonly(false);
        return;
    }
    if (externalIdEl) externalIdEl.value = selected.value;
    var addressStr = selected.getAttribute('data-address');
    if (!addressStr) return;
    try {
        var addr = JSON.parse(addressStr);
        var fullName = [addr.firstname || '', addr.surname || ''].filter(Boolean).join(' ').trim();
        var streetPart = (addr.street || '').trim();
        var street = streetPart;
        var buildingNumber = '1';
        var streetMatch = streetPart.match(/^(\d+[a-zA-Z]?)\s*(.*)$/);
        if (streetMatch) {
            buildingNumber = streetMatch[1];
            street = streetMatch[2].trim() || streetPart;
        }
        document.getElementById('sender-company-name').value = addr.company || '';
        document.getElementById('sender-full-name').value = fullName;
        var addressType = (addr.company || '').trim() ? 'company' : 'home';
        if (typeof selectButtonComboboxByGroupAndValue === 'function') {
            selectButtonComboboxByGroupAndValue('sender-address-type', addressType);
        }
        document.getElementById('sender-street').value = street;
        document.getElementById('sender-house-number').value = buildingNumber;
        document.getElementById('sender-apartment-number').value = addr.flat || addr.apartment || '';
        document.getElementById('sender-postal-code').value = addr.zip || '';
        document.getElementById('sender-city').value = addr.city || '';
        document.getElementById('sender-country').value = addr.country || '';
        document.getElementById('sender-phone-number').value = addr.phone || '';
        document.getElementById('sender-email').value = addr.email || '';
        document.getElementById('sender-bank-account-number').value = '';
        var bankCodeEl = document.getElementById('sender-bank-code');
        if (bankCodeEl) bankCodeEl.value = '';
        setOrderFormSenderFieldsReadonly(true);
    } catch (e) {}
}

document.addEventListener('DOMContentLoaded', function() {
    var senderTemplateSelect = document.getElementById('sender-address-template-select');
    if (senderTemplateSelect) {
        senderTemplateSelect.addEventListener('change', handleSenderAddressTemplateChange);
        var senderFieldIds = ['sender-company-name', 'sender-full-name', 'sender-street', 'sender-house-number', 'sender-apartment-number', 'sender-block', 'sender-entrance', 'sender-floor', 'sender-postal-code', 'sender-city', 'sender-phone-number', 'sender-email', 'sender-bank-account-number', 'sender-bank-code', 'sender-additional-bank-account-number'];
        senderFieldIds.forEach(function(id) {
            var el = document.getElementById(id);
            if (el) el.addEventListener('input', function() { senderTemplateSelect.value = ''; });
        });
        var senderCountryEl = document.getElementById('sender-country');
        if (senderCountryEl) senderCountryEl.addEventListener('change', function() { senderTemplateSelect.value = ''; });
    }

    var hasExternalId = document.getElementById('sender-external-id') && document.getElementById('sender-external-id').value;
    if (hasExternalId) {
        setOrderFormSenderFieldsReadonly(true);
    }

    var shipViaPickupPointCheckbox = document.getElementById('ship_via_pickup_point');
    var pickupRequestCheckbox = document.getElementById('pickup_request');
    if (shipViaPickupPointCheckbox && pickupRequestCheckbox) {
        function updatePickupRequestState() {
            if (shipViaPickupPointCheckbox.checked) {
                pickupRequestCheckbox.checked = false;
                pickupRequestCheckbox.disabled = true;
            } else {
                pickupRequestCheckbox.disabled = false;
            }
        }
        shipViaPickupPointCheckbox.addEventListener('change', updatePickupRequestState);
        updatePickupRequestState();
    }

    var shippingPickupPointSelectButton = document.getElementById('shipping-pickup-point-select-btn');
    if (shippingPickupPointSelectButton) {
        shippingPickupPointSelectButton.addEventListener('click', function() {
            var mapOperator = shippingPickupPointSelectButton.getAttribute('data-map-operator');

            var cityEl = document.getElementById('shipping-city');
            var postalEl = document.getElementById('shipping-postal-code');
            var countryEl = document.getElementById('shipping-country');
            var city = cityEl && cityEl.value ? String(cityEl.value).trim() : '';
            var postalCode = postalEl && postalEl.value ? String(postalEl.value).trim() : '';
            var countryName = '';
            if (countryEl && typeof countryEl.selectedIndex === 'number' && countryEl.selectedIndex >= 0) {
                var selectedOption = countryEl.options[countryEl.selectedIndex];
                if (selectedOption) {
                    countryName = String(selectedOption.text || selectedOption.innerText || '').trim();
                }
            }
            var parts = [postalCode, countryName].filter(function(p) { return p !== ''; });
            var initialAddress = parts.length ? parts.join(' ') : '{{ region }}';

            if (mapOperator) {
                openPointMap('shipping-pickup-point', [mapOperator], 'DELIVERY', initialAddress);
            } else {
                openPointMap('shipping-pickup-point', [], 'DELIVERY', initialAddress);
            }
        });
    }
    var shipmentPickupPointSelectBtn = document.getElementById('shipment-pickup-point-select-btn');
    if (shipmentPickupPointSelectBtn) {
        shipmentPickupPointSelectBtn.addEventListener('click', function() {
            var mapOperator = this.getAttribute('data-map-operator');

            var cityEl = document.getElementById('sender-city');
            var postalEl = document.getElementById('sender-postal-code');
            var countryEl = document.getElementById('sender-country');
            var city = cityEl && cityEl.value ? String(cityEl.value).trim() : '';
            var postalCode = postalEl && postalEl.value ? String(postalEl.value).trim() : '';
            var countryName = '';
            if (countryEl && typeof countryEl.selectedIndex === 'number' && countryEl.selectedIndex >= 0) {
                var selectedOption = countryEl.options[countryEl.selectedIndex];
                if (selectedOption) {
                    countryName = String(selectedOption.text || selectedOption.innerText || '').trim();
                }
            }
            var parts = [postalCode, countryName].filter(function(p) { return p !== ''; });
            var initialAddress = parts.length ? parts.join(' ') : '{{ region }}';

            openPointMap('shipment-pickup-point', mapOperator ? [mapOperator] : null, 'POSTING', initialAddress);
        });
    }
    var deletePickupPointBtn = document.getElementById('shipping-pickup-point-delete-btn');
    if (deletePickupPointBtn) {
        deletePickupPointBtn.addEventListener('click', function() {
            showConfirmModal('{{ text_confirm_reset_pickup_point|e('js') }}', function() {
                $.ajax({
                    url: 'index.php?route=extension/alsendo/alsendo_order.resetPickupPoint&user_token={{ user_token|e('js') }}',
                    type: 'POST',
                    data: { order_id: {{ order_id }} },
                    dataType: 'json',
                    success: function(json) {
                        if (json.success) {
                            location.reload();
                        } else {
                            showInfoModal('{{ text_operation_not_successful|e('js') }}');
                        }
                    },
                    error: function() {
                        showInfoModal('{{ text_operation_not_successful|e('js') }}');
                    }
                });
            });
        });
    }

    function updatePreferredPickupDateVisibility() {
        const pickup = document.getElementById('selected_pickup_type');
        const innerContainer = document.getElementById('shipment-preferred-pickup-date-container');
        const outerContainer = document.getElementById('courier-services-container');
        if (!container) return;
        const isCourier = pickup?.value?.toUpperCase() === 'COURIER';
        const isRomania = typeof CURRENT_REGION !== 'undefined' && String(CURRENT_REGION).toLowerCase() === 'romania';
        const isPoland = typeof CURRENT_REGION !== 'undefined' && String(CURRENT_REGION).toLowerCase() === 'poland';
        innerContainer.style.display = (isCourier && (isRomania || isPoland)) ? 'block' : 'none';
        outerContainer.style.display = (isCourier && (isRomania || isPoland)) ? 'block' : 'none';
    }

    document.querySelectorAll('.pickup-type-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            updateShipmentContainersVisibility();
            setTimeout(updatePreferredPickupDateVisibility, 0);
        });
    });

    updatePreferredPickupDateVisibility();

    const btnGetQuote = document.getElementById('get-quote-button');
    if (btnGetQuote) {
        btnGetQuote.addEventListener('click', function () {
            setTimeout(updatePreferredPickupDateVisibility, 0);
        });
    }

});

function applyValidationErrors(formSelector, errorsObj) {
    var form = document.querySelector(formSelector);
    if (!form) return;
    form.querySelectorAll('.input-validation-error').forEach(function(input) { input.classList.remove('input-validation-error'); });
    form.querySelectorAll('small.validation-error-message').forEach(function(el) { el.remove(); });
    for (var field in errorsObj) {
        if (!errorsObj.hasOwnProperty(field)) continue;
        var message = errorsObj[field];
        var msgText = Array.isArray(message) ? (message[0] || '') : message;
        var input = form.querySelector('[name="' + field + '"]') || form.querySelector('#' + CSS.escape(field.replace(/_/g, '-')));
        if (input) {
            input.classList.add('input-validation-error');
            var errorEl = document.createElement('small');
            errorEl.classList.add('validation-error-message');
            errorEl.className += ' text-danger d-block';
            errorEl.textContent = msgText;
            input.insertAdjacentElement('afterend', errorEl);
        }
    }
}

function getOrderFormPayload() {
    const form = document.getElementById('alsendo-order-form');
    const formData = new FormData(form);
    const payload = {};
    for (const [key, value] of formData.entries()) {
        if (key.endsWith('[]')) {
            payload[key] = payload[key] || [];
            payload[key].push(value);
        } else {
            payload[key] = value;
        }
    }
    return payload;
}

const saveOrderDetailsButton = document.getElementById('save-order-details-btn');
if (saveOrderDetailsButton) {
    saveOrderDetailsButton.addEventListener('click', function () {
        saveOrderDetailsButton.disabled = true;
        const payload = getOrderFormPayload();

        $.ajax({
            url: 'index.php?route=extension/alsendo/alsendo_order.saveOrderDetails&user_token={{ user_token|e('js') }}',
            type: 'POST',
            data: payload,
            dataType: 'json',
            success: function (json) {
                if (json && json.success) {
                    showInfoModal(json.message || '{{ success_order_details_saved|e('js') }}');
                } else {
                    showInfoModal((json && json.error) ? json.error : '{{ text_operation_not_successful|e('js') }}');
                }
                saveOrderDetailsButton.disabled = false;
            },
            error: function () {
                showInfoModal('{{ text_operation_not_successful|e('js') }}');
                saveOrderDetailsButton.disabled = false;
            }
        });
    });
}

document.getElementById('alsendo-order-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const dateContainer = document.getElementById('shipment-preferred-pickup-date-container');
    const hourFrom = document.getElementById('shipment-preferred-pickup-hour-from');
    const hourTo = document.getElementById('shipment-preferred-pickup-hour-to');
    const dateInput = document.getElementById('shipment-preferred-pickup-date');

    if (dateContainer && getComputedStyle(dateContainer).display !== 'none') {
        const fromVal = hourFrom?.value.split(':')[0] ?? 0;
        const toVal = hourTo?.value.split(':')[0] ?? 0;
        if (toVal - fromVal < 2 || toVal <= fromVal) {
            e.preventDefault();
            showInfoModal('{{ error_pickup_hour_range|e('js') }}');
            return;
        }

        const selectedDate = new Date(dateInput?.value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        if (!dateInput?.value || selectedDate < today) {
            e.preventDefault();
            showInfoModal('{{ error_choose_preferred_pickup_date_not_past|e('js') }}');
            return;
        }
    }


    const submitButton = document.getElementById('order-shipment-btn');
    submitButton.disabled = true;

    const payload = getOrderFormPayload();

    $.ajax({
        url: 'index.php?route=extension/alsendo/alsendo_order.validatePreOrderShipment&user_token={{ user_token|e('js') }}',
        type: 'POST',
        data: payload,
        dataType: 'json',
        success: function (json) {
            document.querySelectorAll('.input-validation-error').forEach(input => {
                input.classList.remove('input-validation-error');
            });
            document.querySelectorAll('#alsendo-order-form small.validation-error-message').forEach(el => el.remove());

            if (json.success === false) {
                applyValidationErrors('#alsendo-order-form', json.errors || {});
                if (json.errors && typeof json.errors === 'object' && Object.keys(json.errors).length > 0) {
                    const errorText = Object.values(json.errors).map(function(m) { return Array.isArray(m) ? m[0] : m; }).join(', ');
                    showInfoModal(errorText ? `{{ text_there_are_validation_errors|e('js') }}<br>${errorText}` : '{{ text_there_are_validation_errors|e('js') }}');
                } else {
                    showInfoModal('{{ text_there_are_validation_errors|e('js') }}');
                }
                submitButton.disabled = false;
            }

            if (json.success === true) {
                $.ajax({
                    url: 'index.php?route=extension/alsendo/alsendo_order.submitOrderShipment&user_token={{ user_token|e('js') }}',
                    type: 'POST',
                    data: payload,
                    dataType: 'json',
                    success: function (sendJson) {
                        if (sendJson.success === true) {
                            location.reload();
                        } else {
                            document.querySelectorAll('#alsendo-order-form .input-validation-error').forEach(function(input) {
                                input.classList.remove('input-validation-error');
                            });
                            document.querySelectorAll('#alsendo-order-form small.validation-error-message').forEach(function(el) { el.remove(); });
                            if (sendJson.errors && typeof sendJson.errors === 'object' && Object.keys(sendJson.errors).length > 0) {
                                applyValidationErrors('#alsendo-order-form', sendJson.errors);
                                var errMsg = Object.values(sendJson.errors).map(function(m) { return Array.isArray(m) ? m[0] : m; }).join(', ');
                                showInfoModal(errMsg ? `{{ text_there_are_validation_errors|e('js') }}<br>${errMsg}` : '{{ text_there_are_validation_errors|e('js') }}');
                            } else {
                                showInfoModal(sendJson.error || '');
                            }
                            submitButton.disabled = false;
                        }
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                        submitButton.disabled = false;
                    }
                });
            }
        },
        error: function (xhr, status, error) {
            console.log(error);
            submitButton.disabled = false;
        }
    });
});

// Selecting package type template
let programmaticClick = false;
function safeClick(el) {
    // if (el === null || el === undefined) {
    //     return;
    // }
    programmaticClick = true;
    el.click();
    programmaticClick = false;
}

function handlePackageTemplateChange(selectElement, packageContainer, isFirstPackage) {
    const selectedTemplateId = selectElement.value;

    if (selectedTemplateId) {
        $.ajax({
            url: 'index.php?route=extension/alsendo/module/alsendo&user_token={{ user_token|e('js') }}',
            type: 'POST',
            data: {
                action: 'get_shipping_settings_template_data',
                id: selectedTemplateId,
                user_token: '{{ user_token|e('js') }}',
                auto_complete_content_for_order_id: {{ order_id }}
            },
            dataType: 'json',
            success: function(json) {
                if (json.success) {
                    const d = json.data;
                    packageContainer.querySelector('.package-width').value = d.width || '';
                    packageContainer.querySelector('.package-length').value = d.length || '';
                    packageContainer.querySelector('.package-height').value = d.height || '';
                    packageContainer.querySelector('.package-weight').value = d.weight || '';

                    var packagingSelectEl = packageContainer.querySelector('select.package-shipment-packaging');
                    if (packagingSelectEl) {
                        packagingSelectEl.value = d.package_type && packagingSelectEl.querySelector('option[value="'+d.package_type+'"]') ? d.package_type : (packagingSelectEl.options[0] ? packagingSelectEl.options[0].value : '');
                    } else {% if current_region == 'romania' %} {
                        safeClick(packageContainer.querySelector('[data-group^="package-shipment-packaging"][data-value="'+d.package_type+'"]'));
                    } {% else %} {
                        if (d.package_type === 'standard') {
                            safeClick(packageContainer.querySelector('[data-group^="package-shipment-packaging"][data-value="standard"]'));
                        } else {
                            safeClick(packageContainer.querySelector('[data-group^="package-shipment-packaging"][data-value="non-standard"]'));
                        }
                    }
                    {% endif %}
                    var nonStandardCb = packageContainer.querySelector('.package-non-standard');
                    if (nonStandardCb) nonStandardCb.checked = !!d.non_standard;

                    if (isFirstPackage) {
                        document.getElementById('package-content').value = d.shipment_content || '';
                        safeClick(document.querySelector('.pickup-type-btn[data-value="'+d.pickup_type+'"]'));
                        safeClick(document.querySelector('[data-group="selected_pickup_type"][data-value="'+d.pickup_type+'"]'));

                        var declaredValueInput = document.getElementById('package-declared-value');
                        if (declaredValueInput) {
                            var declVal = parseFloat(d.declared_value) || 0;
                            if (window.ALSENDO_AUTO_DECLARED_VALUE) {
                                var orderTotal = window.ALSENDO_ORDER_TOTAL || 0;
                                declaredValueInput.value = (declVal > orderTotal) ? declVal : orderTotal;
                            } else {
                                declaredValueInput.value = declVal;
                            }
                        }
                    }
                }
            }
        });
    } else {
        packageContainer.querySelector('.package-width').value = '';
        packageContainer.querySelector('.package-length').value = '';
        packageContainer.querySelector('.package-height').value = '';
        packageContainer.querySelector('.package-weight').value = '';

        if (isFirstPackage) {
            document.getElementById('package-content').value = '';
        }
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const packages = document.querySelectorAll('.single-package-container');
    
    packages.forEach((pkg, index) => {
        const templateSelect = pkg.querySelector('.package-template');
        const isFirst = index === 0;
        
        if (templateSelect) {
            templateSelect.addEventListener('change', function() {
                handlePackageTemplateChange(this, pkg, isFirst);
            });
        }
        
        pkg.querySelectorAll('.package-width, .package-length, .package-height, .package-weight').forEach(el => {
            if (!el.classList.contains('silent-change')) {
                el.addEventListener('input', () => resetPackageTemplateSelect(pkg));
            }
        });
        var pkgTypeSelect = pkg.querySelector('select.package-shipment-packaging');
        if (pkgTypeSelect) pkgTypeSelect.addEventListener('change', () => resetPackageTemplateSelect(pkg));
    });
    
    updatePackageHeaders();
});


// Reset selected template when value is manually changed

function resetPackageTemplateSelect(container) {
    if (!programmaticClick) {
        const select = container ? container.querySelector('.package-template') : document.querySelector('.package-template');
        if (select) {
            select.value = '';
        }
    }
}

['package-cod','package-declared-value'].forEach(id=>{
    const el = document.getElementById(id);
    if (el && !el.classList.contains('silent-change')) {
        el.addEventListener('input', () => resetPackageTemplateSelect(null));
    }
});

document.querySelectorAll('.pickup-type-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!btn.classList.contains('silent-change')) {
            resetPackageTemplateSelect(null);
        }
    });
});

function updatePackageHeaders() {
    const packages = document.querySelectorAll('.single-package-container');
    packages.forEach((pkg, index) => {
        const headerContainer = pkg.querySelector('.d-flex');
        const header = pkg.querySelector('.package-header');
        const removeBtn = pkg.querySelector('.remove-package-btn');
        
        if (index === 0) {
header.textContent = '{{ text_package|e('js') }}';
        if (removeBtn) removeBtn.remove();
        } else {
            header.textContent = '{{ text_package|e('js') }} ' + (index + 1);
            if (!removeBtn) {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'btn btn-sm btn-danger remove-package-btn';
                btn.textContent = 'X';
                btn.addEventListener('click', function() {
                    pkg.remove();
                    updatePackageHeaders();
                });
                headerContainer.appendChild(btn);
            }
        }
    });
}

const addAnotherPackageButton = document.querySelector('.add-another-package-button');

if (addAnotherPackageButton) {
    document.querySelector('.add-another-package-button').addEventListener('click', function () {
        const container = document.querySelector('.single-packages-section-container');
        const packages = container.querySelectorAll('.single-package-container');
        const newIndex = packages.length;
        const template = document.querySelector('.single-package-container');
        const clone = template.cloneNode(true);

        clone.querySelectorAll('input[type="number"]').forEach(input => input.value = '');
        clone.querySelector('.package-template').value = '';

        const newGroupName = `package-shipment-packaging-${newIndex}`;
        const packagingSelect = clone.querySelector('select.package-shipment-packaging');
        const packagingButtons = clone.querySelectorAll('[data-group^="package-shipment-packaging"]');
        if (packagingSelect) {
            packagingSelect.id = newGroupName;
            packagingSelect.value = packagingSelect.options[0] ? packagingSelect.options[0].value : 'LIST';
        } else {
            packagingButtons.forEach(btn => {
                btn.setAttribute('data-group', newGroupName);
                btn.classList.remove('active');
            });
            const hiddenInput = clone.querySelector('.package-shipment-packaging');
            hiddenInput.id = newGroupName;
            var standardBtn = clone.querySelector('[data-value="standard"]');
            if (standardBtn) standardBtn.classList.add('active');
            hiddenInput.value = 'standard';
        }

        const templateSelect = clone.querySelector('.package-template');
        templateSelect.addEventListener('change', function () {
            handlePackageTemplateChange(this, clone, false);
        });

        clone.querySelectorAll('.package-width, .package-length, .package-height, .package-weight').forEach(el => {
            if (!el.classList.contains('silent-change')) {
                el.addEventListener('input', () => resetPackageTemplateSelect(clone));
            }
        });
        var clonePkgTypeSelect = clone.querySelector('select.package-shipment-packaging');
        if (clonePkgTypeSelect) clonePkgTypeSelect.addEventListener('change', () => resetPackageTemplateSelect(clone));

        container.appendChild(clone);
        updatePackageHeaders();
    });
}

</script>

{{ footer }}