<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

/** @var \Magetop\Advancepreview\Block\CustomProduct $block */
$urls = $block->getPreviewAjaxUrls();
$extraPrice = $urls['extra_price'];
$uploadCustomDesign = $urls['upload_custom_design'];
$customDiscountUrl = $urls['custom_discount_url'];
$tierPriceUrl = $urls['custom_tierprice_url'];
$addWishlistUrl = $urls['add_to_wishlist'].'uenc/'.sha1(time());
$generateProjectId = $urls['generate_project_id'];
$customerGroup = $block->getCustomerGroup();
$_product = $block->getPreviewProductData();
?>

<input type="hidden" id="txt-preview-url-extra-price" value="<?php echo $extraPrice; ?>">
<input type="hidden" id="txt-customer-group" value="<?php echo $customerGroup ?>">
<input type="hidden" id="txt-upload-custom-url" value="<?php echo $uploadCustomDesign ?>">
<input type="hidden" id="txt-custom-discount-url" value="<?php echo $customDiscountUrl ?>">
<input type="hidden" id="txt-custom-tierprice-url" value="<?php echo $tierPriceUrl ?>">
<input type="hidden" id="txt-model-product-id" value="<?php echo $_product->getId(); ?>">
<input type="hidden" id="txt-custom-media-url" value="<?php echo $block->getMediaUrl(); ?>">
<input type="hidden" id="txt-custom-add-wishlist-url" value="<?php echo $addWishlistUrl; ?>">
<input type="hidden" id="txt-custom-gengerate-id" value="<?php echo $generateProjectId; ?>">
<input type="hidden" id="txt-custom-redirect-login-url" value="<?php echo $block->getRefererUrl(); ?>">
<input type="hidden" id="txt-update-item-status-url" value="<?php echo $urls['re_upload_design_url']; ?>">
<input type="hidden" id="txt-save-new-design-url" value="<?php echo $urls['save_new_design_url']; ?>">
<script>
    require([
        'jquery',
        'mgt_advance_preview_helper',
        'mgt_product_preview'
    ],function ($, helper, productPreview) {
        productPreview.init();
    })
