<?php
/**@var \Magetop\Advancepreview\Block\Order\CustomOrderView $block */
$orderId = $block->getRequest()->getParam('order_id',0);
$imageHelper = $this->helper('Magento\Catalog\Helper\Image');
/**@var \Magento\Sales\Model\Order $order */
$order = $block->getData('order');
$items = $order->getAllItems();
$customerGroup = $block->getCustomerGroup();
$tax = 19;
$grandTotal = 0;
$customerId = $order->getCustomerId();
$statusLabels = [
    'new'=>'New',
    'process'=>'In progress',
    'shipping'=>'Ready for shipping/Production done',
    'shipped'=>'Shipped'
];
$statusCustomPrintLabels = [
    'new'=>'New',
    'downloading'=>'Checking design by Myfitmix',
    'design_failed'=>'Design failed',
    'design_approved'=>'Design approved',
    'customer_reject'=>'Design rejected by customer',
    'design_full_approved'=>'Design fully approved',
    'process'=>'In progress',
    'shipping'=>'Ready for shipping/Production done',
    'shipped'=>'Shipped',
    'delivered'=>'Delivered',
];
$statusKeke = [
    'design_full_approved'=>'Design fully approved',
    'process'=>'In progress',
    'shipping'=>'Ready for shipping/Production done',
    'shipped'=>'Shipped',
    'delivered'=>'Delivered'
];
$statusCustomNoPrintLabels = [
    'new'=>'New',
    'downloading'=>'Checking design by Myfitmix',
    'design_failed'=>'Design failed',
    'design_approved'=>'Design approved',
    'customer_reject'=>'Design rejected by customer',
    'design_full_approved'=>'Design fully approved',
    'process'=>'In progress',
    'shipping'=>'Ready for shipping/Production done',
    'shipped'=>'Shipped',
    'delivered'=>'Delivered',
];
$urls = $block->getAjaxUrls();
$iframeUrl = $block->getUrl('advance_preview/newPreview/index');
?>
<?php if($items) : ?>
    <div class="preview-custom-order-items">
        <?php foreach ($items as $item) : ?>
            <?php
            /** @var  \Magento\Sales\Model\Order\Item $item*/
            $productId = $item->getProduct()->getId();
            $_product = $block->getProductById($productId);
            if(!$_product) {
                continue;
            }
            $previewOrderItem = $block->getPreviewItemByItemId($item->getId());
            $status = '';
            $customerUploadDesign = '';
            $isAdminCreateDesign = 0;
            $adminUploadFile = 0;
            $invoiceId = 0;
            $isNewProof = 0;
            $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : '';
            $trakingInfo = '';
            if($previewOrderItem != null) {
                $status = $previewOrderItem->getData('status');
                $customerUploadDesign = $previewOrderItem->getData('custom_design');
                $isAdminCreateDesign = $previewOrderItem->getData('is_admin_create');
                $adminUploadFile = $previewOrderItem->getData('admin_upload_design');
                $invoiceId = $previewOrderItem->getData('invoice_id');
                $isNewProof = $previewOrderItem->getData('is_new_proof');
                if(trim($previewOrderItem->getData('preview_model')) != '') {
                    $modelPreview = $previewOrderItem->getData('preview_model');
                }
                $trakingInfo = $previewOrderItem->getData('tracking_info');
            }
            $requestOption = $block->getCustomItemDetail($item);
            $token = isset($requestOption['uenc']) ? $requestOption['uenc'] : '';
            // echo '<pre>';
            //      print_r( $requestOption);
            //  echo '</pre>';
            $tierPrice = $block->getTierPriceByProductId($_product);
            $tierQtyPrice = $block->getTierPriceItemByQty($tierPrice, $item->getQtyOrdered());
            $ourPrice = $block->getCustomTierOurPrice($_product,$tierQtyPrice, $customerId);
            $ourPriceRow = $ourPrice * $item->getQtyOrdered();
            $customDiscounts = $block->getPreviewDiscounts($productId);
            $total = $ourPriceRow;
            $designType = isset($requestOption['txt_custom_preview_design_type']) ? $requestOption['txt_custom_preview_design_type'] : 0;
