<?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 */
//echo get_class($block);
$tierPrices = $block->getTierPrice();
$jsonTirPrice = '{}';
if(count($tierPrices)) {
    $jsonTirPrice = $block->convertJsonEncode($tierPrices);
}
//test
$mediaPath = $block->getMediaPath();
$extraOptions = @file_get_contents($mediaPath . 'previews/b2c_option_product.json');
$extraOptions = (array)json_decode($extraOptions);

$extraPriceOptions = @file_get_contents($mediaPath . 'previews/prices.json');
$extraPriceOptions =  (array)json_decode($extraPriceOptions);

$product = $block->getPreviewProductData();
$customerGroup = $block->getCustomerGroup();
$term = $block->getCustomerPaymentTerm();

//echo (string)$previewDiscounts->getSelect();
$minFirstQty = 0;
$maxFirstQty = 0;
if(count($tierPrices)) {
    $minFirstQty = 1;
    foreach ($tierPrices as $tierPrice) {
        $maxFirstQty = $tierPrice['price_qty'];
        break;
    }
}
$previewModels = $block->getPreviewByProductId($product->getId());
$folderPreview = '';
$fileNamePreview = '';
$texture = '';
$light = 0;
$zoom = 0;
$textureWidth = 0;
$textureHeight = 0;
if($previewModels && $previewModels->getSize() > 0) {
    $firstItem = $previewModels->getFirstItem();
    foreach ($previewModels as $previewModel) {
        if($previewModel->getData('is_default') == 1) {
            $defaultPreviewItem = $firstItem;
            break;
        }
    }
    if($defaultPreviewItem == null) {
        $defaultPreviewItem = $firstItem;
    }
//     $namePreviewModel = $defaultPreviewItem->getData('file_preview');
    $texture = $defaultPreviewItem->getData('texture');
    $light = $defaultPreviewItem->getData('preview_light');
    $zoom = $defaultPreviewItem->getData('preview_zoom');
    $textureWidth = $defaultPreviewItem->getData('texture_width');
    $textureHeight = $defaultPreviewItem->getData('texture_height');
    $folderPreview = 'model-'.$defaultPreviewItem->getData('folder_preview');
    $fileNamePreview = $defaultPreviewItem->getData('file_preview');
}
$previewParams = $block->getPreviewItemRequest();
/*echo '<pre>';
    print_r($previewParams);
echo '</pre>';*/
if(isset($previewParams['item']) && $previewParams['item'] > 0) {
    $folderPreview = isset($previewParams['txt_preview_selected']) ? $previewParams['txt_preview_selected'] : '';
}
$additionOptionParams = isset($previewParams['preview_additional_options']) ? $previewParams['preview_additional_options'] : [];
$finalPrice = 0;
$dailyShippings = $block->getDailyShipping($product->getId());
$isOffer = isset($previewParams['is_offer']) ? $previewParams['is_offer'] : 0;
$offerId = isset($previewParams['offer_id']) ? $previewParams['offer_id'] : 0;
$customQty = isset($previewParams['mgt_custom_qty']) ? $previewParams['mgt_custom_qty'] : (isset($previewParams['qty']) ? $previewParams['qty'] : 1);
$isUpdateDesignOrder = $block->getRequest()->getParam('re_up',0);

