<?php
/**
 * Quotes Form.phtml
 *
 * @category  Magetop Extensions
 * @package   Magetop_Quotesystem
 * @author    Magetop Developer
 * @copyright Copyright (c) Magetop (https://www.magetop.com)
 * @license   https://www.magetop.com/license.html
 */

//edit quote at seller end.
$quoteHelper = $block->getHelper();
$params = $block->getParameters();
$entityId = $params["entity_id"];
$quote = $block->getQuoteData($entityId);
$attachments = $quoteHelper->getQuoteAttachmentsArr($quote->getAttachments());
$currencySymbol = $quoteHelper->getBaseCurrencySymbol();
$disabled = true;
$qtyDisabled = false;
$priceDisabled = false;
$statusDisable = false;
$baseCurrency = $quoteHelper->getBaseCurrencyCode();
?>
<?php
if ($block->quoteStatusIsNotSold($quote->getStatus())) {
    $disabled = false;
}
if ($quote->getStatus()== \Magetop\Quotesystem\Model\Quotes::STATUS_SOLD) {
    $qtyDisabled = true;
    $priceDisabled = true;
}
if ($quote->getStatus()== \Magetop\Quotesystem\Model\Quotes::STATUS_DECLINE ||
        $quote->getStatus() == \Magetop\Quotesystem\Model\Quotes::STATUS_APPROVED
    ) {
    $statusDisable = true;
}
?>
<div class="mt_design block">
    <fieldset class="fieldset info mt-fieldset">
        <legend class="legend">
            <?php if ($disabled) { ?>
                <span><?= /* @noEscape */ __('Edit Quote') ?></span>
            <?php } else { ?>
                <span><?= /* @noEscape */ __('View Quote') ?></span>
            <?php } ?>
        </legend>
        <div class="grid">
            <div class="hor-scroll">
                <input type="hidden"
                    class="len"
                    name="id"
                    id="id"
                    value="<?= $escaper->escapeHtml($entityId); ?>"
                />
                <?php   $product = $block->getProductData($quote->getProductId());
                        $imageUrl = $block->imageHelperObj()
                            ->init($product, 'product_listing_thumbnail_preview')
                            ->resize(100, 100)
                            ->getUrl();
                ?>
                <table class="data-table border mt-list-table">
                    <thead>
                        <tr class="first last">
                            <th rowspan="1">
                                <span><?= /* @noEscape */ __("Product"); ?></span>
                            </th>
                            <th rowspan="1">&nbsp;</th>
                            <th colspan="1" class="a-right cart-price-head">
                                <span title="<?= /* @noEscape */ __('Price After Configuration'); ?>">
                                    <?= /* @noEscape */ __("Price"); ?>
                                </span>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="first odd">
                            <td class="product-cart-image">
                                <img alt="<?= $escaper->escapeHtml($product->getName()); ?>"
                                    src="<?= $escaper->escapeUrl($imageUrl) ?>"
                                >
                            </td>
                            <td class="product-cart-info">
                                <h2 class="product-name">
                                <?= $escaper->escapeHtml($product->getName()); ?>
                                </h2>
                                <div class="product-cart-sku">
                                    <span ><?= /* @noEscape */ __("SKU");?> : </span>
                                    <span ><?= $escaper->escapeHtml($product->getSku()); ?></span>
                                </div>
                                <?php
                                    $optionAndPrice = $quoteHelper->getOptionNPrice($product, $quote);
                                    $optionAndPriceArr = explode("~|~", $optionAndPrice);
                                ?>
                                <?php if (isset($optionAndPriceArr)) { ?>
                                    <dl class="item-options"><?= /* @noEscape */ $optionAndPriceArr[0]; ?></dl>
                                <?php } ?>
                            </td>
                            <td class="a-right">
                                <span class="cart-price">
                                    <span class="price">
                                    <?= /* @noEscape */ $quoteHelper->getformattedPrice(
                                        $quote->getProductPrice()
                                    ); ?>
                                    </span>
                                </span>
                            </td>
                        </tr>
                        <tr class="last even">
                            <td colspan="1">
                                <b>
                                    <?= /* @noEscape */ __("Quote Description")." : "; ?>
                                </b>
                            </td>
                            <td colspan="2">
                            <?= $escaper->escapeHtml($quote->getQuoteDesc()); ?>
                            </td>
                        </tr>
                        <tr class="last even">
                            <td colspan="1">
                                <b>
                                    <?= /* @noEscape */ __("Quote Attachments")." : "; ?>
                                </b>
                            </td>
                            <td colspan="2">
                                <?php
                                foreach ($attachments as $attachmentKey => $attachmentVal) {
                                    $attachmentUrl = $quoteHelper->getMediaUrl().'mtquote\files'.$attachmentKey;
                                    ?>
                                    <div>
                                        <a href="<?= $escaper->escapeUrl($attachmentUrl)?>" 
                                            target="blank" 
                                            title="<?= $escaper->escapeHtml($attachmentVal)?>">
                                            <?= $escaper->escapeHtml($attachmentVal)?>
                                        </a>
                                    </div>
                                    <?php
                                } ?>
                            </td>
                        </tr>
                        <tr class="last even">
                            <td colspan="1">
                                <b>
                                    <?= /* @noEscape */ __("Initial Quote Price")." : "; ?>
                                </b>
                            </td>
                            <td colspan="2">
                            <?= $escaper->escapeHtml($currencySymbol.
                            number_format($quote->getInitialQuotePrice(), 2));?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </fieldset>
