<?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 $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;
    protected $productRepository;
    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,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \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;
        $this->productRepository = $productRepository;
    }
    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,227, $this->y - 77, 367, $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);
             $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'));
                 return $this->resultRedirectFactory->create()->setPath('index.php');
             } */
            if(!isset($wishlistOptions['item_token']) || sha1($wishlistOptions['item_token']) != $token) {
                 $this->messageManager->addErrorMessage(__('Offer pdf not found'));
                 return $this->resultRedirectFactory->create()->setPath('index.php');
             }
             /*echo '<pre>';
                print_r($wishlistOptions);
             echo '</pre>';*/
             $offerId = isset($wishlistOptions['offer_id']) ? $wishlistOptions['offer_id'] : '';
             $storeId = isset($wishlistOptions['store_id']) ? $wishlistOptions['store_id'] : 1;

             $productId = isset($wishlistOptions['product_id']) ? $wishlistOptions['product_id'] : 0;
             $customerId = isset($wishlistOptions['customer_id']) ? $wishlistOptions['customer_id'] : 0;
             $customerAddress = $this->getCustomerAddress($customerId);
             $heaerText = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/header_title');
             $companyInfo = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/company_info');
             $saleManage = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/sale_manage');
             $companyInfo = trim($companyInfo) != '' ? explode("\n", str_replace("\r", "", $companyInfo)) : [];
             $yAddressLeft = $this->y;
             $yAddressRight = $this->y;
             if($customerAddress != null) {
                 $leftTexts = [
                     $heaerText,
                     $customerAddress->getPrefix() . ' '. $customerAddress ->getFirstname() . ' '. $customerAddress->getLastname(),
//                     $customerAddress->getStreet()[0],
//                     $customerAddress->getCity(),
//                     $customerAddress->getPostcode(),
//                     $customerAddress->getCountryId(),
                 ];
                 $tmpStreets = $customerAddress->getStreet();
                 if(count($tmpStreets)) {
                     foreach ($tmpStreets as $tmpStreet) {
                         $leftTexts[] = $tmpStreet;
                     }
                 }
                 $leftTexts[] = $customerAddress->getCity();
                 if($customerAddress->getRegion() && $customerAddress->getRegion() != '') {
                     $leftTexts[] = $customerAddress->getRegion();
                 }

                 $leftTexts[] = $customerAddress->getPostcode();
                 $leftTexts[] = $customerAddress->getCountryId();
                 $yAddressLeft = $this->addHeaderTextLeft($page, $leftTexts,$xLeft,$this->y, $storeId);
             }
            $projectName = isset($wishlistOptions['project_name']) ? $wishlistOptions['project_name'] : '';
             // right
             $textRight1 = [
                 'Kontakt:',
             ];
            if(count($companyInfo)) {
                foreach ($companyInfo as $itemcc) {
                    $textRight1[] = $itemcc;
                }
            }
             $textRight2 = [
                 'Date:'.$storeId,
                 'Offer-Nr.:',
                 'Project Name',
                 'Customer-Nr.:',
                 'Sales manager:',
             ];
            if($storeId == 1 || $storeId == 3) {
                $textRight2 = [
                    'Datum:',
                    'Angebots-Nr.:',
                    'Projektname',
                    'Kunden-Nr.:',
                    'Verkaufsleiter:',
                ];
            }
            $textRight3 = [
                date('d-m-Y'),
                $offerId,
                $projectName,
                $customerId,
                $saleManage,
            ];
