<?php

use FiloBlu\Rma\Block\Returns\Form;
use FiloBlu\Rma\Block\Rma\Returns\View;
use Magento\Cms\Block\Block;

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
//phpcs:disable Squiz.ControlStructures.ControlSignature.NewlineAfterOpenBrace
//phpcs:disable Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore
//phpcs:disable Magento2.Files.LineLength.MaxExceeded
//phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
/** @var \FiloBlu\Rma\Block\Returns\Create $block */

$_order =  $block->getOrder();
$_data = $block->getFormData();
$_items = $block->getItems();
$totalAvlQty = 0;
$_returningItemsInfo = $block->getLayout()->createBlock(Block::class)->setBlockId('returning-items-information');
$_returnsInformation = $block->getLayout()->createBlock(Block::class)->setBlockId('return-type-information');
$_normalReturnInfo = $block->getLayout()->createBlock(Block::class)->setBlockId('normal-return-information');
$_easyReturnInformation = $block->getLayout()->createBlock(Block::class)->setBlockId('easy-return-information');
$_easyReturnBeforeSubmitInformation = $block->getLayout()->createBlock(Block::class)->setBlockId('easy-return-before-submit-information');

/** @var \FiloBlu\Rma\Helper\RmaHelper $rmaHelper */
$rmaHelper = $this->helper(\FiloBlu\Rma\Helper\RmaHelper::class);
$easyReturnHelper = $this->helper(\FiloBlu\Rma\Helper\EasyReturnHelper::class);

$easyReturnAmount = (int)$easyReturnHelper->simulateEasyReturnShippingCost(
    $_order->getShippingAddress(),
    $_order->getStore(),
    $_order->getWeight(),
    $_order->getGrandTotal()
);

$returnableItemsCount = 0;

/** @var \FiloBlu\Rma\Helper\OfflinePaymentMethodsHelper $opmHelper */
$opmHelper = $this->helper(\FiloBlu\Rma\Helper\OfflinePaymentMethodsHelper::class);
$ibanOfflinePaymentsEnabled = $opmHelper->isIbanOfflinePaymentsEnabled();
$ibanRequired = false;
if ($ibanOfflinePaymentsEnabled) {
    $ibanRequired = $opmHelper->isIbanRequired($block->getOrder());
}
$attributes = [];
$bundleItemAttributeValueLabel = '';
?>

