<?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\PreviewCart $block */
//echo get_class($block);
/* @var \Magento\Catalog\Helper\Image $imageHelper */
$imageHelper = $this->helper('Magento\Catalog\Helper\Image');
$items = $block->getAllItemInCart();
$customerGroup = $block->getCustomerGroup();
$tax = 19;
$urls = $block->getCartAjaxUrls();
$placeUrl = $urls['place_url'];
$grandTotal = 0;
$address = $block->getCustomerDefaultAddress();
$AllAddress = $block->getCustomerAllAddress();
/** @var \Magento\Customer\Model\Address $billing*/
$billing = isset($address['billing']) ? $address['billing'] : null;
/** @var \Magento\Customer\Model\Address $shipping*/
$shipping = isset($address['shipping']) ? $address['shipping'] : null;
$cartRule1 = $block->getPreviewHelper()->getApdConfigValue('advancepreview/cart_setting/cart_rule1');
$cartRule2 = $block->getPreviewHelper()->getApdConfigValue('advancepreview/cart_setting/cart_rule2');
$isBilling = false;
$isShipping = false;
$iframeUrl = $block->getUrl('advance_preview/newPreview/index');
$customerId = null;
?>
<!--<h3 id="preview-place-order-message"> </h3>-->

<?php if($items && $items->getSize() > 0) : ?>
<div id="preview-custom-checkout-complete" style="display: none">
    <div class="cart-empty">
        <p><?php echo __('You have no items in your shopping cart.') ?></p>
        <p><?php echo __('Click') ?> <a href="http://18.141.220.117/"><?php echo __('here') ?></a> <?php echo __('to continue shopping.') ?></p>
    </div>
</div>
<div class="preview-custom-cart-header">
    <?php if($billing != null && $billing->getId() && $shipping && $shipping->getId() && $shipping->getId() > 0) : ?>
    <?php $isBilling = true; ?>
    <div class="preview-custom-cart-header-2">
        <div class="preview-custom-cart-header-info">
            <h5><?php echo __('Billing address') ?></h5>
            <span>
                <?php echo $billing->getFirstname() .' '. $billing->getLastname(); ?>
            </span>
            <?php $stresses = $billing->getStreet(); ?>
            <?php if(count($stresses) > 0) : ?>
            <?php foreach ($stresses as $stress) : ?>
                <span>
                    <?php echo $stress; ?>
                 </span>
            <?php endforeach; ?>
            <?php endif; ?>

            <span>
                 <?php echo $billing->getCity() ?>
            </span>
            <?php if($billing->getRegion() && $billing->getRegion() != '') : ?>
            <span>
                 <?php echo $billing->getRegion() ?>
            </span>
            <?php endif; ?>
            <span>
                <?php echo $billing->getPostcode() . ' ' . $billing->getCountryId() ?>
            </span>
            <a class="details-btn" href="<?php echo $block->getUrl('customer/address/') ?>"><?php echo __('Detail') ?></a>
        </div>
    </div>
    <?php endif; ?>
    <?php if($billing != null && $billing->getId() && $shipping && $shipping->getId() && $shipping->getId() > 0) : ?>
    <?php $isShipping = true; ?>
    <div class="preview-custom-cart-header-3">
        <div id="preview-custom-cart-header-3-replace" class="preview-custom-cart-header-info" style="width:100%">
            <h5><?php echo __('Delivery address') ?></h5>
             <span>
                <?php echo $shipping->getFirstname() .' '. $shipping->getLastname(); ?>
            </span>
            <?php $stresses = $shipping->getStreet(); ?>
            <?php if(count($stresses) > 0) : ?>
                <?php foreach ($stresses as $stress) : ?>
                    <span>
                    <?php echo $stress; ?>
                 </span>
                <?php endforeach; ?>
            <?php endif; ?>
            <span>
                 <?php echo $shipping->getCity() ?>
            </span>
            <?php if($shipping->getRegion() && $shipping->getRegion() != '') : ?>
            <span>
                 <?php echo $shipping->getRegion() ?>
            </span>
            <?php endif; ?>
            <span>
                <?php echo $shipping->getPostcode() . ' ' . $shipping->getCountryId() ?>
            </span>
             <a class="details-btn" href="<?php echo $block->getUrl('customer/address') ?>"><?php echo __('Detail') ?></a>
        </div>
         <div class="custom-address-dropdown" style="width:auto;">
            <select id="custom-address-dropdown-select" style="border: 1px solid #D9222A;">                        
                 <?php 

                 foreach($AllAddress as $AllAddressss){
                    $customerId = $AllAddressss->getCustomerId();
                ?>
                <option class="custom-address-dropdown-option" value="<?php echo $AllAddressss->getId(); ?>" 
                   <?php 
                   if($AllAddressss->getId() == $shipping->getId()){
                    echo "selected";
                   }?>>                    
                    <span>
                        <?php echo $AllAddressss->getFirstname() .' '. $AllAddressss->getLastname().', '; ?>
                    </span>
                    <?php $stresses = $AllAddressss->getStreet(); ?>
                    <?php if(count($stresses) > 0) : ?>
                        <?php foreach ($stresses as $stress) : ?>
                            <span>
                            <?php echo $stress.', '; ?>
                         </span>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    <span>
                         <?php echo $AllAddressss->getCity().', '; ?>
                    </span>
                    <?php if($AllAddressss->getRegion() && $AllAddressss->getRegion() != '') : ?>
                    <span>
                         <?php echo $AllAddressss->getRegion().', '; ?>
                    </span>
                    <?php endif; ?>
                    <span>
                        <?php echo $AllAddressss->getPostcode() . ', ' . $AllAddressss->getCountryId() ?>
                    </span>
                   <?php } ?> 
                </option>
            </select>
        </div>
    </div>
       
    <?php endif; ?>
    <?php if(!$isShipping || !$isBilling) : ?>
        <p><?php echo __('Address not found ') ?><a href="<?php echo $block->getUrl('customer/address/new') ?>"><?php echo __('Click here') ?></a> <?php echo __('to add new address') ?></p>
    <?php endif; ?>