</div>
<div class="mt_qs_message_container">
    <div class="mt-design">
        <div class="fieldset info mt-fieldset">
            <fieldset class="fieldset">
                <legend class="legend">
                    <span><?= /* @noEscape */ __('Quote Detail') ?></span>
                </legend>
            </fieldset>
            <div class="field required">
                <label class="label admin__field-label">
                    <span>
                        <?= /* @noEscape */ __("Quoted Price")."(".$currencySymbol.")"; ?>
                    </span>
                </label>
                <?php
                if ($quote->getQuoteCurrency() != $baseCurrency) {
                    $price = $quoteHelper->getBaseCurrencyPrice($quote->getQuotePrice(), $quote->getQuoteCurrency());
                } else {
                    $price = $quote->getQuotePrice();
                }
                ?>
                <div class="control">
                    <input type="text"
                        class='input-text required-entry validate-number validate-greater-than-zero'
                        <?= $escaper->escapeHtml(($priceDisabled))?"readonly='readonly'":''?>
                        value="<?= $escaper->escapeHtml($price) ?>"
                        name='quote_price'
                    />
                </div>
            </div>
            <div class="field required">
                <label class="label admin__field-label">
                    <span>
                        <?= /* @noEscape */ __("Quoted Quantity:") ?>
                    </span>
                </label>
                <div class="control">
                    <input type="text"
                        class='input-text required-entry validate-number validate-greater-than-zero 
                        validate-digits-range digits-range-<?= $escaper->escapeHtml($product->getMinQuoteQty())?>-'
                        <?= $escaper->escapeHtml(($qtyDisabled))?"readonly='readonly'":''?>
                        value="<?= $escaper->escapeHtml($quote->getQuoteQty()) ?>"
                        name='quote_qty'
                    />
                    <span class="mt-qs-min-qty"><?=
                                                    $escaper->escapeHtml(
                                                        __(
                                                            'minimum quote quantity limit is %1',
                                                            $product->getMinQuoteQty()
                                                        )
                                                    ); ?></span>
                </div>
            </div>
            <div class="field">
                <label class="label"><?= /* @noEscape */ __('Customer Email') ?>:</label>
                <div class="control">
                    <input type="text"
                        class='input-text'
                        readonly='readonly'
                        value="<?= $escaper->escapeHtml($block->getCustomerData(
                            $quote->getCustomerId()
                        )->getEmail()) ?>"
                        name='customer_email'
                    />
                </div>
            </div>
            <div class="field">
                <label class="label"><?= /* @noEscape */ __('Product Name') ?>:</label>
                <div class="control">
                    <input type="text"
                        class='input-text'
                        readonly='readonly'
                        value="<?= $escaper->escapeHtml($quote->getProductName()) ?>"
                        name='product_name'
                    />
                </div>
            </div>
            <div class="field">
                <label class="required label"><?= /* @noEscape */ __('Status') ?>:</label>
                <div class="control">
                <?php if ($quote->getStatus() == \Magetop\Quotesystem\Model\Quotes::STATUS_SOLD): ?>
                    <input type="text"
                        class='input-text'
                        readonly='readonly'
                        value="<?= /* @noEscape */ __("Sold") ?>"
                        name='status'
                        />
                    <?php elseif ($quote->getStatus() == \Magetop\Quotesystem\Model\Quotes::STATUS_APPROVED):?>
                        <input type="text"
                        class='input-text'
                        readonly='readonly'
                        value="<?= /* @noEscape */ __("Approved") ?>"
                        name='status'
                        />
                    <?php else:?>
                        <?php
                            $statusUnapproved = \Magetop\Quotesystem\Model\Quotes::STATUS_UNAPPROVED;
                            $statusApproved = \Magetop\Quotesystem\Model\Quotes::STATUS_APPROVED;
                            $statusDecline = \Magetop\Quotesystem\Model\Quotes::STATUS_DECLINE;
                        ?>
                        <select name="status">
                            <?php if (!$statusDisable):?>
                            <option value="1" <?= ($quote->getStatus() == $statusUnapproved) ? 'selected' : '' ; ?>>
                                <?= /* @noEscape */ __("Pending"); ?>
                            </option>
                            <?php endif;?>

                            <?php if ($quote->getStatus() != \Magetop\Quotesystem\Model\Quotes::STATUS_APPROVED):?>
                            <option value="2" <?= ($quote->getStatus() == $statusApproved) ? 'selected' : '' ; ?>>
                                <?= /* @noEscape */ __("Approved"); ?>
                            </option>
                            <?php endif;?>
                            <option value="3" <?= ($quote->getStatus() == $statusDecline) ? 'selected' : '' ; ?>>
                                <?= /* @noEscape */ __("Declined"); ?>
                            </option>
                            
                        </select>
                    <?php endif; ?>
                </div>
            </div>
        <?php if (!$disabled) { ?>
            <input type="hidden" name="quote_id" value="<?= $escaper->escapeHtml($entityId) ?>">
            <input type="hidden" name="original_price" value="<?= $escaper->escapeHtml($price) ?>">
                <div class="field required">
                    <label class="label admin__field-label">
                        <span>
                            <?= /* @noEscape */ __("Enter Message:") ?>
                        </span>
                    </label>
                    <div class="control">
                        <textarea id="mt_qs_msg_area"
                            type="text"
                            class="required-entry input-text"
                            name="quote_message"
                            style="resize:none;width:100%;"
                        ></textarea>
                    </div>
                </div>
                <div class="field">
                    <label class="label admin__field-label">
                        <span>
                            <?= /* @noEscape */ __("Upload Attachments:") ?>
                        </span>
                    </label>
                    <div class="control mt-file-field-container">
                        <label class="mt-file-label mt-quote-primary-btn">
                            <?= /* @noEscape */ __('Add Attachment(s)') ?>
                            <input type="file" name="files" class="mt-file-field" id="mt-file-field" 
                            data-url="<?=
                                        $escaper->escapeUrl(
                                            $block->getUrl(
                                                'quotesystem/managequotes/fileUpload',
                                                ['_secure' => $block->getRequest()->isSecure()]
                                            )
                                        ) ?>" multiple="multiple"/>
                        </label>
                    </div>
                </div>
        <?php } ?>
        </div>
    </div>