<script id="template-registrant" type="text/x-magento-template">
    <div class="actions-toolbar">
        <div class="secondary" id="delete<%- data._index_ %>">
            <button type="button" class="action remove delete"><span><?= $block->escapeHtml(__('Remove')) ?></span></button>
        </div>
    </div>
    <fieldset class="fieldset">
        <div class="field item required">
            <label for="items:item<%- data._index_ %>" class="label"><span><?= $block->escapeHtml(__('Item')) ?></span></label>
            <div class="control">
                <?php $bundleID     = 0; ?>
                <?php $firstItemId = $i = $productType = $availableQty = $shipmentType = 0; ?>
                <?php $html         = []; ?>
                <select name="items[<%- data._index_ %>][order_item_id]" class="select" id="items:item<%- data._index_ %>" data-args='{"index":<%- data._index_ %>}'>
                    <?php $firstItemGot = false; ?>

                    <?php foreach ($_items as $_item) : ?>
                        <?php $totalAvlQty += $block->getAvailableQty($_item); ?>
						<?php $itemAvailableQty = $block->getAvailableQty($_item); ?>

                        <?php
                        $__remainingParent = (int)max(
                            0,
                            (float)$_item->getQtyOrdered()
                            - (float)$_item->getQtyRefunded()
                            - (float)($_item->getQtyReturned() ?: 0)
                        );
                        $__isForcedBundle  = 0;
                        ?>


                        <?php if ($itemAvailableQty) : ?>
                            <?php $returnableItemsCount++; ?>

                            <?php if (!$firstItemGot) : ?>
                                <?php
                                    $firstItemGot = true;
                                    $firstItemId = $_item->getId();
                                    $productType = $_item->getProductType();
                                    $availableQty = $block->getAvailableQty($_item);
                                    $shipmentType = $_item->getProduct()->getShipmentType();
                                ?>
                            <?php endif; ?>
                        <?php endif; ?>

                        <?php if ($_item->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) : ?>
                            <?php $bundleID = $_item->getId(); ?>
                            <?php $__isForcedBundle = $forceBundleReturn = (bool)$_item->getProduct()->getForceBundleReturn(); ?>
                        <?php endif; ?>
                        <?php if (!$_item->getParentItemId() || $_item->getParentItemId() != $bundleID) : ?>
                            <?php if ($itemAvailableQty) : ?>
                                <option value="<?= (int) $_item->getId() ?>"
                                        id="item:order_item_id<%- data._index_ %>_<?= (int) $_item->getId() ?>"
                                        rel="<?= $block->escapeHtmlAttr($_item->getProductType()) ?>_<?= $__remainingParent ?>_<?= $block->escapeHtmlAttr($_item->getProduct()->getShipmentType()) ?>_<?= $__isForcedBundle ?>"
                                        data-remaining="<?= $__remainingParent ?>"
                                        data-force-bundle="<?= $__isForcedBundle ?>"
                                >
                                    <?= $block->escapeHtml($_item->getName()) ?>
                                </option>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if ($_item->getParentItemId() != null && $_item->getParentItemId() == $bundleID) : ?>
                            <?php

                                $product = $_item->getProduct();

                                $bundleItemSizeValue = $product->getSize();

                                if (!empty($bundleItemSizeValue)) {
                                    $bundleItemAttribute = 'size';
                                    $attributes[] = $product->getResource()->getAttribute($bundleItemAttribute)->getFrontend()->getValue($product);
                                }

                                $bundleItemColorValue = $product->getColor();

                                if (!empty($bundleItemColorValue)) {
                                    $bundleItemAttribute = 'color_details';
                                    $attributes[$bundleItemAttribute] = ucfirst($product->getResource()->getAttribute($bundleItemAttribute)->getFrontend()->getValue($product));
                                }

                                $bundleItemAttributeValueLabel = implode(' / ', $attributes);
                                $attributes = [];

                            ?>
                            <?php if ($_item->getIsOrdered()) : ?>
                                <?php
                                $html[$bundleID][] = [
                                    $_item->getId(),
                                    $block->escapeHtml($_item->getName()),
                                    $block->getAvailableQty($_item),
                                    1,
                                    $bundleItemAttributeValueLabel
                                ];
                                ?>
                            <?php else : ?>
                                <?php
                                $html[$bundleID][] = [
                                    $_item->getId(),
                                    $block->escapeHtml($_item->getName()),
                                    $block->getAvailableQty($_item),
                                    0,
                                    $bundleItemAttributeValueLabel
                                ];
                                ?>
                            <?php endif; ?>

                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
                <?php if (!empty($html)) : ?>
                    <?php
                        $hidden = '';

                        if (isset($forceBundleReturn) && ($forceBundleReturn)) {
                            $hidden = 'style="display:none"';
                        }
                    ?>
                    <?php foreach ($html as $bundleID => $node) : ?>
                        <div class="nested bundle-product bundle_<?= (int) $bundleID ?>">
                            <div id="radio:item<%- data._index_ %>_<?= (int) $bundleID ?>">
                                <div class="table-wrapper">
                                    <table class="data table table-return-items" id="return-items-table-<?= (int) $bundleID ?>">
                                        <caption class="table-caption"><?= $block->escapeHtml(__('Return items')) ?></caption>
                                        <thead>
                                        <tr>

                                            <th class="col product" scope="col"><?= $block->escapeHtml(__('Sub-items')) ?></th>
                                            <th class="col remaining qty" scope="col" <?= $hidden ?>><?= $block->escapeHtml(__('Remaining Qty')) ?></th>
                                            <th class="col qty" scope="col" <?= $hidden ?>><?= $block->escapeHtml(__('Qty')) ?></th>

                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php foreach ($node as $item) : ?>
                                            <tr>

                                                <td data-th="<?= $block->escapeHtmlAttr(__('Product')) ?>" class="col product">
                                                    <?php if ($item[3]) : ?>
                                                        <input type="checkbox" disabled <?= $hidden ?>>
                                                    <?php else : ?>
                                                        <input id="items[<%- data._index_ %>][<?= (int) $bundleID ?>][checkbox][item][<?= $block->escapeHtmlAttr($item[0]) ?>]" data-validate="{'validate-one-required-by-name':true}"  data-args='{"item" :<?= $block->escapeHtmlAttr($item[0]) ?>, "bundleId" : <?= (int) $bundleID ?>, "index" :<%- data._index_ %>, "initialQty" : <?= $block->escapeHtml($item[2]) ?> }' type="checkbox" value="<?= $block->escapeHtmlAttr($item[0]) ?>" class="checkbox change-container-classname" name="validate-one-checkbox-<?= (int) $bundleID ?>-<%- data._index_ %>" <?= $hidden ?>/>
                                                    <?php endif; ?>
                                                    <label for="items[<%- data._index_ %>][<?= (int) $bundleID ?>][checkbox][item][<?= $block->escapeHtmlAttr($item[0]) ?>]" class="label <?= ($item[3]) ? 'disabled' : '' ?>">
                                                        <?= $block->escapeHtmlAttr($item[1]) ?>
                                                        <?php if ($bundleID): ?>
                                                            - <span><?= $block->escapeHtmlAttr($item[4]) ?></span>
                                                        <?php endif; ?>
                                                    </label>
                                                </td>
                                                <td data-th="<?= $block->escapeHtmlAttr(__('Remaining Qty')) ?>" class="col remaining qty" <?= $hidden ?>><?= $block->escapeHtml($item[2]) ?></td>
                                                <td data-th="<?= $block->escapeHtmlAttr(__('Qty')) ?>" class="col qty" <?= $hidden ?>>
                                                    <?php if (!$item[3]) : ?>
                                                        <input id="items[<%- data._index_ %>][<?= (int) $bundleID ?>][checkbox][qty][<?= $block->escapeHtmlAttr($item[0]) ?>]" name="items[<%- data._index_ %>][items][<?= $block->escapeHtmlAttr($item[0]) ?>]" size="7" data-validate="{'validate-greater-than-zero':true,'required-number':true}" type="number" style="display:none" disabled class="input-text" data-args='{"bundleItemName" : "<?= $block->escapeHtmlAttr($item[1]) ?>", "attributes" : "<?= $block->escapeHtmlAttr($item[4]) ?>"}'>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <div class="field qty required" id="qty_requested_block_<%- data._index_ %>">
            <label for="items:qty_requested<%- data._index_ %>" class="label"><span><?= $block->escapeHtml(__('Quantity To Return')) ?></span></label>
            <div class="control">
                <input type="number" class="input-text qty-to-return" data-validate="{'validate-greater-than-zero':true,'required-number':true}" value="" name="items[<%- data._index_ %>][qty_requested]" id="items:qty_requested<%- data._index_ %>">
                <div class="note" id="remaining_quantity_block_<%- data._index_ %>">
                    <?= $block->escapeHtml(__('Remaining Quantity:')) ?>&nbsp;<span id="remaining_quantity_<%- data._index_ %>" class="qty remaining"></span>
                </div>
            </div>

        </div>

        <?php foreach ($block->getAttributes() as $attribute) : ?>
            <?php $attributeContent = $block->getAttributeHtml($attribute); ?>
            <?php $attributeCode = $attribute->getAttributeCode(); ?>
            <?php if (
                $attributeContent && (
                    ($attributeCode != 'iban_for_return') ||
                    (($attributeCode == 'iban_for_return') && $ibanRequired))
            ) : ?>
                <?= /* @escapeNotVerified */ $attributeContent ?>
            <?php endif; ?>
        <?php endforeach; ?>
    </fieldset>