</div>
<div class="preview-custom-cart">


        <?php foreach ($items as $item) : ?>

            <?php
            /** @var \Magento\Quote\Model\Quote\Item $item*/
            $productId = $item->getProduct()->getId();
            $_product = $block->getProductById($productId);
            if(!$_product) {
                continue;
            }
            $requestOption = $block->getItemInforestion($item);
          /*  echo '<pre>';
                print_r($requestOption);
            echo '</pre>';*/
            $tierPrice = $block->getTierPriceByProductId($_product);
            $tierQtyPrice = $block->getTierPriceItemByQty($tierPrice, $item->getQty());
            $ourPrice = $block->getCustomTierOurPrice($_product,$tierQtyPrice);
            $ourPriceRow = $ourPrice * $item->getQty();
            $customDiscounts = $block->getPreviewDiscounts($productId);
            $total = $ourPriceRow;
            $designType = isset($requestOption['txt_custom_preview_design_type']) ? $requestOption['txt_custom_preview_design_type'] : 0;
            $gernerateProjoectId = isset($requestOption['text_project_generate']) ? $requestOption['text_project_generate'] : 0;
            $designOrderStatus = 'Ordered with standard design';
            if(isset($requestOption['txt_is_request_sample']) && $requestOption['txt_is_request_sample'] == 1) {
                $designOrderStatus = 'Ordered for samples';
            }
            else if($designType == 1) {
                $designOrderStatus = 'Ordered with custom design';
                $customWithExtraCost = isset($requestOption['preview_additional_options']) ? $requestOption['preview_additional_options'] : [];
                if(count($customWithExtraCost)) {
                    $designOrderStatus = 'Ordered with custom design extra costs';
                }

            }
            if($gernerateProjoectId > 0) {
                if($gernerateProjoectId > 1000) {
                    $gernerateProjoectId = $gernerateProjoectId;
                }
                else if($gernerateProjoectId > 100) {
                    $gernerateProjoectId = '0'.$gernerateProjoectId;
                }
                else if($gernerateProjoectId > 10) {
                    $gernerateProjoectId = '00'.$gernerateProjoectId;
                }
                else {
                    $gernerateProjoectId = '000'.$gernerateProjoectId;
                }
            }
            else {
                $gernerateProjoectId = '';
            }
            $projectName = isset($requestOption['custom_project_name']) ? $requestOption['custom_project_name'] : '';
           /* Changed by Nalini*/
            // if($gernerateProjoectId != '') {
            //     $projectName = $gernerateProjoectId . ' - ' .$projectName;
            // }