</script>
<script>
    require([
        'jquery',
        'Magento_Ui/js/modal/confirm',
        'Magento_Ui/js/modal/modal',
        'Magento_Ui/js/modal/alert',
        'mgt_advance_preview_helper',
    ], function ($,confirmation,modal,alert,helper) {
        var previewPro = {};
        previewPro = {
            version: '2.5',
            upload_custom_url: '',
            media_url: '',
            iframe_url: '',
            default_preview_name: '',
            product_id: 0,
            re_upload_design_url : '',
            save_new_design_url: '',
            new_order_item_modal: '',
            uploadImage : function(zoom, light) {
                var self = this;
                var data = new FormData($('#form-upload-custom-design')[0]);
                var url = self.upload_custom_url;
                var ownFolder = $('#txt-preview-selected').val();
                url += 'custom_folder/'+ownFolder;
                // $('#preview-upload-custom-design').css('display','block');
                // helper.showLoading('advance-preview-loading');
                $('#txt-preview-upload-custom-design').prop('disabled',true);
                $('#loading-page-ready-browser').css('display','flex');
                helper.uploadImages(url, data, '', '', function (response) {
                    console.log(response);
                    if(response.status === 'success') {
                        var previewCustom = self.iframe_url + 'model_preview/'+response.own_design + '/product_id/'+ self.product_id + '/name_preview/'+self.default_preview_name;
                        // console.log(previewCustom);
                        $("#iframe-preview-pro").attr("src", previewCustom);
                        // $('#preview-upload-custom-design').css('display','none');
                        $('#txt-preview-selected').val(response.own_design);
                        $('#txt-customer-upload-design').val(response.base_file);
                        // check if 3d load hide loading...
                        var sec = 0;
                        $("#iframe-preview-pro").contents().find(' #txt-preview-3d-loader').val(0);
                        // helper.showLoading('advance-preview-loading');
                        var timer = setInterval(function () {
                            var is3dloaded =  $("#iframe-preview-pro").contents().find(' #txt-preview-3d-loader').val();
                            // console.log(is3dloaded);

                            if(is3dloaded === '1') {
                                // helper.hideLoading('advance-preview-loading');
                                $('#txt-preview-upload-custom-design').prop('disabled',false);
                                console.log("Done check 3d, stop now");
                                // helper.hideLoading('advance-preview-loading');
                                $('#loading-page-ready-browser').css('display','none');
                                clearInterval(timer);

                            }
                            sec++;
                        },500)
                        setTimeout(function () {
                            clearInterval(timer);
                        },11000)
                    }
                    else {
                        $('#txt-preview-upload-custom-design').prop('disabled',false);
                        $('#loading-page-ready-browser').css('display','none');
                        alert({
                            title: 'Error',
                            content: 'Upload error ! You can upload only a Pdf or AI file'
                        })
                    }

                })
            },
            reUpOrderItemDesign : function() {
                var self = this;
                var data = new FormData($('#form-upload-custom-design')[0]);
                var url = self.re_upload_design_url;
                // $('#demo-3d-test').html('');

                helper.uploadImages(url, data, 'advance-preview-loading', '', function (response) {
                    if(response.status === 'success') {
                        let previewData = response.preview_filed || null;
                        if(previewData) {
                            // console.log(response);
                            var modelPreview = previewData.model_preview;
                            self.new_order_item_modal = modelPreview;
                            var previewCustom = self.iframe_url + 'model_preview/'+response.own_design + '/product_id/'+ self.product_id + '/name_preview/'+self.default_preview_name;
                            $("#iframe-preview-pro").attr("src", previewCustom);
                            $('#btn-preview-re-up-design-print').prop('disabled',false);
                        }

                    }
                    else {
                        alert({
                            title: 'Error',
                            content: 'Upload error ! You can upload only a Pdf or AI file'
                        })
                    }
                })
            },
            saveNewDesignOrderIitem : function() {
                var self = this;
                var data = $('#form-upload-custom-design').serialize();
                var url = self.save_new_design_url + 'new_own/' + self.new_order_item_modal;
                console.log(url);
                // url += 'new_own/' + self.new_order_item_modal;
                helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                    console.log(response);
                    window.location.href = $('#txt-design-item-order-view-url').val();
                })
            },

            initData : function() {
                var self = this;
                self.upload_custom_url = $('#txt-upload-custom-url').val();
                self.media_url = $('#txt-custom-media-url').val();
                self.iframe_url = $('#txt-default-iframe-url').val();
                self.default_preview_name = $('#txt-default-preview-name').val();
                self.product_id = $('#txt-model-product-id').val();
                self.re_upload_design_url = $('#txt-update-item-status-url').val();
                self.save_new_design_url = $('#txt-save-new-design-url').val();
            },
            init: function () {
                var self = this;
                self.initData();
                var is3d = $('#txt-is-3d').val();
                if(is3d !== '1') {
                    return;
                }
                $(".img-preview-standard-model-item").click(function () {
                    var isLoadder = $(this).attr('is-loadder');
                    if(isLoadder === '1') {
                        return false;
                    }
                    $('.img-preview-standard-model-item').attr('is-loadder','0');
                    $(this).attr('is-loadder','1');
                    var previewUrl = $(this).attr('full-preview-model');
                    // console.log(previewUrl);
                    $("#iframe-preview-pro").attr("src", previewUrl);
                    // set preview when add to cart
                    //txt-preview-selected
                    var previewModel = $(this).attr('preview-model');
                    $('#txt-preview-selected').val(previewModel);
                });
                $('#txt-preview-upload-custom-design').change(function () {
                    // console.log("Upload Image choi")
                    self.uploadImage(0, 0);
                })
                // test
                const iframe = document.getElementById("iframe-preview-pro");

                iframe.addEventListener("load", function() {
                    console.log("Finish");
                    // check 3d render in ifram
                });
                var sec1 = 0;
                $('#loading-page-ready-browser').css('display','flex');
                $("#iframe-preview-pro").contents().find(' #txt-preview-3d-loader').val(0);
                // helper.showLoading('advance-preview-loading');
                var timer2 = setInterval(function () {
                    var is3dloaded =  $("#iframe-preview-pro").contents().find(' #txt-preview-3d-loader').val();
                    console.log(sec1, is3dloaded);
                    if(is3dloaded === '1') {
                        // helper.hideLoading('advance-preview-loading');
                        $('#txt-preview-upload-custom-design').prop('disabled',false);
                        console.log("Done check 3d when loading ... , stop now");
                        // helper.hideLoading('advance-preview-loading');
                        $('#loading-page-ready-browser').css('display','none');
                        clearInterval(timer2);

                    }
                    else {
                        $('#loading-page-ready-browser').css('display','flex');
                    }
                    sec1++;
                },500)
                setTimeout(function () {
                    clearInterval(timer2);
                },11000)
                $('#btn-txt-order-item-re-up-design').click(function () {
                    $('#txt-order-item-re-up-design').click();
                })
                $('#txt-order-item-re-up-design').change(function () {
                    self.reUpOrderItemDesign();

                });
                $('#btn-preview-re-up-design-print').click(function () {
                    self.saveNewDesignOrderIitem();
                    $(this).html('Loading..')
                    $(this).prop('disabled',false);
                })
            }
        }
        previewPro.init();

    })
</script>