//             $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;
            $this->addWellcomeCustomer($page, $customerName, $xLeft, $this->y, $storeId);
            $product = $this->getProductById($productId, $storeId);
            $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, $storeId );
             $this->setPreviewPdf($pdf,true);
             $newPage = $this->getPreviewPdf()->pages[1];
             $this->renderOrderData($newPage,$offerId,$product, $storeId );

             $fileName = 'myfitmix-offer-'.date('Y-m-d-H-i-s').'.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'] : '';
            $storeId = isset($infoBuyRequest['preview_offer_store_id']) ? $infoBuyRequest['preview_offer_store_id'] : '';
            $paramsAdditionOptions = isset($infoBuyRequest['preview_additional_options']) ? $infoBuyRequest['preview_additional_options'] : [];
            $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');
            }
            foreach ($customDiscounts as $customDiscount) {
                if ($i == 0) {
                    $i++;
                    continue;
                }
                if ($designType == 1 && $i == 1) {
                    $discount = $_product->getData('pcto_discount');
                    $defaultValue = ($ourPrice - (($discount * $ourPrice) / 100))*$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;
                }
                $totalExtraPrice += $customDiscount->getData('discount_price');

                $i++;
            }
            $itemToken = isset($infoBuyRequest['uenc']) ? $infoBuyRequest['uenc'] : '';
            $previewOptions = [
                'our_price'=>$ourPrice,
                'qty'=>$qty,
                'extra_price'=>$totalExtraPrice,
                '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,
                'store_id'=>$storeId
            ];
        }
        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, $storeId = 1) {
        $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,
        $storeId = 0
    ) {
        $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);
        $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 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++;
        }
        // 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) {
            $page->drawText($text2,$xRight,  $y,'UTF-8');
            $text3 = $texts3[$j];
            $page->drawText($text3,$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,
        $storeId = 0
    ) {
        $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);
        $OfferText = 'Offer';
        $DearText = 'Dear';
        $weareText = 'We are glad to make you an offer';
        if($storeId == 1 || $storeId == 3) {
            $OfferText = 'Bieten';
            $DearText = 'Sehr geehrter';
            $weareText = 'Wir machen Ihnen gerne ein Angebot';
        }
        $page->drawText($OfferText,$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($DearText.' '.$customerName,$x1, $y,'UTF-8');
        $y -= $this->font_small * 2;
        $page->drawText($weareText,$x1, $y,'UTF-8');
        $y -= 10;
        $this->y = $y;

    }
    protected function renderItems(
        \Zend_Pdf_Page &$page,
        $orderItems,
        $productInfo,
        $storeId = 0
    ) {
//        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',
        ];
        $AdditionalprintingText = 'Additional printing costs';
        $DeliveryTimeText = 'Delivery time';
        $dayPlusText = 'days plus shipping';
        $shippingPlusTypeText = $orderItems['daily_title'];
        if($storeId == 1 || $storeId == 3) {
            $headers = [
                'pos',
                'Menge',
                'Einheit',
                'Beschreibung',
                'Preis ',
                'Rabatt',
                'Einzelpreis',
                'Gesamtpreis',
            ];
            $AdditionalprintingText = 'Zusätzliche Druckkosten';
            $DeliveryTimeText = 'Lieferzeit';
            $dayPlusText = 'Tage plus Versand';
            if($shippingPlusTypeText == 'Standard') {
                $shippingPlusTypeText = "Standard";
            }
            elseif($shippingPlusTypeText == 'Priority') {
                $shippingPlusTypeText = 'Priorität';
            }
            elseif($shippingPlusTypeText == 'Express') {
                $shippingPlusTypeText = 'Äußern';
            }

        }
         $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 == 'shipping_price') {
                    $colPrice = $orderItems['shipping_price'];
                    $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,$AdditionalprintingText,$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 == 'shipping_price') {
//                            $page->drawText('Delivery time: 8 days plus shipping',$xCol + 5, $yText + 5);
                            $yDes = $this->addBlockText($page,$xCol,$xCol, $xCol + 130,$yText + 5,$DeliveryTimeText . ' ' . $dayPlusText .' - '.$shippingPlusTypeText,$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;
            $textNetAmount = 'Net Amount ';
            $textVat = 'VAT';
            $textAmountToPay = 'Amount to pay';
            if($storeId == 1 || $storeId == 3) {
                $textNetAmount = 'Netto-Betrag ';
                $textVat = 'Mwst';
                $textAmountToPay = 'Zu zahlender Betrag';
            }
            $page->drawText($textNetAmount,$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.'% '.$textVat,$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($textAmountToPay,$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', $storeId);
            $exworks = trim($exworks) ? explode("\n", str_replace("\r", "", $exworks)) : [];
           /* $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($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);

            $buttonLefts = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_left', $storeId);
            $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);
            $page->setStyle($style);
            $yFoot = 55;
            $page->drawLine($this->x,70,580,70);
            if(count($buttonLefts)) {
                $yl = $yFoot; //$yText - 10;
                foreach ($buttonLefts as $buttonLeft) {
                    $page->drawText($buttonLeft,$this->x,$yl,'UTF-8');
                    $yl -= 15;
                }
            }
            $buttonRights = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_right', $storeId);
            $buttonRights = $buttonRights != '' ?  explode("\n", str_replace("\r", "", $buttonRights)) : [];
            if(count($buttonRights)) {
                $yl = $yFoot; //$yText - 10;
                foreach ($buttonRights as $buttonRight) {
                    $page->drawText($buttonRight,$this->x + 290,$yl,'UTF-8');
                    $yl -= 15;
                }
            }
        }



    }
    protected function renderOrderData(
        \Zend_Pdf_Page &$page,
        $offerId,
        $product,
        $storeId = 0
    ) {
        $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);
        $offterText = 'Offer-Nr';
        $SeiteText = 'Seite 2 von 2';
        $DeliveryTimeText = 'Delivery time';
        $StandardPUText = 'Standard-PU:';
        $BestbeforeText = 'Best before:';
        $Ingredients = 'Ingredients:';
        $CustomstaffText = 'Customs tariff number:';
        $Quanitiyvariance = 'Quanitiy variance:';
        if($storeId == 1 || $storeId == 3) {
            $offterText = 'Angebots-Nr';
            $SeiteText = 'Seite 2 von 2';
            $DeliveryTimeText = 'Lieferzeit';
            $StandardPUText = "Standard-PU':";
            $BestbeforeText = 'Haltbar bis:';
            $CustomstaffText = 'Zolltarifnummer:';
            $Ingredients = 'Zutaten:';
            $Quanitiyvariance = 'Mengenabweichung:';
        }
        $page->drawText($offterText,$x,$y,'UTF-8');
        $page->drawText($offerId,$x + 100,$y,'UTF-8');
        $page->drawText($SeiteText,$x + 450,$y,'UTF-8');
        $y -= 40;
        $rule2 = $this->previewHelper->getConfigureValueByStore('advancepreview/pdf_template_offer/button_rule_2', $storeId);
//        $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($Quanitiyvariance,$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', $storeId);
        $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($DeliveryTimeText,$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($StandardPUText,$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($BestbeforeText,$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($CustomstaffText,$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',$storeId);
        $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 = [], $storeId = 2) {
        $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) {
                    $price += $item->getData('price');
                    $additionTitle = $this->translateNatalyText($item->getData('title'), $storeId);
                    $titles[] = $additionTitle;
                }
            }
        }
        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_price');
                 /*   $tmpItemPrice += $priceDiscountItem;
                    $priceAfterDiscont = $this->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);*/
//                    $totalCustomDiscout += $priceAfterDiscont;
//                    echo $customDiscount->getData('discount_price') . $customDiscount->getData('discount_title').'<br/>';
                    $i++;
                }
                // $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 translateNatalyText($text, $storeId = 2) {
        if($text != '') {
            $text = trim($text);
        }
        if($storeId == 2) {
            return $text;
        }
        $trans = $text;
        if($text == '5C transparent') {
            $trans = '5Cdurchsichtig';
        }
        elseif($text == 'Quality check') {
            $trans = 'Qualitätsprüfung';
        }
        elseif($text == 'Design service') {
            $trans = 'Gestaltungsdienst';
        }
        return  $trans;
    }
}