?>
<?php if($product != null) : ?>
    <?php
    $allExtraCustompPrice = (float)$product->getData('preview_additional_options') + (float)$product->getData('pcto_shipping_price') + (float)$product->getData('pcto_shipping_price');
    $previewAdditionOptions = $block->getPreviewAdditionalOptions($product->getId());
    ?>
    <input type="hidden" name="extra_option_all_price" value="<?php echo $allExtraCustompPrice; ?>">
    <input type="hidden" id="txt-preview-type" name="txt_preview_type" value="<?php echo isset($previewParams['txt_preview_type']) ? $previewParams['txt_preview_type'] : ''; ?>">
    <div class="custom-tier-prices" id="custom-tier-prices-content">

    </div>
    <div class="mgt-custom-box-qty">
    <div class="mgt-custom-box-qty no-margin-top">
        <div class="mgt-custom-box-qty-item">
            <div class="mgt-custom-box-qty-item-col">
                <?php echo __('Quantity') ?>
            </div>
            <div class="mgt-custom-box-qty-item-col-input">
                <input type="number" oninput="this.value = this.value.replace(/[^0-9]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==6 && event.keyCode!=8) return false;" id="mgt-custom-qty" value="<?php echo $customQty ?>" name="mgt_custom_qty" class="input-text qty required-entry" data-validate="{required-number:true}">
                <button type="button" id="mgt-custom-qty-update" style="display: none"><?php echo __('Refresh') ?></button>
            </div>
            <div class="mgt-custom-box-qty-item-col">
                <?php echo __('Pcs') ?>
            </div>
        </div>
    </div>
        <div class="delivery-time">
            <label for="txt-daily-shipping"><strong><?php echo __('Delivery time') ?></strong></label>
            <select id="txt-daily-shipping" name="txt_daily_shipping">
                <?php foreach ($dailyShippings as $dailyShipping) : ?>
                    <option value="<?php echo $dailyShipping->getId() ?>" <?php if(isset($previewParams['txt_daily_shipping']) && $previewParams['txt_daily_shipping'] == $dailyShipping->getId()) { ?> selected="selected" <?php } ?>><?php echo __($dailyShipping->getData('delivery_type')) ?></option>
                <?php endforeach; ?>

            </select>
        </div>
    <div class="mgt-project-extra-options" id="preview-project-extra-options" style="display: none">
        <?php if($previewAdditionOptions && $previewAdditionOptions->getSize() > 0) :  ?>
            <?php $ip = 0; ?>
            <?php foreach ($previewAdditionOptions as $additionOption) : ?>
                <?php
                $isDesignService = 0;
                if($ip == $previewAdditionOptions->getSize() - 1) {
                    $isDesignService = 1;
                }
                $additionOptionTitle = $additionOption->getData('title');
                if($additionOptionTitle == '') {
                    continue;
                }
                $additionOptionTitle = trim($additionOption->getData('title'));
                ?>
                <div class="mgt-project-extra-option mgt-project-extra-option-first">
                    <div class="mgt-project-extra-option-col mgt-project-extra-option-col-first">
                        <input type="checkbox" class="txt-preview-extra-option" is-desing-service="<?php echo $isDesignService; ?>" id="txt-preview-extra-option-additional-<?php echo $additionOption->getId(); ?>" name="preview_additional_options[]" value="<?php echo $additionOption->getId(); ?>" <?php echo in_array($additionOption->getId(), $additionOptionParams) ? 'checked="checked"' : ''; ?> <?php if($additionOptionTitle == "5C transparent"){ if($additionOption->getData('fivec_enabale') == 0){ echo "disabled"; }}?> />
                    </div>
                    <div class="mgt-project-extra-option-col">
                        <label style="<?php if($additionOptionTitle == "5C transparent"){ if($additionOption->getData('fivec_enabale') == 0){ echo "color:gray"; }}?>" for="txt-preview-extra-option-additional-<?php echo $additionOption->getId(); ?> "><?php echo __($additionOptionTitle) ?></label>
                    </div>
                    <div class="mgt-project-extra-option-col mgt-project-extra-option-col-last">
                        <a href="javascript:;" data-toggle="preview-tooltip" title="<?php echo __($additionOption->getData('description')) ?>"><i class="fas fa-info-circle"></i></a>
                    </div>
                </div>
                <?php if($isDesignService == 1) : ?>
                    <span id="txt-design-service-note" <?php echo in_array($additionOption->getId(), $additionOptionParams) ? '' : 'style="display: none"'; ?>><?php echo __('After you place an order, our graphic department will contact you for further information.') ?></span>
                <?php endif; ?>
            <?php $ip++; ?>
            <?php endforeach; ?>
        <?php endif; ?>


    </div>

    <div class="mgt-project-price-options" id="mgt-project-discount-options" style="">


    </div>
    <div class="mgt-custom-box-project-name">
        <label><strong><?php echo __('Project name') ?><span style="color: red;">*</span></strong></label>
        <input type="text" id="mgt-custom-project-name" autocomplete="off" onkeypress="return characterWithSpaceAddress(event);" name="custom_project_name" value="<?php echo isset($previewParams['custom_project_name']) ? $previewParams['custom_project_name'] : ''; ?>" placeholder="<?php echo __('Enter project name') ?>" class="input-text" data-validate="{required:true}" maxlength="40">
    </div>
    <div class="mgt-custom-box-project-name request-sample">
        <input type="checkbox" class="checkbox" id="txt-is-request-sample" value="1" <?php echo $customQty < 4 ? 'checked' : ''; ?> name="txt_is_request_sample">
        <label for="txt-is-request-sample"><?php echo __('Request for sample product(s) from 1 to 3') ?></label>
    </div>
    <?php if($isUpdateDesignOrder > 0)  : ?>
        <button type="button"><?php echo __('Submit') ?></button>
    <?php endif; ?>
    <input type="hidden" id="txt-tier-prices" name="txt_preview_tiers_price" value="<?php echo htmlentities($jsonTirPrice); ?>">
    <input type="hidden" name="txt_pcto_discount" value="<?php echo $product->getData('pcto_discount'); ?>">

