{{ header }}{{ column_left }}
<div id="content">
    <div class="page-header">
        <div class="container-fluid">
            <div class="float-end">
                <button type="button" id="button-bulk-send-shipments" data-bs-toggle="tooltip" title="{{ text_button_bulk_create_shipments }}" class="btn btn-primary">
                    <i class="fa-solid fa-truck"></i>
                </button>
                <button type="button" id="button-bulk-download-waybills" data-bs-toggle="tooltip" title="{{ text_button_bulk_download_waybills }}" class="btn btn-primary">
                    <i class="fa-solid fa-arrow-down"></i>
                </button>
                <button type="button" id="button-bulk-cancel-shipments" data-bs-toggle="tooltip" title="{{ text_button_bulk_cancel_shipments }}" class="btn btn-danger">
                    <i class="fa-solid fa-times-circle"></i>
                </button>
            </div>
            <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>
        </div>
    </div>
    <div class="container-fluid">
        <div class="row">
            <div class="card">
                <div class="card-header"><i class="fa-solid fa-list"></i> {{ text_bulk_orders_table_header }}</div>
                <div id="order" class="card-body">{{ list }}</div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        function getIdsFromQuery() {
            const params = new URLSearchParams(window.location.search);
            const idsParam = params.get('ids') || '';
            return idsParam.split(',').filter(id => id);
        }

        function updateErrorMessage(statusClass, orderId, message, success) {
            const $p = $(`p.${statusClass}[data-order-id="${orderId}"]`);
            $p.html(message);

            if (success) {
                if (!$p.hasClass('operation-success')) {
                    $p.addClass('operation-success');
                }
            } else {
                $p.removeClass('operation-success');
            }
        }

        function handleResponse(response, statusClass) {
            $('td.td-order-shipment-status').css('width', '300px');
            $(`p.${statusClass}`).not('.operation-success').html('');

            if (response.errors && typeof response.errors === 'object' && Object.keys(response.errors).length) {
                for (const [orderId, message] of Object.entries(response.errors)) {
                    $(`tr.bulk-order-table-row[data-order-id="${orderId}"]`)
                        .addClass('bulk-table-row-warning')
                        .removeClass('bulk-table-row-success');
                    $(`p.${statusClass}[data-order-id="${orderId}"]`).html(message);

                    if (statusClass === 'order-bulk-send-operation-status') {
                        $(`.try-order-shipment-resubmit-button[data-order-id="${orderId}"]`).prop('disabled', false);
                        $(`.cancel-submitted-order-button[data-order-id="${orderId}"]`).prop('disabled', true);
                    }

                    if (statusClass === 'order-bulk-cancel-operation-status') {
                        $(`.cancel-submitted-order-button[data-order-id="${orderId}"]`).prop('disabled', false);
                        $(`.try-order-shipment-resubmit-button[data-order-id="${orderId}"]`).prop('disabled', true);
                    }
                }
            }

            if (response.success && typeof response.success === 'object' && Object.keys(response.success).length) {
                for (const [orderId, message] of Object.entries(response.success)) {
                    $(`tr.bulk-order-table-row[data-order-id="${orderId}"]`)
                        .addClass('bulk-table-row-success')
                        .removeClass('bulk-table-row-warning');
                    $(`p.${statusClass}[data-order-id="${orderId}"]`)
                        .addClass('operation-success')
                        .html(message);

                    if (statusClass === 'order-bulk-send-operation-status') {
                        $(`.try-order-shipment-resubmit-button[data-order-id="${orderId}"]`).prop('disabled', true);
                        $(`.cancel-submitted-order-button[data-order-id="${orderId}"]`).prop('disabled', false);
                    }

                    if (statusClass === 'order-bulk-cancel-operation-status') {
                        $(`.cancel-submitted-order-button[data-order-id="${orderId}"]`).prop('disabled', true);
                        $(`.try-order-shipment-resubmit-button[data-order-id="${orderId}"]`).prop('disabled', true);
                    }
                }
            }
        }


        $('#button-bulk-send-shipments').on('click', function () {
            const btn = $(this);
            const ids = getIdsFromQuery();
            btn.prop('disabled', true);
            $.post(
                'index.php?route=extension/alsendo/alsendo_order.bulkSubmitOrderShipment&user_token={{ user_token|e('js') }}',
                { ids: ids },
                function (response) {
                    handleResponse(response, 'order-bulk-send-operation-status');
                    setTimeout(() => btn.prop('disabled', false), 500);
                },
                'json'
            );
        });
        $('#button-bulk-download-waybills').on('click', function () {
            const ids = getIdsFromQuery();
            const url = 'index.php?route=extension/alsendo/alsendo_order.bulkDownloadShipmentWaybillsByOrderIds&user_token={{ user_token|e('js') }}';

            const form = $('<form>', {
                method: 'POST',
                action: url,
                target: '_blank',
                style: 'display:none'
            });

            ids.forEach(id => {
                form.append($('<input>', {
                    type: 'hidden',
                    name: 'ids[]',
                    value: id
                }));
            });

            $('body').append(form);
            form.submit();
            form.remove();
        });



        $('#button-bulk-cancel-shipments').on('click', function () {
            const btn = $(this);
            const ids = getIdsFromQuery();

            if (!ids || !ids.length) {
                showInfoModal('{{ text_no_shipments_selected|e('js') }}');
                return;
            }

            btn.prop('disabled', true);
            $.post(
                'index.php?route=extension/alsendo/alsendo_order.bulkCancel&user_token={{ user_token|e('js') }}',
                { ids: ids },
                function (response) {
                    handleResponse(response, 'order-bulk-cancel-operation-status');
                    setTimeout(() => {
                        location.reload();
                    }, 500);
                },
                'json'
            );
        });

        $('.try-order-shipment-resubmit-button').on('click', function () {
            const btn = $(this);
            const orderId = btn.data('order-id');
            btn.prop('disabled', true);

            $.post(
                'index.php?route=extension/alsendo/alsendo_order.submitOrderShipment&user_token={{ user_token|e('js') }}',
                { by_order_id: true, order_id: orderId },
                function(response) {
                    if (response.success === true) {
                        location.reload();
                    }
                    if (response.success === false) {
                        if (response.message === 'Shipment already exists') {
                            location.reload();
                            return;
                        }
                        const e = response;
                        const errorMsg = Array.isArray(e.errors)
                            ? e.errors.join(', ')
                            : (e.errors ? Object.values(e.errors).join(', ') : (e.error || e.message || ''));
                        updateErrorMessage('order-bulk-send-operation-status', orderId, errorMsg, false);
                    }

                    setTimeout(() => btn.prop('disabled', false), 500);
                },
                'json'
            );
        });

        $('.cancel-submitted-order-button').on('click', function () {
            const btn = $(this);
            const orderId = btn.data('order-id');
            btn.prop('disabled', true);

            $.post(
                'index.php?route=extension/alsendo/alsendo_order.cancel&user_token={{ user_token|e('js') }}',
                { alsendo_order_id: orderId },
                function(response) {
                    if (response.success === true) {
                        location.reload();
                    }
                    if (response.success === false) {
                        const e = response;
                        let errorMsg = Array.isArray(e.errors)
                            ? e.errors.join(', ')
                            : (e.errors ? Object.values(e.errors).join(', ') : (e.error || e.message || ''));

                        if (!errorMsg) errorMsg = 'Unknown error';
                        updateErrorMessage('order-bulk-cancel-operation-status', orderId, errorMsg, false);
                    }

                    setTimeout(() => btn.prop('disabled', false), 500);
                },
                'json'
            );
        });

        $(document).on('click', '.download-waybill-single', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).prop('disabled')) return;
            const externalShipmentId = $(this).data('external-shipment-id');
            const url = 'index.php?route=extension/alsendo/alsendo_order.downloadShipmentWaybill&user_token={{ user_token|e('js') }}';

            $.ajax({
                url: url,
                type: 'POST',
                data: { alsendo_order_id: externalShipmentId },
                dataType: 'json',
                success: function (json) {
                    if (json.success === false) {
                        alert(json.error || json.message || '{{ text_operation_not_successful|e('js') }}');
                        return;
                    }
                    if (json.success && json.waybill && json.type === 'pdf') {
                        const binary = atob(json.waybill);
                        const bytes = new Uint8Array(binary.length);
                        for (let i = 0; i < binary.length; i++) {
                            bytes[i] = binary.charCodeAt(i);
                        }
                        const blob = new Blob([bytes], { type: 'application/pdf' });
                        const link = document.createElement('a');
                        const blobUrl = window.URL.createObjectURL(blob);
                        link.href = blobUrl;
                        link.download = 'waybill_' + externalShipmentId + '.pdf';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(blobUrl);
                    }
                },
                error: function (xhr, status, error) {
                    let msg = '{{ text_operation_not_successful|e('js') }}: ' + error;
                    if (xhr.responseText && xhr.responseText.indexOf('{') === 0) {
                        try {
                            const errJson = JSON.parse(xhr.responseText);
                            if (errJson && (errJson.error || errJson.message)) {
                                msg = errJson.error || errJson.message;
                            }
                        } catch (e) {}
                    }
                    alert(msg);
                }
            });
        });
    });
</script>

{{ footer }}
