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

namespace Magetop\Advancepreview\Controller\Product;

use Magento\Framework\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
class ExportPdfOffer extends Action\Action
{
    protected $httpContext;
    protected $filesystem;
    protected $file;
    protected $fileFactory;
    protected $bookTicket;
    protected $x;
    protected $y;
    protected $company_name;
    protected $payment_term;
    protected $item_name;
    protected $ticket_price;
    protected $ticket_time;
    /**
     * @var \Magento\Framework\Stdlib\StringUtils
     */
    protected $stringUtils;
    protected $urlInterface;
    protected $priceHelper;
    protected $session;
    protected $timeHelper;
    /**
     * @var \Magetop\Bookingonline\Model\ResourceModel\BookOrders\CollectionFactory
     */
    protected $bookOrdersFactory;
    protected $productMetadata;
    protected $preview_pdf;
    protected $orderFactory;
    protected $cart;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\ProductFactory
     */
    protected $resProductFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $colProductFactory;
    /**
     * @var \Magento\Customer\Model\Session
     */
    // protected $customerSession;
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
    protected $colPreviewDiscountFactory;
    protected $colPreviewAdditionalFactory;
    protected $colPreviewThreeFactory;
    protected $dailyShippingFactory;
    protected $font_small = 10;
    protected $font_normally = 12;
    protected $font_big = 16;
    protected $itemFactory;
    protected $resItemFactory;
    protected $wishlistOptionFactory;
    protected $addressFactory;
    protected $previewHelper;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Stdlib\StringUtils $stringUtils,
        \Magento\Framework\UrlInterface $urlInterface,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magento\Customer\Model\Session $session,
        \Magento\Framework\App\ProductMetadataInterface $productMetadata,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $colProductFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        \Magento\Wishlist\Model\ItemFactory $itemFactory,
        \Magento\Wishlist\Model\ResourceModel\ItemFactory $resItemFactory,
        \Magento\Wishlist\Model\ResourceModel\Item\Option\CollectionFactory $wishlistOptionFactory,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magetop\Advancepreview\Helper\Data $previewHelper
    )
    {
        parent::__construct($context);
        $this->httpContext = $httpContext;
        $this->filesystem = $filesystem;
        $this->file = $file;
        $this->fileFactory = $fileFactory;
        $this->stringUtils = $stringUtils;
        $this->urlInterface = $urlInterface;
        $this->priceHelper = $priceHelper;
        $this->session = $session;
        $this->productMetadata = $productMetadata;
        $this->orderFactory = $orderFactory;
        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->httpContext = $httpContext;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->customerFactory = $customerFactory;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->itemFactory = $itemFactory;
        $this->resItemFactory = $resItemFactory;
        $this->wishlistOptionFactory = $wishlistOptionFactory;
        $this->addressFactory = $addressFactory;
        $this->previewHelper = $previewHelper;
    }
    public function execute()
    {
        //  try {
            $prwviewMedia = '/advancepreview/icons/';
            $pdf = new \Zend_Pdf();
            $this->setPreviewPdf($pdf);
            /** @var \Zend_Pdf_Page $page*/
            $page = $this->getPreviewPdf()->pages[0];
            //   $page->drawLine(0,842 - $ticketHeight,595,842 - $ticketHeight);
            $this->x = 20;
            $this->y = 832; //print table row from page top – 100px
            $imageDesign = $prwviewMedia.'myfitmix-logo.png';
            //logo
            $this->addImageToPdf($page,$imageDesign,427, $this->y - 77, 567, $this->y);
            $this->y -= 77;
            $this->y -= $this->font_small * 2;
            $xLeft = $this->x;
            $xRight = 297 + 50; //center + 50

            $itemId = $this->getRequest()->getParam('item_id',0);
            $item =  $this->itemFactory->create()->load($itemId);;
            $token = $this->getRequest()->getParam('token','');
            $token =  trim($token);
            if($itemId <= 0|| $token == '') {
                $this->messageManager->addErrorMessage(__('Request offer not found, Please check again'));
                return $this->resultRedirectFactory->create()->setPath('index.php');

            }

            $wishlistOptions = $this->getWishlistOption($itemId);
            if(sha1($wishlistOptions['item_token']) != $token) {
                $this->messageManager->addErrorMessage(__('Request offer not found, Please check again'));

                exit;
               // return $this->resultRedirectFactory->create()->setPath('index.php');
            }
            /*echo '<pre>';
                print_r($wishlistOptions);
             echo '</pre>';*/
            $offerId = isset($wishlistOptions['offer_id']) ? $wishlistOptions['offer_id'] : '';
            $productId = isset($wishlistOptions['product_id']) ? $wishlistOptions['product_id'] : 0;
            $customerId = isset($wishlistOptions['customer_id']) ? $wishlistOptions['customer_id'] : 0;
            $customerAddress = $this->getCustomerAddress($customerId);
            $company_name = $this->getCustomerCompanyName($customerId);
            $payment_term = $wishlistOptions['payment_term'];
            $heaerText = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/header_title');
            $companyInfo = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/company_info');
            $saleManage = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/sale_manage');
            $companyInfo = trim($companyInfo) != '' ? explode("\n", str_replace("\r", "", $companyInfo)) : [];
            $yAddressLeft = $this->y;
            $yAddressRight = $this->y;
            if($customerAddress != null) {
                if($company_name && $company_name!='')
                {
                    $leftTexts = [
                        $heaerText,
                        $company_name,
                        $customerAddress->getPrefix() . ' '. $customerAddress ->getFirstname() . ' '. $customerAddress->getLastname(),
                    ];
                }
                else{
                    $leftTexts = [
                        $heaerText,
                        $customerAddress->getPrefix() . ' '. $customerAddress ->getFirstname() . ' '. $customerAddress->getLastname(),
                    ];
                }

                $tmpStreets = $customerAddress->getStreet();
                $street="";
                if(count($tmpStreets)) {
                    foreach ($tmpStreets as $tmpStreet) {
                      $street.= $tmpStreet." ";
                    }
                }
                $leftTexts[] = $street;
                if($customerAddress->getRegion() && $customerAddress->getRegion() != '') {
                    $leftTexts[] = $customerAddress->getRegion();
                }

                $leftTexts[] = $customerAddress->getPostcode()." ".$customerAddress->getCity();
                $leftTexts[] = $customerAddress->getCountryId();
                $yAddressLeft = $this->addHeaderTextLeft($page, $leftTexts,$xLeft,$this->y);
            }
            $projectName = isset($wishlistOptions['project_name']) ? $wishlistOptions['project_name'] : '';
            // right
            // $textRight1 = [
            //     'Kontakt:',
            // ];
            // if(count($companyInfo)) {
            //     foreach ($companyInfo as $itemcc) {
            //         $textRight1[] = $itemcc;
            //     }
            // }

            $projectName = wordwrap($projectName, 10, "\n", false);
            $textRight1=[" "];
            $textRight2 = [
                __('Date').':',
                __('Offer-Nr').':',
                __('Customer-Nr').':',
                __('Our Contact').':',
                "",
                __('Project name'),
            ];
            $textRight3 = [
                date('d-m-Y', strtotime($item->getAddedAt())),
                $offerId,
                $customerId,
                $saleManage,
                "",
                $projectName,
            ];
            //             $orderId = $this->getRequest()->getParam('order_id',0);



            //             $order = $this->getOrderData($orderId);
            $customerName = $this->getCustomerName($customerId);
            $yAddressRight = $this->addHeaderTextRight($page, $textRight1,$textRight2,$textRight3, $xRight, $this->y);
            $this->y = $yAddressRight < $yAddressLeft ? $yAddressRight : $yAddressLeft;
            $this->y -= 20;
            $isVailidatePrice =  $this->validateUpdatePrice($productId,$wishlistOptions["customDiscounts"], $wishlistOptions['request_option']);
            $isVerifyTierPrice = $this->checkTierPriceChange($wishlistOptions['request_option'], $wishlistOptions["tierQtyPrice"], $wishlistOptions['qty']);
            if(!$isVailidatePrice || !$isVerifyTierPrice) {
                $this->addWellcomeCustomer($page, $customerName, $xLeft, $this->y,1);
            }
            else{
                $this->addWellcomeCustomer($page, $customerName, $xLeft, $this->y,0);
            }

            $product = $this->getProductById($productId);
            $productInfo = [
                'product_name'=>$product->getName(),
                'product_sku'=>$product->getSku(),
                'product_description'=>strip_tags($product->getData('pdf_product_description')),
            ];
            $productImageUrl = $this->getProductImageUrl($product);
            if($productImageUrl != '') {
                $tmpArImages = explode('media',$productImageUrl);
                if(count($tmpArImages)) {
                    $productImageUrl = $tmpArImages[1];
                    $this->addImageToPdf($page,$productImageUrl,$this->x, $this->y - 80,$this->x + 80,$this->y);
                    $this->y -= 90;
                }
            }

            /*$orderItems = $this->getOrderInfo($order);*/

            $this->renderItems($page,$wishlistOptions,$productInfo,$payment_term);
            $this->setPreviewPdf($pdf,true);
            $newPage = $this->getPreviewPdf()->pages[1];
            $this->renderOrderData($newPage,$offerId,$product );
            $buttonLefts = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_left');
            $buttonLefts = $buttonLefts != '' ?  explode("\n", str_replace("\r", "", $buttonLefts)) : [];
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
            $style = new \Zend_Pdf_Style();
            $style->setFont($font,$this->font_small);
            $newPage->setStyle($style);
            $yFoot = 55;
            $newPage->drawLine($this->x,70,580,70);
            if(count($buttonLefts)) {
                $yl = $yFoot; //$yText - 10;
                foreach ($buttonLefts as $buttonLeft) {
                    $newPage->drawText($buttonLeft,$this->x,$yl,'UTF-8');
                    $yl -= 15;
                }
            }
            $buttonRights = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_right');
            $buttonRights = $buttonRights != '' ?  explode("\n", str_replace("\r", "", $buttonRights)) : [];
            if(count($buttonRights)) {
                $yl = $yFoot; //$yText - 10;
                foreach ($buttonRights as $buttonRight) {
                    $newPage->drawText($buttonRight,$this->x + 290,$yl,'UTF-8');
                    $yl -= 15;
                }
            }
            $fileName = 'myfitmix-offer-'.date('Y-m-d-H-i-s',strtotime($item->getAddedAt())).'.pdf';
            $this->fileFactory->create(
                $fileName,
                $pdf->render(),
                DirectoryList::VAR_DIR,
                'application/pdf'
            );
        // }
        // catch (\Exception $exception) {
        //     $this->messageManager->addErrorMessage('Can not download Design '.$exception->getMessage());
        //     //            echo $exception->getMessage();
        //     $this->resultRedirectFactory->create()->setPath('index.php');
        // }
        //        $this->messageManager->addErrorMessage('Download Design success');
        return $this->resultRedirectFactory->create()->setPath('index.php');
    }
    protected function getWishlistOption($wItemId) {
        $collection = $this->wishlistOptionFactory->create()
            ->addFieldToSelect(array('value'))
            ->addFieldToFilter('wishlist_item_id',$wItemId)
            ->addFieldToFilter('code','info_buyRequest');
        $infoBuyRequest = $collection && $collection->getSize() > 0 ? $collection->getFirstItem()->getData('value') : '';
        $infoBuyRequest = $infoBuyRequest != '' ? (array)json_decode($infoBuyRequest) : [];
        $previewOptions = [];
        /*echo '<pre>';
            print_r($infoBuyRequest);
        echo '<pre>';*/
        if(count($infoBuyRequest) && isset($infoBuyRequest['mgt_custom_qty'])) {
            $productId = isset($infoBuyRequest['product']) ? $infoBuyRequest['product'] : 0;
            $qty = isset($infoBuyRequest['qty']) ? $infoBuyRequest['qty'] : 0;
            $customerId = isset($infoBuyRequest['customer_id']) ? $infoBuyRequest['customer_id'] : 0;
            $_product = $this->getProductById($productId);
            $tierPrice = $this->getTierPriceByProductId($_product);
            $tierQtyPrice = $this->getTierPriceItemByQty($tierPrice, $qty);
            $ourPrice = $this->getCustomTierOurPrice($_product,$tierQtyPrice);
            $customDiscounts = $this->getPreviewDiscounts($productId);
            $i = 0;
            $totalExtraPrice = 0;
            $shippingPrice = 0;
            $designType = isset($infoBuyRequest['txt_custom_preview_design_type']) ? $infoBuyRequest['txt_custom_preview_design_type'] : 0;
            $shippingDailyId = isset($infoBuyRequest['txt_daily_shipping']) ? $infoBuyRequest['txt_daily_shipping'] : 0;
            $offerId = isset($infoBuyRequest['request_offer_id']) ? $infoBuyRequest['request_offer_id'] : 0;
            $projectName = isset($infoBuyRequest['custom_project_name']) ? $infoBuyRequest['custom_project_name'] : '';
            $paramsAdditionOptions = isset($infoBuyRequest['preview_additional_options']) ? $infoBuyRequest['preview_additional_options'] : [];
            $payment_term =  isset($infoBuyRequest['txt-payment-term']) ? $infoBuyRequest['txt-payment-term'] : 0;
            $shippingDaily = $this->getDailyShippingById($shippingDailyId);
            $dailyPrice = 0;
            $dailyTitle = '';
            $dailyDay  = 0;
            $additionOptionTitle = '';
            if($shippingDaily != null && $shippingDaily->getId()) {
                $dailyPrice = $shippingDaily->getData('amount');
                $dailyTitle = $shippingDaily->getData('delivery_type');
                $dailyDay = $shippingDaily->getData('delivery_days');
                //                    $dailyDays = $shippingDaily->getData('delivery_days');
            }
            $processingPrice  = 0;
            foreach ($customDiscounts as $customDiscount) {
                if ($i == 0) {
                    $i++;
                    continue;
                }
                if ($designType == 1 && $i == 1) {
                    $discount = $_product->getData('pcto_discount');
                    $defaultValue = $ourPrice * $qty;
                    $additionOption = $this->getAdditionPriceByIds($paramsAdditionOptions, $defaultValue);
                    $totalExtraPrice += $additionOption['price'];
                    $additionOptionTitle .= implode(', ',$additionOption['title']);
                } else if ($i == $customDiscounts->getSize() - 1) {
                    $shippingPrice = $customDiscount->getData('discount_price') + ($ourPrice * $dailyPrice * $qty) / 100;
                    continue;
                }
                if($customDiscount->getData('discount_title')=="Processing & Finishing")
                {
                   $processingPrice =  $qty <4 ? 0:$customDiscount->getData('discount_price');
                }
                $totalExtraPrice += ($customDiscount->getData('discount_title')=="Processing & Finishing" && $qty <4) ? 0: $customDiscount->getData('discount_price');
                $i++;
            }
            $itemToken = isset($infoBuyRequest['uenc']) ? $infoBuyRequest['uenc'] : '';
            if((($ourPrice * $qty) + $totalExtraPrice + $shippingPrice) < 50)
            {
                $shippingPrice =$shippingPrice+4;
            }
            $previewOptions = [
                'our_price'=>$ourPrice,
                'qty'=>$qty,
                'extra_price'=>$totalExtraPrice - $processingPrice,
                'processing_price'=>$processingPrice,
                'shipping_price'=>$shippingPrice,
                'discount'=>$_product->getData('pcto_discount'),
                'offer_id'=>$offerId,
                'product_id'=>$productId,
                'customer_id'=>$customerId,
                'project_name'=>$projectName,
                'addition_title'=>$additionOptionTitle,
                'daily_title'=>$dailyTitle,
                'daily_day'=>$dailyDay,
                'item_token'=>$itemToken,
                'request_option' => $infoBuyRequest,
                'tierQtyPrice'=>$tierQtyPrice,
                'customDiscounts'=>$customDiscounts,
                'payment_term' => $payment_term
            ];
        }
        return $previewOptions;
    }
    protected function getProductImageUrl(
        $product
    ) {
        $imageUrl = '';

        if($product) {
            $helperImport = $this->_objectManager->get('Magento\Catalog\Helper\Image');
            $imageUrl = $helperImport->init($product, 'product_page_image_small')
                ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
                ->resize(380)
                ->getUrl();
        }
        return $imageUrl;
    }
    protected function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }

    protected function insertLogo(\Zend_Pdf_Page &$page,$x,$y, $store = null)
    {
        $this->y = $this->y ? $this->y : 595;
        $image = 'myfitmix-logo.png';
        try {
            if ($image) {
                $imagePath = '/advancepreview/custom_previews/product_id_21/test_pdf/' . $image;
                $mediaDictory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
                if ($mediaDictory->isFile($imagePath)) {
                    $image = \Zend_Pdf_Image::imageWithPath($mediaDictory->getAbsolutePath($imagePath));
                    $top = 822;
                    //top border of the page
                    $widthLimit = 120;
                    //half of the page width
                    $heightLimit = 120;
                    //assuming the image is not a "skyscraper"
                    $width = $image->getPixelWidth();
                    $height = $image->getPixelHeight();

                    //preserving aspect ratio (proportions)
                    $ratio = $width / $height;
                    if ($ratio > 1 && $width > $widthLimit) {
                        $width = $widthLimit;
                        $height = $width / $ratio;
                    } elseif ($ratio < 1 && $height > $heightLimit) {
                        $height = $heightLimit;
                        $width = $height * $ratio;
                    } elseif ($ratio == 1 && $height > $heightLimit) {
                        $height = $heightLimit;
                        $width = $widthLimit;
                    }

                    $y1 = $y - $height;
                    $y2 = $y;
                    $x1 = $x;
                    $x2 = $x + $width;

                    //coordinates after transformation are rounded by Zend
                    $page->drawImage($image, $x1, $y1, $x2, $y2);

                }
            }
        }
        catch (\Exception $exception) {
            return false;
        }
        return true;
    }
    protected function addHeaderTextLeft(
        \Zend_Pdf_Page &$page,
        $texts,
        $x1,
        $y1
    ) {
        $y = $y1;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style = new \Zend_Pdf_Style();
        $style->setFont($font,$this->font_small - 1);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $fistText = $texts[0];
        $page->drawText($fistText,$x1,   $y,'UTF-8');
        $y -= $this->font_small * 3;
        $i = 0;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        foreach ($texts as $text) {
            if($i == 0) {
                $i++;
                continue;
            }
            //             $page->drawText($text,$x1,  $y,'UTF-8');
            $y = $this->addBlockText($page,$x1,$x1,275,$y,$text,$font);
            $y -= $this->font_small + 5;
            $i++;
        }
        return $y;

    }
    protected function getTierPriceByProductId($product) {
        $tierPrices = [];
        //        $_product = $this->getProductById($productId);
        if($product != null) {
            $tierPrices = $product->getTierPrice();
        }
        return $tierPrices;
    }
    protected function getTierPriceItemByQty($tierPriecs = [], $qty = 0) {
        $price = 0;
        $lastIndex = count($tierPriecs) ? count($tierPriecs) - 1 : 0;
        $lastItem = isset($tierPriecs[$lastIndex]) ? $tierPriecs[$lastIndex] : [];
        if($lastIndex > 0 && isset($lastItem['price_qty']) && $qty >= $lastItem['price_qty']) {
            $price = $lastItem['price'];
        }
        else {
            for($i = 0; $i < count($tierPriecs); $i++) {
                if($i == 0 && $qty < $tierPriecs[0]['price_qty']) {
                    $price = $tierPriecs[0]['price'];
                    break;
                }
                if($i + 1 < count($tierPriecs)) {
                    $currentTeir = $tierPriecs[$i];
                    $nextTier = $tierPriecs[$i + 1];
                    if($qty >= $currentTeir['price_qty'] && $qty < $nextTier['price_qty']) {
                        $price = $currentTeir['price'];
                        break;
                    }
                }
            }
        }

        return $price;
    }
    protected function getCustomTierOurPrice($product, $price = 0) {

        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
            //            $product = $this->getProductById($productId);
            if($product) {
                $discount = $product->getData('pcto_discount');
                /* if($discount > 0) {
                    $price -= ($price * $discount) / 100;
                }*/
            }
        }
        return $price;

    }
    protected function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->session->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }
    protected function getCustomerName($customerId) {
        $customer = $this->customerFactory->create()->load($customerId);
        return $customer->getData('firstname') . ' ' .$customer->getData('lastname');
    }
    protected function getCustomerAddress($customerId) {
        $shippingAddress = null;
        $customer = $this->customerFactory->create()->load($customerId);
        $shippingAddressId = $customer->getDefaultShipping();
        $shippingAddress = $this->addressFactory->create()->load($shippingAddressId);
        return $shippingAddress;
    }

    protected function getCustomerCompanyName($customerId) {
      $customer = $this->customerFactory->create()->load($customerId);
      return $customer->getData('custom_company_name');
    }

    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }
    protected function addHeaderTextRight(
        \Zend_Pdf_Page &$page,
        $texts1,
        $texts2,
        $texts3,
        $xRight,
        $y1
    ) {
        $y = $y1;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style = new \Zend_Pdf_Style();
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $i = 0;
        foreach ($texts1 as $text1) {
            //     $page->drawText($text1,$xRight,  $y,'UTF-8');
            //     if($i == 0) {
            //         $y -= $this->font_small * 3;
            //     }
            //     else {
            //         $y -= $this->font_small + 5;
            //     }

            //     $i++;
            // }
            if($text1){
                $page->drawText($text1, $xRight,  $y, 'UTF-8');
                if ($i == 0) {
                    $y -= $this->font_small * 3;
                } else {
                    $y -= $this->font_small + 5;
                }
            }

            $i++;
        }
        // blog 2;
        // $y -= $this->font_small + 5;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $j = 0;
        foreach ($texts2 as $text2) {
          $texts = [];
            $page->drawText($text2,$xRight,  $y,'UTF-8');
            $text3 = $texts3[$j];
            $texts[] =  $text3;
            if(strlen($text3) > 20)
            {
              $texts = explode("/n",substr_replace($text3, "/n", 20, 0));
            }
            if(count($texts)) {
              foreach ($texts as $text) {
                  $page->drawText($text,$xRight + 100,  $y,'UTF-8');
                  $y -= $this->font_small + 5;
              }
            }
            $j++;
        }
        //        $this->y = $y;
        return $y;

    }
    protected function addWellcomeCustomer(
        \Zend_Pdf_Page &$page,
        $customerName,
        $x1,
        $y1,
        $new
    ) {
        $y = $y1;
        $style = new \Zend_Pdf_Style();
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_big);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Offer'),$x1,$y,'UTF-8');
        $y -= $this->font_small * 2;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Dear').' '.$customerName.',',$x1, $y,'UTF-8');
        $y -= $this->font_small * 2;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small -1);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        if($new==0){
            $page->drawText(__('we are glad to make you an offer:'),$x1, $y,'UTF-8');
        }
        else{
            $page->drawText(__('we are glad to make you an offer, using the current prices:'),$x1, $y,'UTF-8');
        }
        $y -= 10;
        $this->y = $y;

    }
    protected function renderItems(
        \Zend_Pdf_Page &$page,
        $orderItems,
        $productInfo,
        $payment_term
    ) {
        //        print_r($orderItems);
        $tax = 19;
        // render header
        $style = new \Zend_Pdf_Style();
        $yText = $this->y - 20;
        /*  $fillColor = new \Zend_Pdf_Color_Rgb(0,0,0);
        $lineColor = new \Zend_Pdf_Color_Rgb(0.8,0.8,0.8);
       $this->drawBlockRect($page,$this->x, $this->y,$this->x + 520, $yText,$fillColor, $lineColor);*/
        $bg = 'advancepreview/icons/bg_gray.png';
        $this->addImageToPdf($page,$bg,$this->x,$yText,$this->x + 560,$this->y);
        // add text
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
       $style->setFont($font,$this->font_small);
       $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        //    $page->drawText('Dear '.$customerName,$x1, $y);
        $xCol = $this->x;
        $headers = [
            __('Pos'),
            __('Q-ty'),
            __('Unit'),
            __('Description'),
            __('Price'),
            __('Discount'),
            __('Unit price'),
            __('Total price'),
        ];
        $h = 0;
        foreach ($headers as $key => $header) {
            if($h == count($headers) - 1) {
                $wlast = $this->widthForStringUsingFontSize($header,$font,$this->font_small);
                $xLast = ($xCol + 90) - $wlast - 2;
                $page->drawText($header,$xLast, $yText + 5,'UTF-8');
            }
            else {
                if($h == 4 || $h == 6) {
                    $wTextHeaderPriceLable = $this->widthForStringUsingFontSize($header,$font,$this->font_small);
                    $xColAlignRightLable = ($xCol + 77.5) - $wTextHeaderPriceLable;
                    $page->drawText($header,$xColAlignRightLable, $yText + 5,'UTF-8');
                }
                elseif($h == 5) {
                    $wTextHeaderPriceLable = $this->widthForStringUsingFontSize($header,$font,$this->font_small);
                    $xColAlignRightLable = ($xCol + 60) - $wTextHeaderPriceLable;
                    $page->drawText($header,$xColAlignRightLable, $yText + 5,'UTF-8');
                }
                else if($h == 2) {
                    $page->drawText($header,$xCol, $yText + 5,'UTF-8');
                }
                else {
                    $page->drawText($header,$xCol + 5, $yText + 5,'UTF-8');
            }

            }

            if($h == 3) {
                $xCol += 135;
            }
            elseif($h == 0 || $h == 2)  {
                $xCol += 30;
            }
            elseif($h == 1 || $h == 5)  {
                $xCol += 60;
            }
            else {
                $xCol += 77.5;
            }
            $h++;
        }
        if(count($orderItems)) {
            $discount = $orderItems['discount'];
            $qty = $orderItems['qty'];
            $k = 1;
            $grandTotalPrice = 0;
            $yText -= 20;
            foreach ($orderItems as $keyV => $orderItem) {
                $xCol = $this->x;

                $colPrice = 0;

                if($keyV == 'our_price') {
                    $m = 0;
                    //                    foreach ()
                    $colPrice = $orderItems['our_price'];

                }
                else if($keyV == 'extra_price') {
                    $colPrice = $orderItems['extra_price'];
                    $qty = 1;

                }
                else if($keyV == 'processing_price') {
                    $colPrice = $orderItems['processing_price'];
                    $qty = 1;

                }
                else if($keyV == 'shipping_price') {
                    $colPrice = $orderItems['shipping_price'];
                    $discount = 0;
                    $qty = 1;
                    //                    $yText -= 20;
                }
                else {
                    continue;
                }
                $priceAfterDiscount = $colPrice - ($colPrice * $discount) / 100;
                $totalOurPrice = $priceAfterDiscount * $qty;
                $grandTotalPrice += $totalOurPrice;
                $cols = [
                    $k,
                    $qty,
                    'stk',
                    'test',
                    $this->convertNumberToPrice($colPrice),
                    $discount.'%',
                    $this->convertNumberToPrice($priceAfterDiscount),
                    $this->convertNumberToPrice($totalOurPrice)
                ];
                $m = 0;
                $yDes = 0;
                foreach ($cols as $col) {
                    if($m == 3) {
                        if($keyV == 'our_price') {
                            $productName = $productInfo['product_name'];
                            $productSku = $productInfo['product_sku'];
                            $productDes = $productInfo['product_description'];
                            //                            $productDes = substr($productDes,0,45);
                            $yDes = $yText + 5;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            //                            $page->drawText($productName,$xCol, $yDes);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productName,$font);
                            $yDes -= 15;
                            $wProductName = $this->widthForStringUsingFontSize($productName,$font,$this->font_small);
                            //                            $yDes -= 15;
                            //                            $page->drawText($productSku,$xCol + 5, $yDes);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productSku,$font);
                            $yDes -= 15;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$productDes,$font);
                        }
                        elseif($keyV == 'extra_price') {
                            //                            $page->drawText('Additional printing costs 5C transparent Quality check Design service',$xCol + 5, $yText + 5);
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,__('Additional options'),$font);
                            $yDes -= 15;
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yDes,$orderItems['addition_title'],$font);
                        }
                        elseif($keyV == 'processing_price') {
                            //                            $page->drawText('Additional printing costs 5C transparent Quality check Design service',$xCol + 5, $yText + 5);
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,__('Processing & finishing'),$font);
                            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                            $style->setFont($font,$this->font_small);
                            $page->setStyle($style);
                        }
                        elseif($keyV == 'shipping_price') {
                            //                            $page->drawText('Delivery time: 8 days plus shipping',$xCol + 5, $yText + 5);
                            // $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,__('Delivery time').': '.$orderItems['daily_day'].__(' days plus shipping').'-'.$orderItems['daily_title'],$font);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,__('Delivery time') .': '.$orderItems['daily_day'].__('days plus shipping').' - '.__($orderItems['daily_title']),$font);

                        }
                        /*else {
                            $page->drawText($col,$xCol + 5, $yText + 5);
                        }*/

                        $xCol += 135;
                    }
                    else if($m == count($cols) - 1) {
                        $wlast = $this->widthForStringUsingFontSize($col,$font,$this->font_small);
                        $xLast = ($xCol + 90) - $wlast;
                        $page->drawText($col,$xLast, $yText + 5,'UTF-8');
                    }
                    elseif($m == 0 || $m == 2) {
                        if($m == 2) {
                            $page->drawText($col,$xCol, $yText + 5,'UTF-8');
                        }
                        else {
                            $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        }

                        $xCol += 30;
                    }
                    elseif($m == 1 || $m == 5) {
                        if($m == 5) {
                            $wTmpTextDiscount = $this->widthForStringUsingFontSize($col,$font,$this->font_small);
                            $xColDoscpimtAlignRight = ($xCol + 60) - $wTmpTextDiscount;
                            $page->drawText($col,$xColDoscpimtAlignRight, $yText + 5,'UTF-8');
                        }
                        else {
                            $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        }

                        $xCol += 60;
                    }
                    else {
                        //                        $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        if($m == 4 || $m == 6) {
                            $wTmpTextPrice = $this->widthForStringUsingFontSize($col,$font,$this->font_small);
                            $xColAlignRight = ($xCol + 77.5) - $wTmpTextPrice;
                            $page->drawText($col,$xColAlignRight, $yText + 5,'UTF-8');
                        }
                        else {
                            $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        }
                        $xCol += 77.5;
                    }
                    $m++;
                    if($m == count($cols)) {
                        $yText = $yDes - 22;
                    }
                }
                $page->drawLine($this->x,$yText + 18,580,$yText + 18);
                $k++;
            }
            //            $yText -= 10;
            //            Net Amount
            $xTotal = $xCol + (55 * 6) + 135;
            $page->drawText(__('Net Amount'),$xCol, $yText,'UTF-8');
            $textGrand = $this->convertNumberToPrice($grandTotalPrice);
            //545 -> 575
            $wGrandTotal = $this->widthForStringUsingFontSize($textGrand,$font,$this->font_small);
            $xGrandTotal = 580 - $wGrandTotal;
            $page->drawText($textGrand,$xGrandTotal, $yText,'UTF-8');
            $taxAmount = ($grandTotalPrice * $tax) / 100;
            $grandTotalPriceTax = $grandTotalPrice + $taxAmount;
            $taxAmount = $this->convertNumberToPrice($taxAmount);

            $yText -= 15;
            $tax =  number_format((float)$tax, 2, '.', '');
            $page->drawText($tax.'%'.' '. __('VAT'),$xCol, $yText,'UTF-8');
            $wTax = $this->widthForStringUsingFontSize($taxAmount,$font,$this->font_small);
            $xTax = 580 - $wTax;
            $page->drawText($taxAmount,$xTax, $yText,'UTF-8');

            $yText -= 15;
            $fillColor = new \Zend_Pdf_Color_Rgb(0,0,0);
            $lineColor = new \Zend_Pdf_Color_Rgb(0,0,0);
            //            $this->drawBlockRect($page,$this->x, $yText + 15,$this->x + 520, $yText - 5,$fillColor, $lineColor);
            $bg = 'advancepreview/icons/bg_gray.png';
            //            $this->addImageToPdf($page,$bg,$this->x,$yText - 10, $this->x + 520,$yText + 10);
            $this->addImageToPdf($page,$bg,$this->x,$yText - 10, $this->x + 560,$yText + 10);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            //            $page->drawText('Amount to pay '.$this->convertNumberToPrice($grandTotalPriceTax),$xCol + 5, $yText - 5,'UTF-8');
            $txtGrandTotalPriceTax = $this->convertNumberToPrice($grandTotalPriceTax);
            $wgrandTotalPriceTax = $this->widthForStringUsingFontSize($txtGrandTotalPriceTax,$font,$this->font_small);
            $xGrandTotalPriceTax = 580 - $wgrandTotalPriceTax - 2;
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
		   $style->setFont($font,$this->font_small);
		   $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $page->drawText(__('Amount to pay'),$xCol + 5, $yText - 5,'UTF-8');
            $page->drawText($txtGrandTotalPriceTax,$xGrandTotalPriceTax, $yText - 5,'UTF-8');
            //
            $yText -= 30;
            $exworks = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_1');
            $exworks = trim($exworks) ? explode("\n", str_replace("\r", "", $exworks)) : [];
            $exworks = array_merge($exworks,explode("~", __('Payment term '.$payment_term)));
            /* $page->drawText('Incoterms - Ex Works');
            $yText -= 15;
            $page->drawText('Payment terms: to pay in advance with 2% discount (myfitmix GmbH, Commerzbank Mainz, Bank code: 550 400 22,'.$this->convertNumberToPrice($grandTotalPriceTax),$xCol, $yText);
            $yText -= 15;*/
            /*  $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
            $style->setFont($font,$this->font_small);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);*/
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
		   $style->setFont($font,$this->font_small);
		   $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            if(count($exworks)) {
                foreach ($exworks as $exwork) {
                    $page->drawText(trim($exwork),$this->x, $yText,'UTF-8');
                    $yText -= 15;
                }
            }

            //$page->drawText('Account Nr.: 2316420; for international bank transfers - BIC/Swift: COBADEFF550, IBAN DE02550400220231642000)'.$this->convertNumberToPrice($grandTotalPriceTax),$xCol, $yText);


        }



    }
    protected function renderOrderData(
        \Zend_Pdf_Page &$page,
        $offerId,
        $product
    ) {
        $x = 25;
        $y = 842 - 100;
        $style = new \Zend_Pdf_Style();
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Offer-Nr'),$x,$y,'UTF-8');
        $page->drawText($offerId,$x + 100,$y,'UTF-8');
        $page->drawText('Seite 2 von 2',$x + 450,$y,'UTF-8');
        $y -= 40;
        $rule2 = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_2');
        //        $page->drawText($rule2,$x,$y,'UTF-8');
        //new is text area
        $y = $this->addBlockText($page,$x,$x,570,$y,$rule2,$font);
        $y -= 20;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Quantity variance:'), $x, $y, 'UTF-8');
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $rule3 = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_3');
        $y -= 18;
        //        $page->drawText($rule3,$x,$y,'UTF-8');
        $y = $this->addBlockText($page,$x,$x,570,$y,$rule3,$font);
        $y -= 22;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Delivery time:'),$x,$y,'UTF-8');
        $y -= 18;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        //        $page->drawText(strip_tags($product->getData('pdf_delivery_time')),$x,$y,'UTF-8');
        $y = $this->addBlockText($page,$x,$x,585,$y,strip_tags($product->getData('pdf_delivery_time')),$font);
        $y -= 22;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Standard-PU').':',$x,$y,'UTF-8');
        $y -= 18;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        //        $page->drawText(strip_tags($product->getData('pdf_packaging')),$x,$y,'UTF-8');
        $y = $this->addBlockText($page,$x,$x,585,$y,strip_tags($product->getData('pdf_packaging')),$font);
        $y -= 22;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Best before').':',$x,$y,'UTF-8');
        $y -= 18;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $bestBefore = strip_tags($product->getData('pdf_best_before'));
        /*if(strpos($bestBefore,'up to 24 months') !== false) {
            $arBestBefores = explode('up to 24 months',$bestBefore);
            $bestBefore1 = $arBestBefores[0];
            $page->drawText($bestBefore1,$x,$y);
            $wBefore1 = $this->widthForStringUsingFontSize($bestBefore1,$font,$this->font_small);
            $wBefore1 += 5;
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
            $style->setFont($font,$this->font_small);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $page->drawText('up to 24 months',$wBefore1,$y);
            $wBefore1 +=  $this->widthForStringUsingFontSize($bestBefore1,$font,$this->font_small);
            $wBefore1 += 5;
            $bestBefore2 = $arBestBefores[1];
            $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
            $style->setFont($font,$this->font_small);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $page->drawText($bestBefore2,$wBefore1,$y);
        }*/
        //        $page->drawText(strip_tags($product->getData('pdf_best_before')),$x,$y,'UTF-8');
        $y = $this->addBlockText($page,$x,$x,585,$y,strip_tags($product->getData('pdf_best_before')),$font);
        //
        $y -= 22;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Ingredients').':',$x,$y,'UTF-8');

        $y -= 18;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        //        $page->drawText(strip_tags($product->getData('pdf_ingredients')),$x,$y,'UTF-8');
        $y = $this->addBlockText($page,$x,$x,585,$y,strip_tags($product->getData('pdf_ingredients')),$font);
        $y -= 22;
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText(__('Customs tariff number').':',$x,$y,'UTF-8');

        $y -= 18;

        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText($product->getData('pdf_customs_tariff_number'),$x,$y,'UTF-8');

        $y -= 22;

        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,$this->font_small);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $lastRules =  $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_4');
        $lastRules = trim($lastRules) != '' ? explode("\n", str_replace("\r", "", $lastRules)) : [];
        foreach ($lastRules as $kr => $lastRule) {
            if($kr == 0) {
                $y -= 22;
                $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
                $style->setFont($font,$this->font_small);
                $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
                $page->setStyle($style);
                $page->drawText($lastRule,$x,$y,'UTF-8');

            }
            else if($kr == count($lastRules) - 1) {
                $y -= 22;
                $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                $style->setFont($font,$this->font_small);
                $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
                $page->setStyle($style);
                $page->drawText($lastRule,$x,$y,'UTF-8');
            }
            else {
                $y -= 22;
                $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
                $style->setFont($font,$this->font_small);
                $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
                $page->setStyle($style);
                $page->drawText($lastRule,$x,$y,'UTF-8');
            }
        }
        //        $page->drawText('We are Bio-certified: DE-ÖKO-005.',$x,$y);
        $y -= 22;
        /*   $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
          $style->setFont($font,$this->font_small);
          $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
          $page->setStyle($style);
         $page->drawText('We hope our offer corresponds to your expectations!',$x,$y);
          $y -= 20;
          $page->drawText('With best regards,',$x,$y);
          $y -= 60;
          $page->drawText('Oleksandr Shcherbina',$x,$y);*/
    }
    public function getAdditionPriceByIds($ids = [], $ourprice = 0)
    {
        $price = 0;
        $titles = [];
        if (count($ids)) {
            $collection = $this->colPreviewAdditionalFactory->create()
                ->addFieldToSelect(array('*'))
                ->addFieldToFilter('addition_id', array('in' => implode(',', $ids)));
            // echo (string)$collection->getSelect();
            if ($collection && $collection->getSize() > 0) {
                foreach ($collection as $item) {
                    $title = trim($item->getData('title'));
                    $dbprice = $item->getData('price');
                    $titles[] = __($title);
                    if (str_contains(strtolower($title), '5c transparent')) {
                        $price += $ourprice * $dbprice;
                    } else {
                        $price += $dbprice;
                    }
                }
            }
        }
        return array(
            'title' => $titles,
            'price' => $price
        );
    }
    protected function getAddDiscountAdditionAllPrice($price, $product) {
        //        $product = $this->getProductById($productId);
        $priceDiscount = $price;
        $customerGroup = $this->getCustomerGroup();
                if($customerGroup > 1) {
                    if($product) {
                $discount = $product->getData('pcto_discount');
                /*if($discount > 0) {
                            $priceDiscount -= ($price * $discount) / 100;
                        }*/
            }
        }

        return $priceDiscount;
    }
    protected function drawBlockRect(
        \Zend_Pdf_Page &$page,
        $x1,
        $y1,
        $x2,
        $y2,
        $color,
        $lineColor
    ) {
        try {
            $style = new \Zend_Pdf_Style();
            $style->setFillColor($color);
            $style->setLineColor($lineColor);
            $page->setStyle($style);
            $page->drawRectangle($x1,$y1,$x2,$y2,\Zend_Pdf_Page::SHAPE_DRAW_STROKE);
            return true;
        }
        catch (\Exception $exception) {

        }
        return false;
    }
    protected function getOrderInfo($order) {

        $rowDataItems = [];
        //        $requestOptions = [];


        if($order) {
            $tax = 19;
            $m = 0;
            $items = $order->getAllItems();

            foreach ($items as $item) {
                $m++;

                $_product = $item->getProduct();
                $productId = $_product->getId();
                $requestOption = $item->getProductOptionByCode('info_buyRequest');
                $shippingDailyId = isset($requestOption['txt_daily_shipping']) ? $requestOption['txt_daily_shipping'] : 0;
                $shippingDaily = $this->getDailyShippingById($shippingDailyId);
                $dailyPrice = 0;
                if($shippingDaily != null && $shippingDaily->getId()) {
                    $dailyPrice = $shippingDaily->getData('amount');
                    //                    $dailyDays = $shippingDaily->getData('delivery_days');
                }
                $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : 0;
                $designType = isset($requestOption['txt_custom_preview_design_type']) ? $requestOption['txt_custom_preview_design_type'] : 0;
                // $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : 0;
                $qty = isset($requestOption['qty']) ? $requestOption['qty'] : 1;
                $projectName = isset($requestOption['custom_project_name']) ? trim($requestOption['custom_project_name']) : '';
                $tierPrice = $this->getTierPriceByProductId($_product);
                $tierQtyPrice = $this->getTierPriceItemByQty($tierPrice, $qty);
                $ourPrice = $this->getCustomTierOurPrice($_product,$tierQtyPrice);
                $ourPriceRow = $ourPrice * $qty;
                $tmpItemPrice = ($tierQtyPrice * $qty); //$ourPriceRow;
                $customDiscounts = $this->getPreviewDiscounts($productId);
                $i = 0;
                $totalExtraPrice = 0;
                $shippingPrice = 0;
                foreach ($customDiscounts as $customDiscount) {
                    if($i == 0) { $i++; continue; }
                    if($designType == 1 && $i == 1) {
                        //                        $paramAdditionalOptions = isset($requestOption['preview_additional_options']) ? $requestOption['preview_additional_options'] : [];
                        //                        $priceDiscountItem += $this->getAdditionalOptionPrice($paramAdditionalOptions, $productId);
                    }
                    else if($i == $customDiscounts->getSize() - 1) {
                        $shippingPrice = $customDiscount->getData('discount_price') + ($ourPrice * $dailyPrice * $qty) / 100;
                        continue;
                    }
                    $totalExtraPrice += ($customDiscount->getData('discount_title')=="Processing & Finishing" && $qty <4) ? 0: $customDiscount->getData('discount_price');
                    /*   $tmpItemPrice += $priceDiscountItem;
                    $priceAfterDiscont = $this->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);*/
                    //                    $totalCustomDiscout += $priceAfterDiscont;
                    //                    echo $customDiscount->getData('discount_price') . $customDiscount->getData('discount_title').'<br/>';
                    $i++;
                }
                if(($ourPriceRow + $totalExtraPrice + $shippingPrice) < 50)
                {
                    $shippingPrice =$shippingPrice + 4;
                }
                // $total = $total + (($total * $tax) / 100);
                //                $totalPriceAfterDiscount = $ourPriceRow + $totalCustomDiscout;
                //                $uniPrice = $totalPriceAfterDiscount / $qty;
                /* $rowDataItems[] = [
                    'pos'=>$m,
                    'qty'=>$qty,
                    'description'=>$_product->getShortDescription(),
                    'price'=>$tmpItemPrice,
                    'discount'=>$_product->getData('pcto_discount'),
                    'uni_price'=>$uniPrice,
                    'grand_total'=>$totalPriceAfterDiscount,
                ];*/
                $rowDataItems = [
                    'our_price'=>$ourPrice,
                    'qty'=>$qty,
                    'extra_price'=>$totalExtraPrice,
                    'shipping_price'=>$shippingPrice,
                    'discount'=>$_product->getData('pcto_discount')
                ];
                break;
            }
        }
        return $rowDataItems;

    }
    protected function getOrderData($orderId) {
        return  $this->orderFactory->create()->load($orderId);
    }
    protected function getPreviewDiscounts($productId = 0) {
        $collection = $this->colPreviewDiscountFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
        return $collection;
    }
    protected function _addTextToPage(\Zend_Pdf_Page &$page, $content, $x1, $y1,$length = 40,$line = 0,$lineHeight = 25) {
        $text = [];
        $style = new \Zend_Pdf_Style();
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
        $style->setFont($font,22);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0));
        $page->setStyle($style);
        if($content != '') {
            foreach ($this->stringUtils->split($content,$length, true, true) as $_value) {
                $text[] = $_value;
            }
            $i = 0;
            if(count($text)) {
                foreach ($text as $part) {
                    $i++;
                    if(($line > 0) && $i > $line) {
                        $y1 += $lineHeight;
                        break;
                    }
                    if($line > 0 && $i == $line) {
                        //$part .= '...';
                    }
                    $page->drawText(strip_tags(ltrim($part)), $x1, $y1, 'UTF-8');
                    $y1 -= $lineHeight;
                }
            }
        }
        return $y1;
    }
    public function addBlockText($page,$x0,$x1,$x2,$y1,$text,$font) {
        $arText = explode(' ',$text);
        $x = $x1;
        if(count($arText)) {
            $i = 0;
            foreach ($arText as $str) {
                $textTmp = $str . ' ';
                $tmpW = $this->widthForStringUsingFontSize($textTmp,$font,$this->font_small);
                if($x + $tmpW >= $x2) {
                    $x = $x0;
                    $y1 -= 15;
                    $page->drawText($textTmp, $x, $y1, 'UTF-8');
                    $x += $tmpW;
                }
                else {
                    $page->drawText($textTmp, $x, $y1,'UTF-8');
                    $x += $tmpW;
                }
            }
        }
        return $y1;

    }
    public function widthForStringUsingFontSize($string, $font, $fontSize)
    {
        $drawingString = @iconv(
            'UTF-8',
            'UTF-16BE',
            $string
        );

        $characters = [];
        for ($i = 0; $i < strlen($drawingString); $i++) {
            $characters[] = ord($drawingString[$i++]) << 8 | ord($drawingString[$i]);
        }
        $glyphs = $font->glyphNumbersForCharacters($characters);
        $widths = $font->widthsForGlyphs($glyphs);
        $stringWidth = array_sum($widths) / $font->getUnitsPerEm() * $fontSize;
        return $stringWidth;
    }

    protected function addImageToPdf(
        \Zend_Pdf_Page &$page,
        $image,
        $x1,
        $y1,
        $x2,
        $y2
    ) {
        try {
            $mediaDictory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $image = \Zend_Pdf_Image::imageWithPath($mediaDictory->getAbsolutePath($image));
            $page->drawImage($image,$x1, $y1,$x2, $y2);
            return true;
        }
        catch (\Exception $exception) {

        }
        return  false;
    }
    protected function setPreviewPdf(\Zend_Pdf $pdf,$isNew = true) {
        if($isNew)
            $pdf->pages[] = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);
        $this->preview_pdf = $pdf;
    }
    protected function getPreviewPdf() {
        //Size A4: 595x842
        return $this->preview_pdf;
    }
    protected function getPreivewMediaPath() {
        return '/advancepreview/custom_previews/product_id_21/test_pdf/';
    }
    /**
     * @param $price
     * @return float|string
     */
    function convertNumberToPrice($price) {
        return $this->priceHelper->currency($price,true,false);
    }
    public function getDailyShippingById($dailyId = 0) {
        if($dailyId > 0) {
            $collection = $this->dailyShippingFactory->create()
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
        return  null;
    }
    function cleanString($string) {
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

        return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    }
    protected function validateUpdatePrice($productId,$customDiscounts,$requestOption) {
        $itcPriceDiscounts = isset($requestOption['ict_discounts_price']) ? (array)$requestOption['ict_discounts_price'] : [];
        $itcPriceAdditional = isset($requestOption['ict_addition_price']) ? (array)$requestOption['ict_addition_price'] : [];
        $itcPriceDailies = isset($requestOption['ict_daily_price']) ? (array)$requestOption['ict_daily_price'] : [];
        $itcProductPrice = isset($requestOption['ict_product_price']) ? $requestOption['ict_product_price'] : 0;
        $itcDiscount = isset($requestOption['txt_pcto_discount']) ? $requestOption['txt_pcto_discount'] : 0;
        $isPriceDiscoutVaild = $this->validatePriceDiscount($customDiscounts, $itcPriceDiscounts);
        $isPriceAdditonalVaild = $this->validatePriceAddiontional($productId, $itcPriceAdditional);
        $isPriceDailiVaild = $this->validatePriceDailies($productId, $itcPriceDailies);
        $isVaild = true;
        $_product = $this->getProductById($productId);
        if($_product && $itcProductPrice == $_product->getFinalPrice() && $itcDiscount == $_product->getData('pcto_discount')) {
            // $isVaild = true;
        }
        else {
            $isVaild = false;
        }
        if(!$isPriceDiscoutVaild  || !$isPriceAdditonalVaild || !$isPriceDailiVaild) {
            $isVaild = false;
        }
        return $isVaild;
    }
    protected function checkTierPriceChange($requestOption, $newTierPrice, $qty) {
        //
        $itemTiers = isset($requestOption['txt_preview_tiers_price']) ? $requestOption['txt_preview_tiers_price'] : '';
        if($itemTiers != '') {
            $itemTiers = (array)json_decode($itemTiers);
        }
        else {
            $itemTiers = [];
        }
        $isOK = false;
        if(count($itemTiers)) {
          /*  foreach ($itemTiers as $itemTier) {
                $itemTier = (array)$itemTier;
                $priceQty = isset($itemTier['price_qty']) ? (int)$itemTier['price_qty'] : 0;
                $tierPrice = isset($itemTier['price']) ? $itemTier['price'] : 0;
                if($priceQty == $qty && $tierPrice == $newTierPrice) {
                    $isOK = true;
                    break;
                }
            }*/
            $requestTierPrice = $this->getTierPriceItemByQtyPro($itemTiers, $qty);
            if($requestTierPrice == $newTierPrice) {
                $isOK = true;
            }
        }
        return $isOK;
    }
    protected function validatePriceDiscount($discounts, $paramsDiscounts) {
        $isOK = true;
        if($discounts) {
            foreach ($discounts as $key => $value) {
               if(!array_key_exists($value->getId(),$paramsDiscounts)) {
                $isOK = false;
                break;
               }
               $txtPrice = $paramsDiscounts[$value->getId()];
               if($value->getData('discount_price') != $txtPrice) {
                    $isOK = false;
                    break;
               }
            }
        }
        return $isOK;
    }
    protected function validatePriceAddiontional($productId, $params) {
        $isOK = true;
        $collection = $this->getPreviewAdditionalOptions($productId);
        if($collection) {
            foreach ($collection as $key => $value) {
               if(!array_key_exists($value->getId(),$params)) {
                $isOK = false;
                break;
               }
               $txtPrice = $params[$value->getId()];
               if($value->getData('price') != $txtPrice) {
                    $isOK = false;
                    break;
               }
            }
        }
        return $isOK;
    }
    protected function validatePriceDailies($productId, $params) {
        $isOK = true;
        $collection = $this->getDailyShippingByProductId($productId);
        if($collection) {
            foreach ($collection as $key => $value) {
               if(!array_key_exists($value->getId(),$params)) {
                $isOK = false;
                break;
               }
               $txtPrice = $params[$value->getId()];
               if($value->getData('amount') != $txtPrice) {
                    $isOK = false;
                    break;
               }
            }
        }
        return $isOK;
    }
     /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\Collection
     */
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }

    public function getDailyShippingByProductId($productId = 0) {
        $collection = $this->dailyShippingFactory->create()
                ->addFieldToSelect(array('amount'))
                ->addFieldToFilter('product_id',$productId);
        return  $collection;
    }

    public function getTierPriceItemByQtyPro($tierPriecs = [], $qty = 0) {
      $price = 0;
      $lastIndex = count($tierPriecs) ? count($tierPriecs) - 1 : 0;
      $lastItem = isset($tierPriecs[$lastIndex]) ? (array)$tierPriecs[$lastIndex] : [];
      if($lastIndex > 0 && isset($lastItem['price_qty']) && $qty >= $lastItem['price_qty']) {
          $price = $lastItem['price'];
      }
      else {
          for($i = 0; $i < count($tierPriecs); $i++) {
              $firesItem = (array)$tierPriecs[0];
              if($i == 0 && $qty < $firesItem['price_qty']) {
                  $tierPriceItem = (array)$tierPriecs[0];
                  $price = $tierPriceItem['price'];
                  break;
              }
              if($i + 1 < count($tierPriecs)) {
                  $currentTeir = (array)$tierPriecs[$i];
                  $nextTier = (array)$tierPriecs[$i + 1];
                  if($qty >= $currentTeir['price_qty'] && $qty < $nextTier['price_qty']) {
                      $price = $currentTeir['price'];
                      break;
                  }
              }
          }
      }

      return $price;
  }
}