//            $customerUploadDesign = isset($requestOption['customer_upload_design']) ? trim($requestOption['customer_upload_design']) : '';
//            $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : 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'] : '';
            if($gernerateProjoectId != '') {
                $projectName = $gernerateProjoectId . ' - ' .$projectName;
            }
//            echo $modelPreview;
            $previewModels = $block->getPreviewByProductId($productId);
            /*$light = 0;
            $namePreviewModel = '';
            $zoom = 0;
            $texture =  '';
            $textureWidth = 0;
            $textureHeight = 0;
            if($previewModels && $previewModels->getSize() > 0) {
                $namePreviewModel = $previewModels->getFirstItem()->getData('file_preview');
                $light = $previewModels->getFirstItem()->getData('preview_light');
                $zoom = $previewModels->getFirstItem()->getData('preview_zoom');
                $texture = $previewModels->getFirstItem()->getData('texture');
                $zoom = $previewModels->getFirstItem()->getData('preview_zoom');
                $textureWidth = $previewModels->getFirstItem()->getData('texture_width');
                $textureHeight = $previewModels->getFirstItem()->getData('texture_height');
            }*/
//            $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']) ? (int)$requestOption['txt_preview_light_selected'] : 0;
            $zoom = isset($requestOption['txt_preview_zoom_selected']) ? (int)$requestOption['txt_preview_zoom_selected'] : 0;
            $textureWidth =  isset($requestOption['txt_preview_width_selected']) ? (int)$requestOption['txt_preview_width_selected'] : 0;
            $textureHeight =  isset($requestOption['txt_preview_height_selected']) ? (int)$requestOption['txt_preview_height_selected'] : 0;
            $texture =  isset($requestOption['txt_preview_texture_selected']) ? $requestOption['txt_preview_texture_selected'] : '0';
            $desingClick  =  isset($requestOption['is_design_service']) ? (int)$requestOption['is_design_service'] : 0;
            $is3D = false;
            if($block->checkProductEnable3D($_product) && $modelPreview != '' && $namePreviewModel != '' && $light > 0 && $zoom > 0) {
                $is3D = true;
            }
            // custom shipping
            $dailyId = isset($requestOption['txt_daily_shipping']) ? (int)$requestOption['txt_daily_shipping'] : 0;
            $dailyShippigAmount = 0;
            $dailyDays = 0;
            if($dailyId > 0) {
                $dailyShippig = $block->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;
            }
            $paramAdditionalOptions = isset($requestOption['preview_additional_options']) ? $requestOption['preview_additional_options'] : [];
            ?>
            <div class="preview-custom-order-item">
                <?php if($is3D) : ?>
                    <?php /*<div class="custom-order-items-image" id="preview-custom-order-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="custom-order-items-image">
                        <?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>
                    </div>

                <?php else : ?>
                    <div class="custom-order-items-image">
                        <?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() ?>">
                    </div>
                <?php endif; ?>
                <div class="custom-order-item-info">
                    <span class="pc-item-info"><?php echo $projectName; ?></span>
                    <span class="pc-item-info"><a href="<?php echo $_product->getProductUrl() ?>"><?php echo $_product->getName(); ?></a> </span>
                    <span class="pc-item-info"><?php echo $_product->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="custom-order-item-total">
                    <div class="preview-custom-order-item-col-last">
                        <div class="preview-custom-order-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 (int)$item->getQtyOrdered() ?></span>

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

                        </div>
                    </div>
                    <div class="preview-custom-order-item-col-last">
                        <div class="preview-custom-order-item-col-last-left">
                            <span class="pc-item-info"><?php echo (int)$item->getQtyOrdered(); ?> x <?php echo $block->convertNumberToPrice($ourPrice); ?></span>
                        </div>
                        <div class="preview-custom-order-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_price');
                        if($designType == 1 && $i == 1) {

                            $priceDiscountItem += $block->getAdditionalOptionPrice($paramAdditionalOptions, $productId);
                        }
                        elseif($dailyShippigAmount > 0 && $i == $customDiscounts->getSize() - 1) {
                            // if shipping
                            $shippingCharge = (($tierQtyPrice * $dailyShippigAmount * $item->getQtyOrdered()) / 100);
                            $priceDiscountItem += $shippingCharge;
                        }
                        $priceAfterDiscont = $block->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product, $customerId);
                        $total += $priceAfterDiscont;
                        ?>

                        <div class="preview-custom-order-item-col-last">
                            <div class="preview-custom-order-item-col-last-left">
                                <?php  if($dailyShippigAmount > 0 && $i == $customDiscounts->getSize() - 1) : ?>
                                    <span class="pc-item-info">
                                           <?php echo __('Delivery time: ') ?><b><?php echo $dailyDays ?></b><?php echo __(' days plus shipping') ?>
                                    </span>
                                <?php else : ?>
                                    <span class="pc-item-info"><?php echo $customDiscount->getData('discount_title'); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="preview-custom-order-item-col-last-right">
                                <span class="pc-item-info"><?php echo $block->convertNumberToPrice($priceAfterDiscont); ?></span>
                            </div>
                        </div>
                        <?php $i++; ?>
                    <?php endforeach; ?>
                    <div class="preview-custom-order-item-col-last">
                        <div class="preview-custom-order-item-col-last-left total">
                            <?php $txtTax = number_format((float)$tax, 2, '.', ''); ?>
                            <span class="pc-item-info"><?php echo __('%1% VAT',$txtTax) ?></span>
                            <br/>
                            <span class="pc-item-info"><?php echo __('Total') ?></span>
                        </div>
                        <div class="preview-custom-order-item-col-last-right total">
                            <?php $taxTotal = (($total * $tax) / 100); // add tax ?>
                            <?php $total = $total + $taxTotal; // add tax ?>
                            <?php $grandTotal += $total; ?>
                            <span><?php echo $block->convertNumberToPrice($taxTotal) ?></span>
                            <br/>
                            <span><?php echo $block->convertNumberToPrice($total) ?></span>
                        </div>
                    </div>

                </div>
                <div class="preview-custom-order-item-status">
                    <?php if($designType == 0) : ?>
                        <span id="preview-project-item-status-<?php echo $item->getId(); ?>"><?php echo  isset($statusLabels[$status]) ? $statusLabels[$status] : ucfirst($status); ?></span>
                    <?php elseif ($designType == 1 && $customerUploadDesign != '') : ?>
                        <span id="preview-project-item-status-<?php echo $item->getId(); ?>"><?php echo  isset($statusCustomPrintLabels[$status]) ? $statusCustomPrintLabels[$status] : ucfirst($status); ?></span>
                        <br/>
                        <?php if($status == 'design_failed') : ?>
                            <span><?php echo __('Please upload a new design file') ?></span>
                        <?php endif; ?>
                    <?php elseif ($designType == 1 && $customerUploadDesign == '') : ?>
                        <span id="preview-project-item-status-<?php echo $item->getId(); ?>"><?php echo isset($statusCustomNoPrintLabels[$status]) ? $statusCustomNoPrintLabels[$status] : ''; ?></span>
                    <?php endif; ?>
                    <?php if($designType == 1 && $desingClick == 1 && !array_key_exists($status,$statusKeke)) : ?>
                        <p><?php echo __('Our graphic department will contact you for the further information') ?></p>
                    <?php endif; ?>
                    <?php if($status == 'shipped' || $status == 'delivered') : ?>
                        <p>
                            <?php echo $trakingInfo ?>
                        </p>
                    <?php endif; ?>
                </div>
                <div class="preview-custom-order-item-action">
                    <?php if($designType == 1 && $customerUploadDesign != '' && $status == 'design_failed') : ?>
                        <form action="/" method="post" id="form-upload-custom-design-item-<?php echo $item->getId() ?>" enctype="multipart/form-data" style="display: none">
                            <button class="btn-preview-upload-custom-design" item-id="<?php echo $item->getId(); ?>" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Pro 6.0.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M105.4 182.6c12.5 12.49 32.76 12.5 45.25 .001L224 109.3V352c0 17.67 14.33 32 32 32c17.67 0 32-14.33 32-32V109.3l73.38 73.38c12.49 12.49 32.75 12.49 45.25-.001c12.49-12.49 12.49-32.75 0-45.25l-128-128C272.4 3.125 264.2 0 256 0S239.6 3.125 233.4 9.375L105.4 137.4C92.88 149.9 92.88 170.1 105.4 182.6zM480 352h-160c0 35.35-28.65 64-64 64s-64-28.65-64-64H32c-17.67 0-32 14.33-32 32v96c0 17.67 14.33 32 32 32h448c17.67 0 32-14.33 32-32v-96C512 366.3 497.7 352 480 352zM432 456c-13.2 0-24-10.8-24-24c0-13.2 10.8-24 24-24s24 10.8 24 24C456 445.2 445.2 456 432 456z"/></svg><span><?php echo __('Upload your design') ?></span></button>
                            <input type="hidden" name="product_id" value="<?php echo $_product->getId(); ?>">
                            <input type="hidden" name="texture" value="<?php echo $texture; ?>">
                            <input type="hidden" name="texture_width" value="<?php echo $textureWidth; ?>">
                            <input type="hidden" name="texture_height" value="<?php echo $textureHeight; ?>">
                            <input type="hidden" name="own_folder" value="<?php echo $modelPreview; ?>">
                            <input type="hidden" name="original_file" value="<?php echo $customerUploadDesign; ?>">
                            <input type="hidden" name="zoom" value="<?php echo $zoom; ?>">
                            <input type="hidden" name="light" value="<?php echo $light ?>">
                            <input type="hidden" name="name_preview" value="<?php echo $namePreviewModel ?>">
                            <input type="hidden" name="item_id" value="<?php echo $item->getId(); ?>">

                            <span style="display: none">
                                  <input class="txt-preview-upload-custom-design" item-id="<?php echo $item->getId(); ?>" id="txt-preview-upload-custom-design-<?php echo $item->getId() ?>" type="file" name="custom_preview" />
                            </span>
                        </form>
                        <a href="<?php echo $_product->getProductUrl() ?>?re_up=<?php echo $item->getId(); ?>" class="action primary"><?php echo __('Upload Design') ?></a>
                    <?php elseif($designType == 1 && $customerUploadDesign != '' && $isNewProof == 1 && ($status == 'design_approved' || $status === 'customer_reject')) : ?>
                            <span><?php echo __('Design is approved by the admin, please re-confirm.') ?></span>
                            <br/>
                            <a href="<?php echo $_product->getProductUrl() ?>?preview_design=<?php echo $item->getId(); ?>" target="_blank"><?php echo __('Preview the file') ?></a>
                            <br/>
                            <a href="<?php echo $block->getMediaUrl(). 'advancepreview/custom_previews/product_id_'.$productId.'/'.$modelPreview.'/'.$customerUploadDesign ?>"><?php echo __('Download the file') ?></a>
                            <br/>
                            <button type="button" class="btn-update-design-item-status" id="btn-update-design-item-status-<?php echo $item->getId(); ?>" style="display: inline-block" item-id="<?php echo $item->getId(); ?>" item-status="<?php echo 'design_full_approved'; ?>" project-name="<?php echo $item->getProduct()->getName(); ?>"><?php echo __('Confirm') ?></button>
                            <br/>
                            <button type="button" class="btn-update-design-item-status" id="btn-update-design-item-status-<?php echo $item->getId(); ?>" style="display: inline-block" item-id="<?php echo $item->getId(); ?>" item-status="<?php echo 'customer_reject'; ?>" project-name="<?php echo $item->getProduct()->getName(); ?>"><?php echo __('Reject') ?></button>
                        <?php elseif($designType == 1 && $customerUploadDesign == '') : ?>
                            <?php if($isAdminCreateDesign == 1) : ?>
                                <?php if($adminUploadFile != '') : ?>
                                    <a href="<?php echo $_product->getProductUrl() ?>?preview_design=<?php echo $item->getId(); ?>" target="_blank"><?php echo __('Preview the file') ?></a>
                                    <br/>
                                    <a href="<?php echo $block->getMediaUrl(). 'advancepreview/custom_previews/product_id_'.$productId.'/'.$modelPreview.'/'.$adminUploadFile ?>"><?php echo __('Download the file') ?></a>
                                    <br/>
                                    <p>
                                        <?php echo __('Design is uploaded by the admin, please re-confirm.') ?>
                                    </p>
                                    <button type="button" class="btn-approved-admin-create-design" id="btn-approved-admin-create-design-<?php echo $item->getId(); ?>" item-id="<?php echo $item->getId(); ?>" style="display: inline-block" item-status="<?php echo '1'; ?>" admin-file="<?php echo $adminUploadFile; ?>" project-name="<?php echo $item->getProduct()->getName(); ?>"><?php echo __('Approve') ?></button>
                                    <button type="button" class="btn-reject-admin-create-design" id="btn-reject-admin-create-design-<?php echo $item->getId(); ?>" item-id="<?php echo $item->getId(); ?>" style="display: inline-block" item-status="<?php echo '0'; ?>" admin-file="<?php echo $adminUploadFile; ?>" project-name="<?php echo $item->getProduct()->getName(); ?>"><?php echo __('Reject') ?></button>
                                 <?php endif; ?>
                            <?php elseif($isAdminCreateDesign == 0)  : ?>
                                <a href="<?php echo $_product->getProductUrl() ?>?re_up=<?php echo $item->getId(); ?>" class="action primary"><?php echo __('Upload Design') ?></a>
                            <?php endif; ?>
                        <?php endif ?>
                    <?php if($status == 'shipped') : ?>
                    <button type="button" class="btn-update-design-item-status" id="btn-update-design-item-status-<?php echo $item->getId(); ?>" style="display: inline-block" item-id="<?php echo $item->getId(); ?>" item-status="<?php echo 'delivered'; ?>" project-name="<?php echo $item->getProduct()->getName(); ?>" total="<?php echo $total; ?>"><?php echo __('Delivered') ?></button>
                    <?php elseif($status == 'delivered' && $invoiceId > 0) : ?>
                    <?php
                    $invoiceUrl = $block->getUrl('advance_preview/order/DownloadInvoicePdf/').'invoice_id/'.$invoiceId.'/order_id/'.$orderId;;
                    if($token != '') {
                        $invoiceUrl .= '/token/'.sha1($token);
                    }
                    ?>
                    <a class="action primary" target="_blank" href="<?php echo $invoiceUrl; ?>"><?php echo __('View Invoice') ?></a>
                    <?php endif; ?>

                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <input type="hidden" id="txt-re-upload-design-url" value="<?php echo $urls['re_upload_design_url']; ?>">
    <input type="hidden" id="txt-update-item-status-url" value="<?php echo $urls['update_item_status']; ?>">
    <input type="hidden" id="txt-order-detail-url" value="<?php echo $block->getUrl('sales/order/view/order_id/'.$orderId); ?>">
    <input  type="hidden" id="txt-customer-name" value="<?php echo $order->getCustomerName(); ?>">
    <input  type="hidden" id="txt-customer-id" value="<?php echo $order->getCustomerId(); ?>">
    <input  type="hidden" id="txt-customer-email" value="<?php echo $order->getCustomerEmail(); ?>">
    <input  type="hidden" id="txt-order-increment-id" value="<?php echo $order->getIncrementId(); ?>">
    <input  type="hidden" id="txt-order-id" value="<?php echo $order->getId(); ?>">
   <script>
        require([
            'jquery',
            'customer_preview_order'
        ],function ($, customerPreviewOrder) {
            customerPreviewOrder.init();
        })
    </script>
<?php endif; ?>