</div>
<script id="mt-file-field-template" type="text/x-magento-template">
    <div class="mt-uploaded-file">
        <span class="mt-uploaded-file-style mt-quote-primary-btn"><%- data.extension %></span>
        <span class="mt-uploaded-file-name"><%- data.name %></span>
        <input type="hidden" name="attachments[]" value="<%- data.file %>" class="mt-uploaded-file-value"/>
        <span class="mt-uploaded-file-del"></span>
    </div>
</script>
<script id="mt-file-field-uploader-template" type="text/x-magento-template">
    <div id="<%- data.id %>" class="mt-uploaded-file-row">
        <img src="<?= /* @noEscape */ $block->getViewFileUrl('Magetop_Quotesystem/images/ajax-loader-big.gif')?>"/>
    </div>
</script>
<script>
    require([
        "jquery",
        'mage/template',
        'Magento_Ui/js/modal/alert',
        "jquery/ui",
        "jquery/file-uploader"
    ], function ($, mageTemplate, alert) {
        $('#mt-file-field').fileupload({
            dataType: 'json',
            sequentialUploads: true,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|pdf|doc|zip)$/i,
            add: function (e, data) {
                var progressTmpl = mageTemplate('#mt-file-field-uploader-template'),
                    tmpl;
                var thisObj = $(this);

                $.each(data.files, function (index, file) {
                    data.fileId = Math.random().toString(33).substr(2, 18);

                    tmpl = progressTmpl({
                        data: {
                            id: data.fileId
                        }
                    });

                    if ($('.mt-uploaded-file').length) {
                        var indexKey = 1;
                        $('.mt-uploaded-file').each(function () {
                            if (indexKey == 1) {
                                $(this).before(tmpl);
                            }
                            indexKey++;
                        });
                    } else {
                        $(tmpl).appendTo('.mt-file-field-container');
                    }
                });

                thisObj.fileupload('process', data).done(function () {
                    data.submit();
                });
            },
            done: function (e, data) {
                if (data.result && !data.result.error) {
                    var progressTmpl = mageTemplate('#mt-file-field-template'),
                    tmpl;
                    tmpl = progressTmpl({
                        data: {
                            name: data.result.name,
                            file: data.result.file,
                            extension: data.result.type
                        }
                    });

                    $(tmpl).appendTo('.mt-file-field-container');
                } else {
                    $('#' + data.fileId)
                        .delay(2000)
                        .hide('highlight');
                    alert({
                        content: $.mage.__('Unable to add attachment due to file size or file type issue.')
                    });
                }
                $('#' + data.fileId).remove();
            },
            progress: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
                $(progressSelector).css('width', progress + '%');
            },
            fail: function (e, data) {
                var progressSelector = '#' + data.fileId;
                $(progressSelector).removeClass('upload-progress').addClass('upload-failure')
                    .delay(2000)
                    .hide('highlight')
                    .remove();
            }
        });
        $('#mt-file-field').fileupload('option', {
            process: [{
                action: 'load',
                fileTypes: /^image\/(gif|jpe?g|png|pdf|doc|zip)$/
            }, {
                action: 'resize',
                maxWidth: "<?= \Magento\Framework\File\Uploader::MAX_IMAGE_WIDTH?>",
                maxHeight: "<?= \Magento\Framework\File\Uploader::MAX_IMAGE_HEIGHT?>"
            }, {
                action: 'save'
            }]
        });

        $('.mt-file-field-container').on("click", ".mt-uploaded-file-del", function() {
            var thisObj = $(this);
            var fileName = $(this).parent('.mt-uploaded-file').find('.mt-uploaded-file-value').val();
            $.ajax({
                url: "<?= $escaper->escapeUrl($block->getUrl(
                    'quotesystem/managequotes/fileDelete',
                    ['_secure' => $block->getRequest()->isSecure()]
                ))?>",
                data: { file_name : fileName },
                type: "post",
                datatype: "json",
                showLoader: true,
                success: function (data) {
                    thisObj.parent('.mt-uploaded-file').remove();
                },
                error: function (data) {
                    thisObj.parent('.mt-uploaded-file').remove();
                }
            });
        });
    });
