<?php
// @codingStandardsIgnoreFile
use FiloBlu\Rma\Block\Returns\Form;
use FiloBlu\Rma\Block\Rma\Returns\View;
use Magento\Cms\Block\Block;

/** @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());
}
?>

<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><?= /* @escapeNotVerified */ __('Remove') ?></span></button>
        </div>
    </div>
    <fieldset class="fieldset">
        <div class="field item required">
            <label for="items:item<%- data._index_ %>" class="label"><span><?= /* @escapeNotVerified */ __('Item') ?></span></label>
            <div class="control">
                <?php $bundleID     = 0; ?>
                <?php $firstItemId = $i = $productType = $availableQty = 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 if ($itemAvailableQty) : ?>
						<?php $returnableItemsCount++; ?>

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

                        <?php if ($_item->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) : ?>
                            <?php $bundleID = $_item->getId(); ?>
                        <?php endif; ?>
                        <?php if (!$_item->getParentItemId() || $_item->getParentItemId() != $bundleID) : ?>
                            <?php if ($itemAvailableQty) : ?>
                                <option value="<?= /* @escapeNotVerified */ $_item->getId() ?>" id="item:order_item_id<%- data._index_ %>_<?= /* @escapeNotVerified */ $_item->getId() ?>" rel="<?= /* @escapeNotVerified */ $_item->getProductType() ?>_<?= /* @escapeNotVerified */ $block->getAvailableQty($_item) ?>"><?= $block->escapeHtml($_item->getName()) ?></option>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if ($_item->getParentItemId() != null && $_item->getParentItemId() == $bundleID) : ?>
                            <?php if ($_item->getIsOrdered()) : ?>
                                <?php
                                $html[$bundleID][] = [
                                    $_item->getId(),
                                    $block->escapeHtml($_item->getName()),
                                    $block->getAvailableQty($_item),
                                    1,
                                ];
                                ?>
                            <?php else : ?>
                                <?php
                                $html[$bundleID][] = [
                                    $_item->getId(),
                                    $block->escapeHtml($_item->getName()),
                                    $block->getAvailableQty($_item),
                                    0,
                                ];
                                ?>
                            <?php endif; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
                <?php if (!empty($html)) : ?>
                    <?php foreach ($html as $bundleID => $node) : ?>
                        <div class="nested bundle-product">
                            <div id="radio:item<%- data._index_ %>_<?= /* @escapeNotVerified */ $bundleID ?>">
                                <div class="table-wrapper">
                                    <table class="data table table-return-items" id="return-items-table-<?= /* @escapeNotVerified */ $bundleID ?>">
                                        <caption class="table-caption"><?= /* @escapeNotVerified */ __('Return items') ?></caption>
                                        <thead>
                                        <tr>
                                            <th class="col product" scope="col"><?= /* @escapeNotVerified */ __('Sub-items') ?></th>
                                            <th class="col remaining qty" scope="col"><?= /* @escapeNotVerified */ __('Remaining Qty') ?></th>
                                            <th class="col qty" scope="col"><?= /* @escapeNotVerified */ __('Qty') ?></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php foreach ($node as $item) : ?>
                                            <tr>
                                                <td data-th="<?= $block->escapeHtml(__('Product')) ?>" class="col product">
                                                    <?php if ($item[3]) : ?>
                                                        <input type="checkbox" disabled>
                                                    <?php else : ?>
                                                        <input id="items[<%- data._index_ %>][<?= /* @escapeNotVerified */ $bundleID ?>][checkbox][item][<?= /* @escapeNotVerified */ $item[0] ?>]" data-validate="{'validate-one-required-by-name':true}"  data-args='{"item" :<?= /* @escapeNotVerified */ $item[0] ?>, "bundleId" : <?= /* @escapeNotVerified */ $bundleID ?>, "index" :<%- data._index_ %>, "initialQty" : <?= $block->escapeHtml($item[2]) ?> }' type="checkbox" value="<?= /* @escapeNotVerified */ $item[0] ?>" class="checkbox change-container-classname" name="validate-one-checkbox-<?= /* @escapeNotVerified */ $bundleID ?>-<%- data._index_ %>" />
                                                    <?php endif; ?>
                                                    <label for="items[<%- data._index_ %>][<?= /* @escapeNotVerified */ $bundleID ?>][checkbox][item][<?= /* @escapeNotVerified */ $item[0] ?>]" class="label <?= ($item[3]) ? 'disabled' : '' ?>"><?= /* @escapeNotVerified */ $item[1] ?></label>
                                                </td>
                                                <td data-th="<?= $block->escapeHtml(__('Remaining Qty')) ?>" class="col remaining qty"><?= /* @escapeNotVerified */ $item[2] ?></td>
                                                <td data-th="<?= $block->escapeHtml(__('Qty')) ?>" class="col qty">
                                                    <?php if (!$item[3]) : ?>
                                                        <input id="items[<%- data._index_ %>][<?= /* @escapeNotVerified */ $bundleID ?>][checkbox][qty][<?= /* @escapeNotVerified */ $item[0] ?>]" name="items[<%- data._index_ %>][items][<?= /* @escapeNotVerified */ $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]) ?>"}'>
                                                    <?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><?= /* @escapeNotVerified */ __('Quantity To Return') ?></span></label>
            <div class="control">
                <input type="number" class="input-text" 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_ %>">
                    <?= /* @escapeNotVerified */ __('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" 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><?= /* @escapeNotVerified */ __('New Return for Order %1', $_order->getIncrementId()) ?></span>
            </legend>

            <div class="field id">
                <span class="label"><span><?= /* @escapeNotVerified */ __('Order ID') ?></span></span>
                <div class="control"><span><?= /* @escapeNotVerified */ $_order->getIncrementId() ?></span></div>
            </div>
            <div class="field name">
                <span class="label"><span><?= /* @escapeNotVerified */ __('Customer Name') ?></span></span>
                <div class="control"><span><?= $block->escapeHtml($_order->getCustomerName()) ?></span></div>
            </div>
            <div class="field email">
                <span class="label"><span><?= /* @escapeNotVerified */ __('Email') ?></span></span>
                <div class="control"><span><?= /* @escapeNotVerified */ $_order->getCustomerEmail() ?></span></div>
            </div>
            <div class="field contact email">
                <label class="label" for="email"><span><?= /* @escapeNotVerified */ $this->helper('Magento\Rma\Helper\Data')->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="<?= /* @escapeNotVerified */ $block->getContactEmail() ?>">
                </div>
            </div>

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

        <fieldset class="fieldset">
            <legend class="legend"><span><?= /* @escapeNotVerified */ __('Return Items Information') ?></span></legend>

            <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><?= /* @escapeNotVerified */ __('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><?= /* @escapeNotVerified */ __('Comments') ?></span></label>
                <div class="control">
                    <textarea id="rma_comment" cols="5" rows="3" name="rma_comment" class="input-text"><?php if ($_data) : ?><?= /* @escapeNotVerified */ $_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": <?= /* @escapeNotVerified */ 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": "<?= /* @escapeNotVerified */ ($totalAvlQty) ?: 0 ?>",
                    "firstItemId": "<?= /* @escapeNotVerified */ $firstItemId ?>",
                    "productType": "<?= /* @escapeNotVerified */ $productType ?>",
                    "availableQuantity": "<?= /* @escapeNotVerified */ ($availableQty) ?: 0 ?>",
                    "prodTypeBundle": "<?= /* @escapeNotVerified */ \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE ?>"
                },
                "validation": {
                     "ignore": ":hidden:not(input[id$='_value'])"
                }
            }
        }
    </script>
</form>