</script>

<form id="rma_create_form" method="post" action="<?=
                                                    /* @noEscape */ $block->getSubmitUrl() ?>" enctype="multipart/form-data" class="form form-create-return" data-order-id="<?= $_order ? $_order->getId() : '' ?>">
    <div class="step-1">
        <?php if ($_returningItemsInfo) : ?>
            <div class="returning-items-info"><?php echo $_returningItemsInfo->toHtml(); ?></div>
        <?php endif; ?>

        <fieldset class="fieldset">
            <legend class="legend">
                <span><?= $block->escapeHtml(__('New Return for Order %1', $_order->getIncrementId())) ?></span>
            </legend>
            <br>
            <div class="field id">
                <span class="label"><span><?= $block->escapeHtml(__('Order ID')) ?></span></span>
                <div class="control"><span><?= $block->escapeHtml($_order->getIncrementId()) ?></span></div>
            </div>
            <div class="field name">
                <span class="label"><span><?= $block->escapeHtml(__('Customer Name')) ?></span></span>
                <div class="control"><span><?= $block->escapeHtml($_order->getCustomerName()) ?></span></div>
            </div>
            <div class="field email">
                <span class="label"><span><?= $block->escapeHtml(__('Email')) ?></span></span>
                <div class="control"><span><?= $block->escapeHtml($_order->getCustomerEmail()) ?></span></div>
            </div>
            <div class="field contact email">
                <label class="label" for="email"><span><?= $block->escapeHtml($this->helper(Magento\Rma\Helper\Data::class)->getContactEmailLabel()) ?></span></label>
                <div class="control">
                    <input type="text" name="customer_custom_email" id="email" title="Contact Email Address" class="input-text" data-validate="{'validate-email':true}" value="<?= $block->escapeHtml($block->getContactEmail()) ?>">
                </div>
            </div>
            <div class="field address shipping">
                <span class="label"><span><?= $block->escapeHtml(__('Order Shipping Address')) ?></span></span>
                <address class="control"><?= /* @noEscape */ $block->format($_order->getShippingAddress(), 'html') ?></address>
            </div>

            <?=
            $block->getLayout()
                ->createBlock(View::class)
                ->setTemplate('FiloBlu_Rma::return/create/additional.phtml')
                ->toHtml()
            ?>
        </fieldset>

        <fieldset class="fieldset">
            <legend class="legend"><span><?= $block->escapeHtml(__('Return Items Information')) ?></span></legend>
            <br>
            <div id="registrant-options"></div> <?php /* fields of the form are inserted here */ ?>
            <div class="actions-toolbar">
                <div class="secondary">
                    <button type="button" id="add-item-to-return" class="action add" <?php if ($returnableItemsCount == 1) : ?> disabled<?php endif; ?>>
                        <span><?= $block->escapeHtml(__('Add Item To Return')) ?></span>
                    </button>
                </div>
            </div>
            <?php if ($ibanRequired): ?>
                <div id="iban-for-return-wrapper" class="field iban_for_return global required">
                    <label for="iban_for_return" class="label"><span>IBAN for Return</span></label>
                    <div class="control">
                        <input type="text" id="iban_for_return" name="iban_for_return" value="" class="input-text" required="true" aria-required="true">
                    </div>
                </div>
            <?php endif; ?>
            <div class="field comment">
                <label for="rma_comment" class="label"><span><?= $block->escapeHtml(__('Comments')) ?></span></label>
                <div class="control">
                    <textarea id="rma_comment" cols="5" rows="3" name="rma_comment" class="input-text"><?php if ($_data) : ?><?= $block->escapeHtml($_data->getRmaComment()) ?><?php endif; ?></textarea>
                </div>
            </div>

            <div class="actions-toolbar">
                <div class="primary">
                    <button class="action primary" disabled id="confirm-returning-items" type="button">
                        <span><?= __('Confirm') ?></span>
                    </button>
                </div>
            </div>

            <div class="return-types-error mage-error hide" generated>
                <?= __('Sorry, something went wrong. Please try again later.'); ?>
            </div>
        </fieldset>
    </div>

    <div class="step-2 hide">
        <div class="returning-items-summary"></div>

        <div class="return-type">
            <div class="return-type-information">
                <?php if ($_returnsInformation) : ?>
                    <?= $_returnsInformation->toHtml() ?>
                <?php endif; ?>
            </div>

            <div class="order-links">
                <p class="current item nav easy-return">
                    <strong><?= __('Easy return') ?></strong>
                </p>

                <?php if ($easyReturnAmount) : ?>
                    <p class="item nav normal-return">
                        <a href="#"><?= __('Normal return'); ?></a>
                    </p>
                <?php endif; ?>

            </div>

            <div class="contents">
                <div class="content">
                    <div class="easy-return-information">
                        <?php if ($_easyReturnInformation) : ?>
                            <?= $_easyReturnInformation->toHtml() ?>
                        <?php endif; ?>
                    </div>

                    <div class="price-wrapper">
                        <span><?= __('Price') ?></span> <span class="simple-rma-message"></span>
                    </div>

                    <div class="fieldset fieldset-easy-return">
                        <?= $block->getLayout()->createBlock(Form::class)->setTemplate($block::SHIPPING_ADDRESS_TEMPLATE)->toHtml() ?>
                    </div>

                    <div class="actions-wrapper">
                        <button class="action primary" id="confirm-shipping-address" type="button">
                            <span><?= __('Confirm') ?></span>
                        </button>

                        <button class="action go-back secondary" data-step=".step-2" data-target=".step-1" type="button">
                            <span><?= __('Back') ?></span>
                        </button>
                    </div>
                </div>

                <div class="content">
                    <input type="radio" id="normal-rma" name="return_type" value="normal-return" />

                    <?php if ($_normalReturnInfo) : ?>
                        <div><?= $_normalReturnInfo->toHtml() ?></div>
                    <?php endif; ?>

                    <div class="actions-wrapper">
                        <button type="submit" class="action submit primary" id="submit.save" title="<?= /* @escapeNotVerified */ __('Save') ?>">
                            <span><?= /* @escapeNotVerified */ __('Submit') ?></span>
                        </button>

                        <button class="action go-back secondary" data-step=".step-2" data-target=".step-1" type="button">
                            <span><?= __('Back') ?></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="step-3 hide">
        <div class="returning-items-summary"></div>
        <div class="return-type-summary"></div>

        <div>
            <?php if ($_easyReturnBeforeSubmitInformation) : ?>
                <div class="easy-return-final-info"><?= $_easyReturnBeforeSubmitInformation->toHtml() ?></div>
            <?php endif; ?>

            <p><?= __('Total') ?> <span class="simple-rma-message"></span></p>

            <div class="actions-wrapper">
                <button type="submit" class="action submit primary" id="submit.save" title="<?= /* @escapeNotVerified */ __('Save') ?>">
                    <span><?= /* @escapeNotVerified */ __('Submit') ?></span>
                </button>

                <button class="action go-back secondary" data-step=".step-3" data-target=".step-2" type="button">
                    <span><?= __('Back') ?></span>
                </button>
            </div>
        </div>
    </div>

    <script type="text/x-magento-init">
        {
            "#rma_create_form": {
                "fileElement": {},
                "rmaCreate": {
                    <?php $i = 0; ?>
                    <?php if ($_data) : ?>
                    <?php $formDataPost = $_data->getItems(); ?>
                    <?php if (is_array($formDataPost)) : ?>
                    "formDataPost": <?= /* @noEscape */ json_encode($formDataPost) ?>,
                    <?php endif; ?>
                    <?php endif; ?>
                    "templateRegistrant": "#template-registrant",
                    "registrantOptions": "#registrant-options",
                    "addItemToReturn": "add-item-to-return",
                    "btnRemove": "delete",
                    "row": "#row",
                    "addRow": "additional row",
                    "qtyReqBlock": "#qty_requested_block",
                    "remQtyBlock": "#remaining_quantity_block",
                    "remQty": "#remaining_quantity",
                    "reasonOtherRow": "#reason_other",
                    "reasonOtherInput": "#items:reason_other",
                    "radioItem": "#radio:item",
                    "orderItemId": "#item:order_item_id",
                    "itemsItem": "items:item",
                    "itemsReason": "items:reason",
                    "totalAvlQty": "<?= ($totalAvlQty) ? (int) $totalAvlQty : 0 ?>",
                    "firstItemId": "<?= (int) $firstItemId ?>",
                    "productType": "<?= $block->escapeJs($productType) ?>",
                    "shipmentType": "<?= $block->escapeJs($shipmentType) ?>",
                    "availableQuantity": "<?= ($availableQty) ? (int) $availableQty : 0 ?>",
                    "prodTypeBundle": "<?= /* @noEscape */ \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE ?>",
                    "forceBundleReturn": "<?= isset($forceBundleReturn) ? (int)$forceBundleReturn : 0 ?>"
                },
                "validation": {
                     "ignore": ":hidden:not(input[id$='_value'])"
                }
            }
        }
    </script>
</form>