<!--     <div class="preview-total-price-content">
        <div class="preview-total-price-text">
            <?php echo __('Gesammtpreis') ?>
        </div>
        <div id="preview-total-price-value">
            <?php echo $block->convertNumberToPrice($product->getFinalPrice()); ?>
        </div>
    </div> -->


<?php endif; ?>
<input type="hidden" id="txt-tier-fist-min-qty" value="<?php echo $minFirstQty ?>">
<input type="hidden" id="txt-tier-fist-max-qty" value="<?php echo $maxFirstQty ?>">
<input type="hidden" name="txt_mgt_preview_customer_group" value="<?php echo $customerGroup; ?>">
<input type="hidden" id="txt-custom-preview-design-type" name="txt_custom_preview_design_type" value="<?php echo isset($previewParams['txt_custom_preview_design_type']) ? $previewParams['txt_custom_preview_design_type'] : '' ?>">
<!--<input type="hidden" id="txt-preview-selected" name="txt_preview_selected" value="<?php /*echo $folderPreview; */?>">-->
<input type="hidden" id="txt-preview-name-selected" name="txt_preview_name_selected" value="<?php echo $fileNamePreview; ?>">
<input type="hidden" id="txt-preview-item-id" name="txt_preview_item_id" value="<?php echo $previewParams['item']; ?>">
<input type="hidden" id="txt-project-generate" name="text_project_generate" value="<?php echo isset($previewParams['text_project_generate']) ? $previewParams['text_project_generate'] : '' ?>">
<input type="hidden" id="txt-project-final-price" name="txt_project_final_price" value="0">
<input type="hidden"  name="request_offer_id" value="<?php echo $block->getStoreId().time(); ?>">
<input type="hidden"  id="txt-is-offer" value="<?php echo $isOffer; ?>">
<input type="hidden"  name="custom_offer_id" value="<?php echo $offerId; ?>">
<input type="hidden" id="txt-customer-upload-design" name="customer_upload_design" value="<?php echo isset($previewParams['customer_upload_design']) ? $previewParams['customer_upload_design'] : ''; ?>">
<!--Defalt 3d -->
<input type="hidden" id="txt-preview-default" name="txt_preview_default" value="<?php echo $folderPreview; ?>">
<input type="hidden" id="txt-preview-file-default" name="txt_preview_file_default" value="<?php echo $fileNamePreview; ?>">
<input type="hidden" id="txt-payment-term" name="txt-payment-term" value="<?php echo $term; ?>">
<input type="hidden" id="txt-preview-zoom-default" name="txt_preview_zoom_default" value="<?php echo $zoom; ?>">
<input type="hidden" id="txt-preview-width-default" name="txt_preview_width_default" value="<?php echo $textureWidth; ?>">
<input type="hidden" id="txt-preview-height-default" name="txt_preview_height_default" value="<?php echo $textureHeight; ?>">
<input type="hidden" id="txt-preview-light-default" name="txt_preview_light_default" value="<?php echo $light; ?>">
<input type="hidden" id="txt-preview-texture-default" name="txt_preview_texture_default" value="<?php echo $texture; ?>">
<!-- Field for 3d-->
<input type="hidden" id="txt-preview-selected" name="txt_preview_selected" value="<?php echo $folderPreview; ?>">
<input type="hidden" id="txt-preview-file-selected" name="txt_preview_file_selected" value="<?php echo $fileNamePreview; ?>">
<input type="hidden" id="txt-preview-zoom-selected" name="txt_preview_zoom_selected" value="<?php echo $zoom; ?>">
<input type="hidden" id="txt-preview-width-selected" name="txt_preview_width_selected" value="<?php echo $textureWidth; ?>">
<input type="hidden" id="txt-preview-height-selected" name="txt_preview_height_selected" value="<?php echo $textureHeight; ?>">
<input type="hidden" id="txt-preview-light-selected" name="txt_preview_light_selected" value="<?php echo $light; ?>">
<input type="hidden" id="txt-preview-texture-selected" name="txt_preview_texture_selected" value="<?php echo $texture; ?>">
<input type="hidden" id="txt-preview-is-design-service" name="is_design_service" value="<?php echo $isDesignService == 1?(in_array($additionOption->getId(), $additionOptionParams) ? 1 : 0):0?>">
<!---->
<div style="display:none;" id="preview-custom-option-values">

