<?php

// phpcs:disable Generic.Files.LineLength.TooLong

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
/** @var \Magento\Shipping\Block\Adminhtml\Create\Items $block */

use Macopedia\OrlenShipping\Model\Carrier\OrlenShipping;

?>

<section class="admin__page-section">
    <div class="admin__page-section-title">
        <span class="title"><?= $escaper->escapeHtml(__('Items to Ship')) ?></span>
    </div>
    <div class="admin__table-wrapper">
        <table class="data-table admin__table-primary order-shipment-table">
            <thead>
                <tr class="headings">
                    <th class="col-product"><span><?= $escaper->escapeHtml(__('Product')) ?></span></th>
                    <th class="col-ordered-qty"><span><?= $escaper->escapeHtml(__('Qty')) ?></span></th>
                    <th class="col-qty<?php if ($block->isShipmentRegular()): ?> last<?php endif; ?>">
                        <span><?= $escaper->escapeHtml(__('Qty to Ship')) ?></span>
                    </th>
                    <?php if (!$block->canShipPartiallyItem()): ?>
                    <th class="col-ship last"><span><?= $escaper->escapeHtml(__('Ship')) ?></span></th>
                    <?php endif; ?>
                </tr>
            </thead>
            <?php $_items = $block->getShipment()->getAllItems() ?>
            <?php $_i = 0; foreach ($_items as $_item):
                if ($_item->getOrderItem()->getParentItem()):
                    continue;
                endif;
                $_i++ ?>
                <tbody class="<?= $_i%2 ? 'odd' : 'even' ?>">
                    <?= $block->getItemHtml($_item) ?>
                    <?= $block->getItemExtraInfoHtml($_item->getOrderItem()) ?>
                </tbody>
            <?php endforeach; ?>
        </table>
    </div>
</section>