//            echo $modelPreview;
//            $previewModels = $block->getPreviewByProductId($productId);
            $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : '';
            $namePreviewModel = isset($requestOption['txt_preview_file_selected']) ? $requestOption['txt_preview_file_selected'] : '';
            $light = isset($requestOption['txt_preview_light_selected']) ? $requestOption['txt_preview_light_selected'] : 0;
            $zoom = isset($requestOption['txt_preview_zoom_selected']) ? $requestOption['txt_preview_zoom_selected'] : 0;
            $textureWidth =  isset($requestOption['txt_preview_width_selected']) ? $requestOption['txt_preview_width_selected'] : 0;
            $textureHeight =  isset($requestOption['txt_preview_height_selected']) ? $requestOption['txt_preview_height_selected'] : 0;

           /* if($previewModels && $previewModels->getSize() > 0) {
                $namePreviewModel = $previewModels->getFirstItem()->getData('file_preview');
                $light = $previewModels->getFirstItem()->getData('preview_light');
                $zoom = $previewModels->getFirstItem()->getData('preview_zoom');
            }*/

            $is3D = false;
            if($block->checkProductEnable3D($_product) && $modelPreview != '' && $namePreviewModel != '') {
                $is3D = true;
            }
            // custom shipping
            $dailyId = isset($requestOption['txt_daily_shipping']) ? (int)$requestOption['txt_daily_shipping'] : 0;
            $dailyShippigAmount = 0;
            $dailyDays = 0;
            if($dailyId > 0) {
                $dailyShippig = $this->getDailyShippingById($dailyId);
                $dailyShippigAmount = $dailyShippig != null && $dailyShippig->getData('amount') > 0 ? $dailyShippig->getData('amount') : 0;
                $dailyDays = $dailyShippig != null && $dailyShippig->getData('delivery_days') > 0 ? $dailyShippig->getData('delivery_days') : 0;
            }
            $customOptions = [];
            $paramAdditionalOptions = isset($requestOption['preview_additional_options']) ? $requestOption['preview_additional_options'] : [];

            $isdesignservice = [];
            $designservice = 'No';
            if(count($paramAdditionalOptions)){
                    foreach ($paramAdditionalOptions as $Options) {                        
                       $isdesignservice[] = $block->getPreviewAdditionalOptionLabels($Options);                        
                    }
                    if ((in_array("Design service", $isdesignservice)) || (in_array("Gestaltungsdienst", $isdesignservice)))
                      {
                      $designservice = 'Yes';
                      }
            }
            ?>
            <?php //print_r($requestOption); ?>
            <div class="preview-custom-cart-item">
                <?php if($is3D) : ?>
                    <?php /*<div class="preview-custom-cart-item-col-1" id="preview-custom-cart-preview-item-<?php echo $item->getItemId(); ?>" product-id="<?php echo $productId ?>" model-preview="<?php echo $modelPreview; ?>" preview-file-name="<?php echo $namePreviewModel; ?>" preview-light="<?php echo $light; ?>" preview-zoom="<?php echo $zoom; ?>">
                    </div>*/ ?>
                    <div class="preview-custom-cart-item-col-1">
                        <?php  $previewParam = "name_preview/{$namePreviewModel}/model_preview/{$modelPreview}/product_id/{$productId}"; ?>
                        <iframe id="iframe-preview-pro" src="<?php echo $iframeUrl.$previewParam; ?>" title="HIhi" style="width: 100%; height: 200px;"></iframe>
                        <?php
                            if ($requestOption['customer_upload_design'] == null && $designType == 1) { ?>
                                <div id="empty-image-message">
                                    <?php
                                    if ($designservice == 'Yes') {
                                        echo __('No Logo. You can upload the logo also later, if you have chosen our design service. But this can influence the delivery time.');
                                    }else{
                                        echo __('No design. You can upload the design also later. But this can influence the delivery time.');                                        
                                    }?>
                                </div><?php
                            }?>
                    </div>
                <?php else : ?>
                    <div class="preview-custom-cart-item-col-1">
                        <?php
                        $image = $imageHelper->init($_product, 'product_page_image_small')->keepAspectRatio(true)->resize(200, 200)->getUrl();
                        ?>
                        <img src="<?php echo $image;?>" alt="<?php echo $_product->getName() ?>" type="<?php echo $_product->getName() ?>">
                        <?php
                        if ($_product->getData('pcto_cust_design') == 1) {
                            if ($requestOption['customer_upload_design'] != null) {
                                $imageutl =  $block->getMediaUrl().'advancepreview/custom_previews/product_id_'.$productId.'/'.$requestOption['txt_preview_selected'].'/'.$requestOption['customer_upload_design']; ?>
                                <a id="cart-cust-download-image-link" href="<?php echo $imageutl ?>" style="text-align: center"; download><?php echo __('Download the file') ?></a>
                        <?php }
                        if ($requestOption['customer_upload_design'] == null && $designType == 1) { ?>
                            <div id="empty-image-message">
                                <?php
                                    if ($designservice == 'Yes') {
                                        echo __('No Logo. You can upload the logo also later, if you have chosen our design service. But this can influence the delivery time.');
                                    }else{
                                        echo __('No design. You can upload the design also later. But this can influence the delivery time.');
                                    }
                                     ?>
                            </div><?php
                            }
                        }?>
                    </div>
                <?php endif; ?>
                <div class="preview-custom-cart-item-col-2">

                    <span class="pc-item-info"><?php echo $projectName; ?></span>
                    <span class="pc-item-info"><a href="<?php echo $_product->getProductUrl() ?>"><?php echo $item->getProduct()->getName(); ?></a> </span>
                    <span class="pc-item-info"><?php echo $item->getProduct()->getSku(); ?></span>
                    <span class="pc-item-info"><?php echo __($designOrderStatus) ?></span>
                    <span class="pc-item-info"><?php echo $_product->getData('short_description'); ?></span>
                    <?php if(count($paramAdditionalOptions)) : ?>
                        <?php $addionLables = $block->getPreviewAdditionalOptionLabels($paramAdditionalOptions); ?>
                        <span class="pc-item-info"><?php echo __($addionLables) ?></span>
                    <?php endif; ?>
                </div>
                <div class="preview-custom-cart-item-col-3">
                  <!--  <button type="button">Detail</button>-->
                    <a class="edit-btn" href="<?php echo $block->getUrl('checkout/cart/configure/').'id/'.$item->getId().'/product_id/'.$productId ?>"><?php echo __('Edit') ?></a>
                </div>
                <div class="preview-custom-cart-item-col-4">
                    <div class="preview-custom-cart-item-col-last">
                        <div class="preview-custom-cart-item-col-last-left">
                            <!-- <input type="text" id="txt-qty-<?php echo $item->getId(); ?>" name="" value="<?php echo $item->getQty() ?>"> -->
                            <span class="quantity"><?php echo $item->getQty() ?></span>

                        </div>
                        <div class="preview-custom-cart-item-col-last-right">
                            <span class="pc-item-info-pcs">PCS</span>

                        </div>
                    </div>
                    <div class="preview-custom-cart-item-col-last">
                        <div class="preview-custom-cart-item-col-last-left">
                            <span class="pc-item-info"><?php echo $item->getQty() ?> x <?php echo $block->convertNumberToPrice($ourPrice); ?></span>
                        </div>
                        <div class="preview-custom-cart-item-col-last-right">
                            <span><?php echo $block->convertNumberToPrice($ourPriceRow) ?></span>
                        </div>
                    </div>
                    <?php $i = 0; ?>
                        <?php foreach ($customDiscounts as $customDiscount) : ?>
                            <?php if($i == 0) { $i++; continue; } ?>
                            <?php
                                $priceDiscountItem = ($customDiscount->getData('discount_title')=="Processing & Finishing" && $item->getQty() <4) ? 0:$customDiscount->getData('discount_price');
                                if($designType == 1 && $i == 1) {
                                    $defaultValue = $tierQtyPrice * $item->getQty();
                                    $priceDiscountItem += $block->getAdditionalOptionPrice($paramAdditionalOptions, $productId, $defaultValue);
                                    $priceAfterDiscont = $block->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);
                                }
                                else if($dailyShippigAmount > 0 && $i == $customDiscounts->getSize() - 1) {
                                    // if shipping
                                    $shippingCharge = (($tierQtyPrice * $dailyShippigAmount * $item->getQty()) / 100);
                                    $priceDiscountItem += $shippingCharge;
                                    $priceAfterDiscont = $priceDiscountItem;
                                }
                                else{
                                    $priceAfterDiscont = $block->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);
                                }

                                $total += $priceAfterDiscont;
                                $customOptions[] = [
                                    'title'=>$customDiscount->getData('discount_title'),
                                    'price'=>$priceAfterDiscont
                                ];
                                $i++;
                                //$txtDiscountTitle = str_replace('_',' ',$akt);
                                ?>
                                <?php endforeach; ?>
                                <?php
                                 if($total < 50)
                                 {
                                    $total =$total+4;
                                    $customOptions[count($customOptions) - 1] ['price']=$customOptions[count($customOptions) - 1] ['price']+4;
                                 }
                                $i = 0;
                                foreach ($customOptions as $customOption) :
                                ?>
                            <div class="preview-custom-cart-item-col-last">
                                <div class="preview-custom-cart-item-col-last-left">
                                    <?php if($dailyShippigAmount > 0 && $i ==  count($customOption)) : ?>
                                        <?php echo __('Delivery time:') ?> <span class="days"><?php echo $dailyDays ?></span>  <?php echo __('days plus shipping') ?>
                                    <?php else : ?>
                                        <span class="pc-item-info"><?php echo __($customOption['title']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="preview-custom-cart-item-col-last-right">
                                    <span class="pc-item-info"><?php echo $block->convertNumberToPrice($customOption['price']); ?></span>
                                </div>
                            </div>
                            <?php $i++; ?>
                        <?php endforeach; ?>
                    <div class="preview-custom-cart-item-col-last">
                        <div class="preview-custom-cart-item-col-last-left total">
                            <span class="pc-item-info"><?php echo __('Total') ?></span>
                        </div>
                        <div class="preview-custom-cart-item-col-last-right total">
                            <?php //$total = $total + (($total * $tax) / 100); // add tax ?>
                            <?php $grandTotal += $total; ?>
                            <span><?php echo $block->convertNumberToPrice($total) ?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>

</div>
<div class="preview-cart-footer">
    <div class="preview-cart-footer-left">
        <div class="preview-cart-footer-rule">
            <input type="checkbox" name="preview_cart_rule_1" id="preview-cart-rule-1" value="1" title="Datenschutz" class="input-text">
            <label for="preview-cart-rule-1"><?php echo __($cartRule1) ?></label>
        </div>
    </div>
    <div class="preview-cart-footer-right">
        <div class="preview-cart-footer-total total">
                    <span class="preview-cart-footer-total-left">
                        <?php echo __('Price (net)') ?>
                    </span>
            <span class="preview-cart-footer-total-right">
                         <?php echo $block->convertNumberToPrice($grandTotal) ?>
                    </span>

        </div>
        <div class="preview-cart-footer-total total">
                    <span class="preview-cart-footer-total-left">
                        <?php echo __('19.00 % VAT', $tax) ?>
                    </span>
            <?php $grandTotalTax = ($grandTotal * $tax) / 100 ?>
            <span class="preview-cart-footer-total-right">
                         <?php echo $block->convertNumberToPrice($grandTotalTax) ?>
                    </span>

        </div>
        <div class="preview-cart-footer-total grand-total">
                    <span class="preview-cart-footer-total-left">
                        <?php echo __('Total price') ?>
                    </span>
            <?php $grandTotalIncludeTax = $grandTotalTax + $grandTotal; ?>
            <span class="preview-cart-footer-total-right">
                         <?php echo $block->convertNumberToPrice($grandTotalIncludeTax) ?>
                    </span>

        </div>
    </div>
</div>
<div class="preview-custom-cart-footer">
    <?php if(!$isShipping || !$isBilling) : ?>
        <div style="font-size: 1.1em; color: #D9222A; font-weight: 500; display: inline-block; clear: both; width: 100%; margin: 20px 0 0 0;"><?php echo __('Please fill in the address details to proceed with the purchase') ?></div>
    <?php endif; ?>
    <button type="button" id="btn-custom-place-order" <?php if(!$isShipping || !$isBilling) { ?> disabled="disabled" <?php } ?>><?php echo __('Place order') ?></button>
</div>
<input type="hidden" id="txt-place-custom-order" value="<?php echo $placeUrl; ?>">
<input type="hidden" id="txt-home-url" value="<?php echo $block->getUrl('checkout/cart'); ?>">
<input type="hidden" id="txt-test-text-warning" value="<?php echo __('You must read and agree the terms and conditions before placing an order'); ?>">
<script>
    require([
        'jquery',
        'mgt_custom_cart'
    ],function ($, customCart) {
        customCart.init();
    })
    document.onkeydown = function(e) {
  if(event.keyCode == 123) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
     return false;
  }
  if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
     return false;
  }
}
document.addEventListener('contextmenu', event => event.preventDefault());
</script>
<?php endif; ?>

<script>
    require(['jquery', 'jquery/ui'], function($){
        $(document).ready( function() {
            $("#custom-address-dropdown-select").on('change',function(){
                var ShippingId = $('#custom-address-dropdown-select').val();
                var CustomerId = <?php echo $customerId; ?>;

                $.ajax({
                  method: "POST",
                  url: "<?php  echo $block->getUrl('advance_preview/addressdropdown/ajaxreceive'); ?>",
                  data: { shippingid: ShippingId,
                          customerid: CustomerId
                        },
                  dataType: "json",
                     statusCode: {
                        200: function() {
                          $("#preview-custom-cart-header-3-replace").load(location.href + " #preview-custom-cart-header-3-replace");
                        }
                    }   
                })
            });
        });
    });
</script>