</div>
<!-- update time -->
<input type="hidden" name="ict_product_price" value="<?php echo $product->getFinalPrice(); ?>">
<?php foreach ($dailyShippings as $dailyShipping) : ?>
    <input type="hidden" name="ict_daily_price[<?php echo $dailyShipping->getId(); ?>]" value="<?php echo $dailyShipping->getData('amount'); ?>">
<?php endforeach; ?>
<?php if($previewAdditionOptions && $previewAdditionOptions->getSize() > 0) :  ?>
    <?php foreach ($previewAdditionOptions as $additionOption) : ?>
        <input type="hidden" name="ict_addition_price[<?php echo $additionOption->getId(); ?>]" value="<?php echo $additionOption->getData('price'); ?>">
    <?php endforeach; ?>
<?php endif; ?>

<input type="hidden" id="txt-re-update-design-item" name="re_update_design_item" value="<?php echo $isUpdateDesignOrder; ?>">
<input type="hidden" name="preview_offer_store_id" value="<?php echo $block->getOpdStoreId(); ?>">

<script>
    require(['jquery', 'jquery/ui'], function($){
      $(document).ready( function() {
        $('#product-addtocart-button, #preivew-product-addtocart-button, #product-preview-request-offer').click( function(event){
            let customprojectname = $('#mgt-custom-project-name').val();
            $('#cut-project-name-validation').remove();
            if(customprojectname)
            {
                if(characterWithSpaceAddress(customprojectname) == false) {
                $('#mgt-custom-project-name').css('border-color','red');
                throw $('<span id="cut-project-name-validation" style="color:red;"><?php echo __('Invalid Input. Allowed characters are letters, and numbers.') ?></span>').insertAfter('#mgt-custom-project-name');
                }else {
                    $('#mgt-custom-project-name').css('border-color','#ebebeb');
                }
            }
            else{
                $('#mgt-custom-project-name').css('border-color','red');
                throw $('<span id="cut-project-name-validation" style="color:red;"><?php echo __('This is a required field.') ?></span>').insertAfter('#mgt-custom-project-name');
            }

        })
        $('#product_addtocart_form').on( "submit", function( event ) {
            let customprojectname = $('#mgt-custom-project-name').val();
            if(characterWithSpaceAddress(customprojectname) == false) {
                $('<span id="cut-project-name-validation" style="color:red;"><?php echo __('Invalid Input. Allowed characters are letters, and numbers.') ?></span>').insertAfter('#mgt-custom-project-name');
                        return false;

            }
        });
      });
    });
</script>

<script>
    require(['jquery', 'jquery/ui'], function($){
      $(document).ready(function(){
        $('#btn-prview-standrad-design').click( function(event){
            //if ($("body").hasClass("checkout-cart-configure")) {
                if($('#iframe-preview-pro').length != 0){
                    var getIframeVal = $('iframe[id=iframe-preview-pro]').contents().find('#txt-mgt-model-preview').val();
                    $('#txt-preview-selected').val(getIframeVal);
                }
                $('#txt-custom-preview-design-type').val(0);
                $('#txt-customer-upload-design').val("");
                $('#preview-project-extra-options .txt-preview-extra-option').prop('checked', false);
            /*}else{
                location.reload();
            }*/
        })
    })
    });
</script>