<section class="admin__page-section">
    <div class="admin__page-section-title">
        <span class="title"><?= $escaper->escapeHtml(__('Shipment Total')) ?></span>
    </div>
    <div class="admin__page-section-content order-comments-history">
        <div class="admin__page-section-item">
            <div class="admin__page-section-item-title">
                <span class="title"><?= $escaper->escapeHtml(__('Shipment Comments')) ?></span>
            </div>
            <div class="admin__page-section-item-content">
                <div id="order-history_form" class="admin__field">
                    <label class="admin__field-label"
                           for="shipment_comment_text">
                        <span><?= $escaper->escapeHtml(__('Comment Text')) ?></span></label>
                    <div class="admin__field-control">
                        <textarea id="shipment_comment_text"
                                  class="admin__control-textarea"
                                  name="shipment[comment_text]"
                                  rows="3"
                                  cols="5">
                            <?= $escaper->escapeHtml($block->getShipment()->getCommentText()) ?>
                        </textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="admin__page-section-item order-totals order-totals-actions">
        <?php // MACOPEDIA CUSTOM START ?>
        <div class="admin__page-section-item-title">
            <span class="title"><?= $escaper->escapeHtml(__('ORLEN Paczka')) ?></span>
        </div>
        <?php if (str_contains($block->getShipment()->getOrder()->getShippingMethod(), OrlenShipping::CODE)): ?>
            <div class="admin__field admin__field-wide">
                <label class="admin__field-label" for="sender_orders">
                    <span><?= $escaper->escapeHtml(__('Sender Orders')) ?></span>
                </label>
                <div class="admin__field-control">
                    <input type="text"
                           name="shipment[sender_orders]"
                           id="sender_orders"
                           class="admin__control-text"
                           maxlength="30"
                           value="<?= $escaper->escapeHtml($block->getShipment()->getData('sender_orders')) ?>" />
                </div>
            </div>
            <div class="field choice admin__field admin__field-option field-append">
                <input id="has_insurance"
                       class="admin__control-checkbox"
                       name="shipment[has_insurance]"
                       value="1"
                       type="checkbox"/>
                <label class="admin__field-label"
                       for="has_insurance">
                    <span><?=$escaper->escapeHtml(__('Insure')) ?></span></label>
            </div>
        <div id="pack_value_container" class="admin__field admin__field-wide" style="display: none;">
                <label class="admin__field-label" for="pack_value">
                    <span><?= $escaper->escapeHtml(__('Pack Value')) ?></span>
                </label>
                <div class="admin__field-control">
                    <input type="text"
                           name="shipment[pack_value]"
                           id="pack_value"
                           class="admin__control-text"
                           maxlength="6"
                           data-validate='{
                        "required": true,
                        "number": true,
                        "validate-not-negative-number": true,
                        "validate-less-than-equals-to-constant": 5000
                   }'
                           value="<?= $escaper->escapeHtml($block->getShipment()->getData('pack_value')) ?>" />
                    <div class="note">
                        <small>
                            <?= $escaper->escapeHtml(__('Chargeable service:')) ?>
                            <br>
                            <?= $escaper->escapeHtml(__('Up to PLN 500: 0 PLN | Up to 1500 PLN: PLN 0.80 | Up to PLN 2,500: PLN 1.00 | Up to PLN 5,000: PLN 2.00')) ?>
                        </small>
                    </div>
                </div>
            </div>
            <div class="admin__field admin__field-wide">
                <label class="admin__field-label" for="box_size">
                    <span><?= $escaper->escapeHtml(__('Box Size')) ?></span>
                </label>
                <div class="admin__field-control">
                    <select name="shipment[box_size]" id="box_size" class="admin__control-select">
                        <?php $defaultBoxSize = $block->getDefaultBoxSize() ?>
                        <?php foreach ($block->getBoxSizeOptions() as $option): ?>
                            <option value="<?= $escaper->escapeHtmlAttr($option['value']) ?>"
                                <?= $option['value'] === $defaultBoxSize ? 'selected' : '' ?>>
                                <?= $escaper->escapeHtml($option['label']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        <?php endif; ?>
        <br>
        <?php // MACOPEDIA CUSTOM END ?>
        <div class="admin__page-section-item-title">
            <span class="title"><?= $escaper->escapeHtml(__('Shipment Options')) ?></span>
        </div>
        <div class="admin__page-section-item-content">
            <?php if ($block->canCreateShippingLabel()): ?>
                <div class="field choice admin__field admin__field-option field-create">
                    <input id="create_shipping_label"
                           class="admin__control-checkbox"
                           name="shipment[create_shipping_label]"
                           value="1"
                           type="checkbox"/>
                    <label class="admin__field-label"
                           for="create_shipping_label">
                        <span><?= $escaper->escapeHtml(__('Create Shipping Label')) ?></span></label>
                    <?= /* @noEscape */ $secureRenderer->renderEventListenerAsTag(
                        'onclick',
                        'toggleCreateLabelCheckbox();',
                        'input#create_shipping_label'
                    ) ?>
                </div>
            <?php endif ?>

            <div class="field choice admin__field admin__field-option field-append">
                <input id="notify_customer"
                       class="admin__control-checkbox"
                       name="shipment[comment_customer_notify]"
                       value="1"
                       type="checkbox"/>
                <label class="admin__field-label"
                       for="notify_customer">
                    <span><?=$escaper->escapeHtml(__('Append Comments')) ?></span></label>
            </div>

            <?php if ($block->canSendShipmentEmail()): ?>
                <div class="field choice admin__field admin__field-option field-email">
                    <input id="send_email"
                           class="admin__control-checkbox"
                           name="shipment[send_email]"
                           value="1"
                           type="checkbox"/>
                    <label class="admin__field-label"
                           for="send_email">
                        <span><?= $escaper->escapeHtml(__('Email Copy of Shipment')) ?></span></label>
                </div>
            <?php endif; ?>
            <?= $block->getChildHtml('submit_before') ?>
            <div class="order-history-comments-actions actions">
                <?= $block->getChildHtml('submit_button') ?>
                <?= $block->getChildHtml('submit_after') ?>
            </div>
        </div>
    </div>
</section>
<?php $scriptString = <<<script

require([
    "jquery",
    "Magento_Ui/js/modal/alert",
    "prototype"
], function(jQuery, alert){

//<![CDATA[
var sendEmailCheckbox = $('send_email');
if (sendEmailCheckbox) {
    var notifyCustomerCheckbox = $('notify_customer');
    var shipmentCommentText = $('shipment_comment_text');
    Event.observe(sendEmailCheckbox, 'change', bindSendEmail);
    bindSendEmail();
}
function bindSendEmail() {
    if (sendEmailCheckbox.checked == true) {
        notifyCustomerCheckbox.disabled = false;
    }
    else {
        notifyCustomerCheckbox.disabled = true;
    }
}

// MACOPEDIA CUSTOM START
var hasInsuranceCheckbox = $('has_insurance');
var packValueContainer = $('pack_value_container');
var packValueInput = $('pack_value');
var originalValidation = packValueInput ? packValueInput.readAttribute('data-validate') : null;

if (hasInsuranceCheckbox && packValueContainer && packValueInput) {
    hasInsuranceCheckbox.observe('change', togglePackValueField);
    togglePackValueField();
}

function togglePackValueField() {
    if (hasInsuranceCheckbox.checked) {
        packValueContainer.show();
        if (!packValueInput.readAttribute('data-validate')) {
            packValueInput.writeAttribute('data-validate', originalValidation);
        }
    } else {
        packValueContainer.hide();
        packValueInput.removeAttribute('data-validate');
    }
}
// MACOPEDIA CUSTOM END

window.toggleCreateLabelCheckbox = function() {
    var checkbox = $('create_shipping_label');
    var submitButton = checkbox.up('.order-totals').select('.submit-button span')[0];
    if (checkbox.checked) {
        submitButton.innerText += '...';
    } else {
        submitButton.innerText = submitButton.innerText.replace(/\.\.\.$/, '');
    }
}
window.submitShipment = function(btn) {
    if (!validQtyItems()) {
        alert({
            content: '{$block->escapeJs(__('Invalid value(s) for Qty to Ship'))}'
        });
        return;
    }
    var checkbox = $(btn).up('.order-totals').select('#create_shipping_label')[0];
    if (checkbox && checkbox.checked) {
        packaging.showWindow();
    } else {
        disableElements('submit-button');
        // Temporary solution will be replaced after refactoring order functionality
        jQuery('#edit_form').on('invalid-form.validate', function() {
            enableElements('submit-button');
            jQuery('#edit_form').off('invalid-form.validate');
        });
        jQuery('#edit_form').triggerHandler('save');
    }
}
window.validQtyItems = function() {
    var valid = true;
    $$('.qty-item').each(function(item) {
        var val = parseFloat(item.value);
        if (isNaN(val) || val < 0) {
            valid = false;
        }
    });
    return valid;
}

window.bindSendEmail = bindSendEmail;

window.shipmentCommentText = shipmentCommentText;
window.notifyCustomerCheckbox = notifyCustomerCheckbox;
window.sendEmailCheckbox = sendEmailCheckbox;
//]]>

});

script;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
