<?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();
//$is3D = $_product->getData('pcto_is_3d');;
$previewModels = $block->getPreviewByProductId($_product->getId());
$namePreviewModel = '';
$texture =  '';
$light = 0;
$zoom = 0;
$defaultPreviewId = 0;
$previewNames = [];
if($previewModels && $previewModels->getSize() > 0) {
    $defaultPreviewId = $previewModels->getFirstItem()->getId();
    $namePreviewModel = $previewModels->getFirstItem()->getData('file_preview');
    $texture = $previewModels->getFirstItem()->getData('texture');
    $light = $previewModels->getFirstItem()->getData('preview_light');
    $zoom = $previewModels->getFirstItem()->getData('preview_zoom');
    foreach ($previewModels as $previewModel) {
        $previewNames[] = [
          'id'=>$previewModel->getData('folder_preview'),
            'filename'=>$previewModel->getData('file_preview')
        ];
    }
}
$textPreviewName = count($previewNames) ? json_encode($previewNames) : '{}';
$is3D = 0;
if($_product->getData('pcto_is_3d') == 1 && $namePreviewModel != '' && $light > 0 && $zoom > 0) {
    $is3D = 1;
}
?>
<!--hidden url-->
<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-list-preview-file" value="<?php echo htmlentities($textPreviewName); ?>">
<input type="hidden" id="txt-default-preview-id" value="<?php echo $defaultPreviewId; ?>">
<input type="hidden" id="txt-preview-option-url" value="<?php echo $urls['preview_option_url']; ?>">
<input type="hidden" id="txt-update-item-status-url" value="<?php echo $urls['re_upload_design_url']; ?>">
<input type="hidden" id="txt-clone-design-url" value="<?php echo $urls['clone_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>
<?php if($is3D == 1) : ?>
<script>

    require([
        'jquery',
        'Magento_Ui/js/modal/confirm',
        'Magento_Ui/js/modal/modal',
        'Magento_Ui/js/modal/alert',
        'mgt_advance_preview_helper',
        'product_preview_pro',
    ],function ($,confirmation,modal,alert,helper, productPreviewPro) {
        var three3D = {
            version: '2.5',
            product_id: 0,
            item_id: 0,
            is_3d: false,
            upload_custom_url: '',
            name_preview: '',
            own_design: '',
            standard_model: '',
            preview_light: 0,
            preview_zoom: 0,
            preview_element_id: '',
            default_model: '',
            preview_lists: [],
            update_order_item_design_id: 0,
            re_upload_design_url : '',
            clone_design_url: '',
            save_new_design_url: '',
            default_your_custom_model: '', // if custom design and click desgin service
            default_standard_model: '',
            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;
                $('#demo-3d-test').html('');
                // $('#'+previewElementId).html('');
                $('#preview-uploading-custom-design').css('display','block');
                helper.uploadImages(url, data, 'advance-preview-loading', '', function (response) {
                    console.log("Uopdate Image", response);
                    if(response.status === 'success') {
                        var productId = self.product_id;
                        var ownModel = response.own_design;
                        self.own_design = ownModel;
                        var namePreview = self.name_preview;
                        // var ownModel = self.own_design;
                        var owndeisgn = 'product_id_'+productId+'/'+ownModel+'/'+namePreview;
                        var previewElementId = self.preview_element_id;
                        $('#txt-preview-selected').val(ownModel);
                        $('#txt-customer-upload-design').val(response.base_file);
                        console.log(owndeisgn);
                        // helper.showLoading('advance-preview-loading');
                        setTimeout(function () {
                            console.log('Show Preview Design 1000');
                            productPreviewPro.productPreviewImage(owndeisgn, zoom, light,previewElementId);
                            // helper.hideLoading('advance-preview-loading');
                            $('#preview-uploading-custom-design').css('display','none');
                        },200)
                        if($('#btn-preview-re-up-design-print').length) {
                            $('#btn-preview-re-up-design-print').prop('disabled',false);
                        }
                    }
                })
            },
            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) {
                            helper.showLoading('advance-preview-loading')
                            $('#demo-3d-test').html('');
                            var elementId = 'demo-3d-test';
                            var namePreview = previewData.name_preview;
                            var light = previewData.light;
                            var zoom = previewData.zoom
                            var modelPreview = previewData.model_preview;
                            var productId = previewData.product_id
                            self.new_order_item_modal = modelPreview;
                            // light = parseInt(light);
                            // zoom = parseInt(zoom);

                            var defaultModel = 'product_id_'+productId+'/'+modelPreview+'/'+namePreview;
                            console.log(elementId,light,zoom,defaultModel);
                             productPreviewPro.productPreviewImage(defaultModel, zoom, light,elementId);
                            // helper.showLoading('advance-preview-loading');
                            // $('#btn-preview-re-up-design-print').html('Redirecting....')
                            $('#btn-preview-re-up-design-print').prop('disabled',false);
                          /*  setTimeout(function () {
                                // productPreviewPro.productPreviewImage(defaultModel, zoom, light,elementId);
                                //  window.location.href = $('#txt-design-item-order-view-url').val();
                            },2000)*/
                        }
                    }
                })
            },
            cloneDesign : function(defaultModel, productId, callback) {
                var self = this;
                var data = {
                  default_model: defaultModel,
                  product_id: productId
                };
                var url = self.clone_design_url;
                helper.doRequest(url,data,'advance-preview-loading','',function (response) {
                    // console.log(response);
                   callback(response)
                })
            },
            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;
                var reupId = $('#txt-design-item-id-upload-print').val();
                if(!isNaN(reupId)) {
                    reupId = parseInt(reupId);
                }
                else {
                    reupId = 0;
                }
                console.log("reup id ", reupId);
                if(reupId > 0) {
                    $('.product-info-price').css('display','none');
                }
                self.product_id = $('#txt-model-product-id').val();
                self.is_3d = $('#txt-is-3d').val() === '1' ? true : false;
                self.upload_custom_url = $('#txt-upload-custom-url').val();
                self.name_preview = $('#txt-name-preview-model').val();

                var previewLight = $('#txt-name-preview-light').val();
                var previewZoom = $('#txt-name-preview-zoom').val();
                self.preview_zoom = parseInt(previewZoom);
                self.preview_light = parseInt(previewLight);
                self.preview_element_id = 'demo-3d-test';
                // self.default_model = $('#txt-preview-default-model').val();
                var itemId = $('#txt-preview-item-id').val();
                itemId = parseInt(itemId);
                self.item_id = itemId;
                self.standard_model = 'model-'+ $('#txt-preview-default-model').val() ;
                if(itemId > 0) {
                    self.standard_model = $('#txt-preview-selected').val();
                    self.default_your_custom_model = $('#txt-preview-selected').val();
                }
                if(reupId > 0) {
                    self.standard_model = $('#txt-preview-default-model').val() ;
                }
                var previewLists = $('#txt-list-preview-file').val();
                if(previewLists !== undefined) {
                    self.preview_lists = JSON.parse(previewLists);
                }
                var designOrderItemDesignId = $('#txt-design-item-id-upload-print').val();
                self.update_order_item_design_id = parseInt(designOrderItemDesignId);
                self.re_upload_design_url = $('#txt-update-item-status-url').val();
                self.clone_design_url = $('#txt-clone-design-url').val();
                self.save_new_design_url = $('#txt-save-new-design-url').val();
                console.log( previewLists);
            },
            init: function () {
                var self = this;
                console.log("3D load Before check")
                let is3D =  $('#txt-is-3d').val() === '1' ? true : false;
                if(is3D === true && $('#txt-name-preview-model').length && $('#txt-name-preview-model').val() !== '') {
                    // var defaultModelPreview = 'model-' + self.default_model;

                    var defaultTextureWidth = $('#txt-preview-width-default').val();
                    var defaultTextureHeight = $('#txt-preview-width-default').val();
                    var defaultTexture = $('#txt-preview-texture-default').val();
                    self.initData();
                    var namePreview = self.name_preview;
                    var productId = self.product_id;
                    var defaultModel = 'product_id_'+productId+'/'+self.standard_model+'/'+namePreview;
                    console.log("3D load Before check after check ", defaultModel, self.standard_model)
                    var zoom = self.preview_zoom;
                    var light = self.preview_light;
                    var previewElementId = self.preview_element_id;
                    productPreviewPro.productPreviewImage(defaultModel, zoom, light,previewElementId);

                    $('.img-preview-standard-model-item').click(function () {
                        var previewId = $(this).attr('three-id');
                        var fileGltf = '';
                        let mZoom = $(this).attr('zoom');
                        let mLight = $(this).attr('light');
                        let mTextureWidth = $(this).attr('texture-width');
                        let mTextureHeight = $(this).attr('texture-height');
                        let mTexture = $(this).attr('texture-image');
                        if(self.preview_lists) {
                            for(var tmpPreview of self.preview_lists) {
                                if(tmpPreview.id === previewId) {
                                    fileGltf = tmpPreview.filename
                                    break;
                                }
                            }
                        }
                        console.log(fileGltf);
                        if(fileGltf !== '') {

                            var model = 'product_id_'+productId+'/model-'+previewId+'/'+fileGltf;
                            // self.standard_model = 'model-'+previewId;
                            var previewElementId = self.preview_element_id;
                            $('#'+previewElementId).html('');
                            $('#txt-preview-selected').val('model-'+previewId);
                            $('#txt-preview-file-selected').val(fileGltf);
                            $('#txt-preview-zoom-selected').val(mZoom);
                            $('#txt-preview-light-selected').val(mLight);
                            $('#txt-preview-width-selected').val(mTextureWidth);
                            $('#txt-preview-height-selected').val(mTextureHeight);
                            $('#txt-preview-texture-selected').val(mTexture);
                            mZoom = parseInt(mZoom);
                            mLight = parseInt(mLight)
                            console.log(model, mZoom, mLight,previewElementId);
                            productPreviewPro.productPreviewImage(model, mZoom, mLight,previewElementId);
                        }
                        else {
                            alert({
                                title: 'Error',
                                content: 'Order not found'
                            })
                        }

                    })
                    $('#txt-preview-upload-custom-design').change(function () {
                        // console.log("Upload Image choi")
                        self.uploadImage(zoom, light);
                    })
                    $('#btn-prview-own-design').click(function () {
                        $(this).find('.submit.primary').removeClass('unselected');
                        $('#btn-prview-standrad-design').find('.submit.primary').addClass('unselected');
                        var owrPreivewId = self.default_your_custom_model;
                        if(owrPreivewId !== '') {
                            $('#txt-preview-selected').val(owrPreivewId);
                            $('#txt-preview-file-selected').val(namePreview);
                            $('#txt-preview-zoom-selected').val(zoom);
                            $('#txt-preview-light-selected').val(light);
                            $('#txt-preview-width-selected').val(defaultTextureWidth);
                            $('#txt-preview-height-selected').val(defaultTextureHeight);
                            $('#txt-preview-texture-default').val(defaultTexture);
                            var modelOwn = 'product_id_'+productId+'/'+owrPreivewId + '/'+namePreview;
                            var previewElementId = self.preview_element_id;
                            $('#'+previewElementId).html('');
                            console.log('OwnDeisng', modelOwn, zoom, light,previewElementId);
                            productPreviewPro.productPreviewImage(modelOwn, zoom, light,previewElementId);
                        }
                        else {
                            console.log('Cutomize not found, need generate ');
                          /*  owrPreivewId = 'model-'+$('#txt-preview-default-model').val();
                            if(self.item_id > 0) {
                                owrPreivewId = $('#txt-preview-selected').val();
                                self.own_design = owrPreivewId;
                            }*/
                            var tmpDefaultPreviewOrder = $('#txt-preview-default-model').val();
                            self.cloneDesign(tmpDefaultPreviewOrder, self.product_id,function (response) {
                                // console.log("KEKEKEK");
                                if(response.status === 'success') {
                                    self.own_design = response.clone_folder;
                                    self.default_your_custom_model = response.clone_folder;
                                    $('#txt-preview-selected').val(self.own_design);
                                    // $('#txt-preview-selected').val(owrPreivewId);
                                    $('#txt-preview-file-selected').val(namePreview);
                                    $('#txt-preview-zoom-selected').val(zoom);
                                    $('#txt-preview-light-selected').val(light);
                                    $('#txt-preview-width-selected').val(defaultTextureWidth);
                                    $('#txt-preview-height-selected').val(defaultTextureHeight);
                                    $('#txt-preview-texture-default').val(defaultTexture);
                                    var modelOwn = 'product_id_'+productId+'/'+self.own_design + '/'+namePreview;
                                    var previewElementId = self.preview_element_id;
                                    $('#'+previewElementId).html('');
                                    console.log('OwnDeisng', modelOwn, zoom, light,previewElementId);
                                    productPreviewPro.productPreviewImage(modelOwn, zoom, light,previewElementId);
                                }
                            })

                        }


                        // self.init3DModel(modelOwn, zoom, light);
                    })
                    /*$('input.txt-preview-extra-option').click(function () {

                        // self.getExtraPrice();
                        var isShowDesignSericeNote = false;
                        var isDesignService = $(this).attr('is-desing-service');
                        if(isDesignService === '1') {
                            if($(this).is(":checked")) {
                                $('#txt-preview-is-design-service').val(1);
                                isShowDesignSericeNote = false;
                            }

                        }
                        if(isShowDesignSericeNote) {
                            $('#txt-customer-upload-design').val('');
                            self.own_design = self.default_your_custom_model;
                            // self.default_your_custom_model = response.clone_folder;
                            $('#txt-preview-selected').val(self.own_design);
                             $('#txt-preview-selected').val(self.own_design);
                            $('#txt-preview-file-selected').val(namePreview);
                            $('#txt-preview-zoom-selected').val(zoom);
                            $('#txt-preview-light-selected').val(light);
                            $('#txt-preview-width-selected').val(defaultTextureWidth);
                            $('#txt-preview-height-selected').val(defaultTextureHeight);
                            $('#txt-preview-texture-default').val(defaultTexture);
                            var modelOwn = 'product_id_'+productId+'/'+self.own_design + '/'+namePreview;
                            var previewElementId = self.preview_element_id;
                            $('#'+previewElementId).html('');
                            console.log('OwnDeisng', modelOwn, zoom, light,previewElementId);
                            productPreviewPro.productPreviewImage(modelOwn, zoom, light,previewElementId);
                        }

                    })*/
                    $('#btn-prview-standrad-design').click(function () {
                        $(this).find('.submit.primary').removeClass('unselected');
                        $('#btn-prview-own-design').find('.submit.primary').addClass('unselected');
                        var modelStandard = 'product_id_'+productId+'/'+self.standard_model + '/'+namePreview;
                        // console.log(modelStandard);
                        $('#txt-preview-selected').val(self.standard_model);
                        $('#txt-preview-file-selected').val(namePreview);
                        $('#txt-preview-zoom-selected').val(zoom);
                        $('#txt-preview-light-selected').val(light);
                        $('#txt-preview-width-selected').val(defaultTextureWidth);
                        $('#txt-preview-height-selected').val(defaultTextureHeight);
                        $('#txt-preview-texture-default').val(defaultTexture);
                        var previewElementId = self.preview_element_id;
                        $('#'+previewElementId).html('');
                        productPreviewPro.productPreviewImage(modelStandard, zoom, light,previewElementId);
                    })
                    $('#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);
                    })
                    /*setTimeout(function () {
                        console.log(self.update_order_item_design_id);
                        if(self.update_order_item_design_id > 0) {
                            $('#btn-prview-own-design').click();
                        }
                    },500)*/
                    if(self.item_id > 0) {
                        /*console.log("EDIT CAR%D 3d")
                        $('.txt-preview-extra-option').click(function () {
                            var isDesignService = $(this).attr('is-desing-service') || '0';
                            console.log(isDesignService);
                            if(isDesignService === '1') {
                                var tmpEditCartPrviewEdit = '';
                                if($(this).is(":checked") === true) {
                                    // var previewWitoutPint = '';
                                    if(self.default_standard_model === '') {
                                        var tmpDefaultPreviewOrder = $('#txt-preview-default-model').val();
                                        self.cloneDesign(tmpDefaultPreviewOrder, self.product_id, function (response) {
                                            self.default_standard_model = response.clone_folder;
                                            $('#txt-preview-selected').val(response.clone_folder);
                                            $('#'+previewElementId).html('');
                                            tmpEditCartPrviewEdit = 'product_id_'+productId+'/'+ response.clone_folder + '/'+namePreview;
                                            productPreviewPro.productPreviewImage(tmpEditCartPrviewEdit, zoom, light,previewElementId);
                                        })
                                    }
                                    else {
                                        $('#'+previewElementId).html('');
                                        tmpEditCartPrviewEdit = 'product_id_'+productId+'/'+ self.default_standard_model + '/'+namePreview;
                                        productPreviewPro.productPreviewImage(tmpEditCartPrviewEdit, zoom, light,previewElementId);
                                        $('#txt-preview-selected').val(self.default_standard_model);

                                    }
                                    console.log( zoom, light,previewElementId);
                                }
                                else {
                                    $('#'+previewElementId).html('');

                                    tmpEditCartPrviewEdit = 'product_id_'+productId+'/'+ self.default_your_custom_model + '/'+namePreview;
                                    productPreviewPro.productPreviewImage(tmpEditCartPrviewEdit, zoom, light,previewElementId);
                                    $('#txt-preview-selected').val(self.default_your_custom_model);
                                }
                            }

                        })*/
                    }
                }

            },
        }
        three3D.init();

    })
</script>
<?php endif; ?>