<?php
if(count($tierPrices) > 1 ) {
    $custsecondtierPrices = (int)$tierPrices['1']['price_qty'];?>
    <script>
    require(['jquery', 'jquery/ui'], function($){
      $(document).ready( function() {
        $('#preivew-product-addtocart-button, #product-preview-request-offer').click( function(event){
            let custpreviewtype = $("#txt-preview-type").val();
            let custproductqty = $("#mgt-custom-qty").val();
            let custsecondtierprices = <?php echo $custsecondtierPrices; ?>

            // if (custpreviewtype == 2) {
            //     if (custproductqty < custsecondtierprices) {
            //             $('html, body').animate({
            //                 scrollTop: $("#custom-tier-prices-content").offset().top
            //             }, 1000);
            //         if($('#mgt-custom-box-qty-item').length == 0){
            //             if(<?php echo $block->getOpdStoreId(); ?> == 2) {
            //             throw $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">The minimum order quantity is '+ custsecondtierprices +' pieces.</span>').insertAfter('.mgt-custom-box-qty-item');
            //             }else{
            //                 throw $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">Die Mindestbestellmenge liegt bei '+ custsecondtierprices +' Stück.</span>').insertAfter('.mgt-custom-box-qty-item');
            //             }
            //         }else{
            //             throw false;
            //         }
            //     }else{
            //         if($('#mgt-custom-box-qty-item').length > 0){
            //             $('#mgt-custom-box-qty-item').remove();
            //         }
            //     }

            // }else{
                if (custproductqty > 3 && custproductqty < custsecondtierprices) {
                        $('html, body').animate({
                            scrollTop: $("#custom-tier-prices-content").offset().top
                        }, 1000);
                    if($('#mgt-custom-box-qty-item').length == 0){
                        if(<?php echo $block->getOpdStoreId(); ?> == 2) {
                            throw $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">The minimum order quantity is '+ custsecondtierprices +' pieces.</span>').insertAfter('.mgt-custom-box-qty-item');
                        }else{
                            throw $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">Die Mindestbestellmenge liegt bei '+ custsecondtierprices +' Stück.</span>').insertAfter('.mgt-custom-box-qty-item');
                        }
                    }else{
                        throw false;
                    }
                }else{
                    if($('#mgt-custom-box-qty-item').length > 0){
                        $('#mgt-custom-box-qty-item').remove();
                    }
                }
            //}
        })
      });
    });
</script>
<script>
    function characterWithSpaceAddress(event) {
        var regex = /^[@#$%<>"!`_~:;?\/\^\]&\[*}{)(=\\]*$/;
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        console.log(key);
        if (regex.test(key)) {
            event.preventDefault();
            return false;
        }
    };
    require(['jquery', 'jquery/ui'], function($){
      $(document).ready( function() {
        $('#product-updatecart-button').click( function(event){
            let custpreviewtype = $("#txt-preview-type").val();
            let custproductqty = $("#mgt-custom-qty").val();
            let custsecondtierprices = <?php echo $custsecondtierPrices; ?>

            // if (custpreviewtype == 2) {
            //     if (custproductqty < custsecondtierprices) {
            //             $('html, body').animate({
            //                 scrollTop: $("#custom-tier-prices-content").offset().top
            //             }, 1000);
            //         if($('#mgt-custom-box-qty-item').length == 0){
            //             if(<?php echo $block->getOpdStoreId(); ?> == 2) {
            //              $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">The minimum order quantity is '+ custsecondtierprices +' pieces.</span>').insertAfter('.mgt-custom-box-qty-item');
            //             }else{
            //              $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">Die Mindestbestellmenge liegt bei '+ custsecondtierprices +' Stück.</span>').insertAfter('.mgt-custom-box-qty-item');
            //             }
            //             return false;
            //         }else{
            //             return false;
            //         }
            //     }
            // }else{
                if (custproductqty > 3 && custproductqty < custsecondtierprices) {
                        $('html, body').animate({
                            scrollTop: $("#custom-tier-prices-content").offset().top
                        }, 1000);
                    if($('#mgt-custom-box-qty-item').length == 0){
                        if(<?php echo $block->getOpdStoreId(); ?> == 2) {
                         $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">The minimum order quantity is '+ custsecondtierprices +' pieces.</span>').insertAfter('.mgt-custom-box-qty-item');
                        }else{
                         $('<span id="mgt-custom-box-qty-item" style="color:red; text-align:center; margin-top: 9px">Die Mindestbestellmenge liegt bei '+ custsecondtierprices +' Stück.</span>').insertAfter('.mgt-custom-box-qty-item');
                        }
                        return false;
                    }else{
                        return false;
                    }
                }
            //}
        })
        
        $('form').on('focus', 'input[type=number]', function (e) {
          $(this).on('wheel.disableScroll', function (e) {
            e.preventDefault()
          })
        })
        $('form').on('blur', 'input[type=number]', function (e) {
          $(this).off('wheel.disableScroll')
        })

        $(function () {
          $("[data-toggle=preview-tooltip]").tooltip();
        });
      });
    });
</script>

<?php } ?>

<style>
.ui-tooltip.ui-widget.ui-widget-content {
    border: 1px solid #d3d3d3;
    background-color: black;
    color: white;
}
.ui-tooltip {
	padding: 8px;
	position: absolute;
	z-index: 9999;
	max-width: 300px;
}
body .ui-tooltip {
	border-width: 2px;
}
.mgt-custom-box-qty .update-refresh .mgt-custom-box-qty-item-col {
    width: 25%;
}
.mgt-custom-box-qty .update-refresh .mgt-custom-box-qty-item-col-input {
    display: flex;
    width: 50%;
    column-gap: 10px;
}
.mgt-custom-box-qty .update-refresh .mgt-custom-box-qty-item-col-input #mgt-custom-qty-update {
    width: 40%;
    display: flex;
    justify-content: center;
}
.mgt-custom-box-qty .update-refresh .mgt-custom-box-qty-item-col-input #mgt-custom-qty {
    width: 100%;
}
</style>