</script>
<script>
    require([
        "jquery",
        "mage/mage",
        ], function($mt_jq){
        var dataForm = $mt_jq('#form-quote');
        dataForm.mage('validation', {});
        jQuery("#save_butn").on("click",function(){
            if($mt_jq("#form-quote").valid()!=false){
                jQuery("#save_butn").attr("disabled","disabled");
                jQuery("#form-quote").submit();
            }
        });
    });
</script>
<script>
    require([
        "jquery", 
        "mage/mage",
        ], function($mt_jq){
            
        jQuery("#save").on("click",function(e){ 
            if($mt_jq("#edit_form").valid()!=false){ 
                e.preventDefault();
                var status = $mt_jq("select[name='status'] option:selected").val();
                var oldStatus = "<?=  /* @noEscape */ __($quote->getStatus()) ?>";
                if (!status) {
                    status = $mt_jq("input[name='status']").val();
                }
                if (status == "Approved") {
                    status = 2;
                }
                if (status != oldStatus) {
                    var r = "";
                    if (status == 2) {
                        var surity = 'Are you sure you want to Approve the quote(s)? After approving this quote,';
                        var messageConfirmation = surity+' you will not be able to decline it?';
                        r = confirm($mt_jq.mage.__(messageConfirmation));
                    } else {
                        r = confirm($mt_jq.mage.__('Are you sure Decline the quote(s)?'));
                    }
                    if (r == true) {
                        jQuery("#save").attr("disabled","disabled");
                        return;
                    } else {
                        stopEvent(e);
                    } 
                } 
                return false;
            }
        });
    });
</script>

