<?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\Order;

use Magento\Framework\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
class DownloadInvoicePdf 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 $number_page = 0;
    protected $current_page = null;
    protected $foolter_texts = [];
    protected $colPreviewOrderItemsFactory;
    protected $invoice;
    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,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        \Magento\Sales\Model\Order\Invoice $invoice
    )
    {
        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->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
        $this->invoice = $invoice;
    }
    public function execute()
    {
         try {
             $prwviewMedia = '/advancepreview/icons/';
             $pdf = new \Zend_Pdf();
             $this->setPreviewPdf($pdf);
             /** @var \Zend_Pdf_Page $page*/
             $numberPage = $this->number_page;
             $page = $this->getPreviewPdf()->pages[$numberPage];
             //   $page->drawLine(0,842 - $ticketHeight,595,842 - $ticketHeight);
             $this->x = 20;
             $this->y = 822; //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 -= 30;
             $xLeft = $this->x;
             $xRight = 297 + 50; //center + 50
             $orderId = $this->getRequest()->getParam('order_id',0);
             $invoiceId = $this->getRequest()->getParam('invoice_id',0);
             $token = $this->getRequest()->getParam('token','');
             $token = trim($token);
             if($orderId <= 0 || $invoiceId <= 0 || $token == '') {
                 $this->messageManager->addErrorMessage(__('Invoice not found'));
                 return  $this->resultRedirectFactory->create()->setPath('index.php');
             }
             $order = $this->getOrderData($orderId);
             $invoice = $this->getInvoiceDetails($invoiceId);
             $invoiceIncrementId = $invoice->getIncrementId();
             if(!$order || !$invoice) {
                 $this->messageManager->addErrorMessage(__('Invoice not found'));
                 return  $this->resultRedirectFactory->create()->setPath('index.php');
             }
             $customerId = $order->getCustomerId();
             $offerId = $invoice->getIncrementId();
             $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);
             }
             $projectName = isset($wishlistOptions['project_name']) ? $wishlistOptions['project_name'] : '';
             // right
             $textRight1 = [
                 'Kontakt:',
             ];
             if(count($companyInfo)) {
                 foreach ($companyInfo as $itemcc) {
                     $textRight1[] = $itemcc;
                 }
             }
             $textRight2 = [
                 'Date:',
                 'Invoice-Nr.:',
                 'Customer-Nr.:',
                 'Sales manager:',
             ];
             $textRight3 = [
                 date('d-m-Y'),
                 $offerId,
                 $customerId,
                 $saleManage,
             ];
             $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);
             $this->renderFoolter($page);
             $items = $order->getAllItems();
             $checkToken = false;
             $this->current_page = $page;
             $customerGroup = $this->getCustomerGroupByCustomerId($customerId);
             if(count($items)) {
                 foreach ($items as $item) {
                     $invoiceItemId = $this->getItemIdByInvoiceId($invoiceId);
                     if($invoiceItemId != $item->getId()) {
                         continue;
                     }

                     $_product = $item->getProduct();
                     $productId = $_product->getId();
//                     $infoBuyRequest = $item->getProductOptionByCode('info_buyRequest');
                     $infoBuyRequest = $this->getCustomItemDetail($item);
                     $itemToken = isset($infoBuyRequest['uenc']) ? $infoBuyRequest['uenc'] : '';
                     if(sha1($itemToken) == $token) {
                         $checkToken = true;
                     }
//                     $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'] : '';
                     $projectName = isset($infoBuyRequest['custom_project_name']) ? $infoBuyRequest['custom_project_name'] : '';
                     $gernerateProjoectId = isset($infoBuyRequest['text_project_generate']) ? $infoBuyRequest['text_project_generate'] : 0;
                     if($gernerateProjoectId > 0) {
                         if($gernerateProjoectId > 1000) {
                             $gernerateProjoectId = $gernerateProjoectId;
                         }
                         else if($gernerateProjoectId > 100) {
                             $gernerateProjoectId = '0'.$gernerateProjoectId;
                         }
                         else if($gernerateProjoectId > 10) {
                             $gernerateProjoectId = '00'.$gernerateProjoectId;
                         }
                         else {
                             $gernerateProjoectId = '000'.$gernerateProjoectId;
                         }
                     }
                     else {
                         $gernerateProjoectId = '';
                     }
                     if($gernerateProjoectId != '') {
                         $projectName = $gernerateProjoectId . ' - ' .$projectName;
                     }
                     $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) {
                             $additionOption = $this->getAdditionPriceByIds($paramsAdditionOptions);
                             $totalExtraPrice += $additionOption['price'];
                             $additionOptionTitle .= implode(',',$additionOption['title']);
                         } else if ($i == $customDiscounts->getSize() - 1) {
                             $shippingPrice = $customDiscount->getData('discount_price') + ($ourPrice * $dailyPrice * $item->getQtyOrdered()) / 100;
                             continue;
                         }
                         $totalExtraPrice += $customDiscount->getData('discount_price');

                         $i++;
                     }
                     $discount = $customerGroup > 1 ? $_product->getData('pcto_discount') : 0;
                     $previewOptions = [
                         'our_price'=>$ourPrice,
                         'qty'=>$qty,
                         'extra_price'=>$totalExtraPrice,
                         'shipping_price'=>$shippingPrice,
                         'discount'=>$discount,
                         'offer_id'=>$offerId,
                         'product_id'=>$productId,
                         'customer_id'=>$customerId,
                         'project_name'=>$projectName,
                         'addition_title'=>$additionOptionTitle,
                         'daily_title'=>$dailyTitle,
                         'daily_day'=>$dailyDay,
                     ];
                     $productInfo = [
                         'product_name'=>$_product->getName(),
                         'product_sku'=>$_product->getSku(),
                         'product_description'=>strip_tags($_product->getData('pdf_product_description')),
                     ];
                     $productImageUrl = $this->getProductImageUrl($_product);
//                     $customPage = $page;
                     if($this->y < 200) {
                         $this->setPreviewPdf($pdf,true);
                         $this->number_page++;
                         $numberPage = $this->number_page;
                         $this->current_page = $this->getPreviewPdf()->pages[$numberPage];
                         $this->y = 800;
                         $this->renderFoolter($this->current_page);
                     }

                     $this->renderItems( $this->current_page,$previewOptions,$productInfo,$_product );
                     if($this->y < 300) {
                          $this->setPreviewPdf($pdf,true);
                          $this->number_page++;
                          $numberPage = $this->number_page;
                            $this->current_page = $this->getPreviewPdf()->pages[$numberPage];
                          $this->y = 800;
                         $this->renderFoolter($this->current_page);

                      }
                     $this->renderProductDetail( $this->current_page,$_product);

//                    break;

                 }
             }
             if(!$checkToken) {
                 $this->messageManager->addErrorMessage(__('Invoice Not found'));
                 return  $this->resultRedirectFactory->create()->setPath('index.php');
             }
             $fileName = 'myfitmix-invoice-'.$invoiceIncrementId.'-'.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');
//            echo $exception->getMessage();
             $this->resultRedirectFactory->create()->setPath('index.php');
         }
//        $this->messageManager->addErrorMessage('Download Design success');
        $this->resultRedirectFactory->create()->setPath('index.php');
    }

    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 renderItemRuels() {
        $page = $this->getPreviewPdf()->pages[$this->number_page];
        /*if($this->y < 100) {
            $this->number_page++;
            $numberPage = $this->number_page;
            $page = $this->getPreviewPdf()->pages[$numberPage];
            $this->y = 800;
        }*/
        $yText = $this->y;
        $exworks = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/button_rule_1');
        $exworks = trim($exworks) ? explode("\n", str_replace("\r", "", $exworks)) : [];
        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->getOpdSetting('advancepreview/pdf_template_offer/button_rule_left');
        $buttonLefts = $buttonLefts != '' ?  explode("\n", str_replace("\r", "", $buttonLefts)) : [];
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
        $style = new \Zend_Pdf_Style();
        $style->setFont($font,$this->font_small);
        $page->setStyle($style);
        if(count($buttonLefts)) {
            $yl = $yText - 20;
            foreach ($buttonLefts as $buttonLeft) {
                $page->drawText($buttonLeft,$this->x,$yl,'UTF-8');
                $yl -= 15;
            }
        }
        $buttonRights = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/button_rule_right');
        $buttonRights = $buttonRights != '' ?  explode("\n", str_replace("\r", "", $buttonRights)) : [];
        if(count($buttonRights)) {
            $yl = $yText - 20;
            foreach ($buttonRights as $buttonRight) {
                $page->drawText($buttonRight,$this->x + 290,$yl,'UTF-8');
                $yl -= 15;
            }
        }
    }
    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);
        $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->getName();
        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
    ) {
        $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('Invoice',$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;
//        $page->drawText('we are glad to make you an offer:',$x1, $y,'UTF-8');
        $y -= 20;
        $this->y = $y;

    }
    protected function renderItems(
        \Zend_Pdf_Page &$page,
        $orderItems,
        $productInfo,
        $product
    ) {
//        print_r($orderItems);
        $tax = 19;
        // render header
        $xCol = $this->x;

        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
        $style = new \Zend_Pdf_Style();
        $style->setFont($font,$this->font_normally);
        $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
        $page->setStyle($style);
        $page->drawText($product->getName(),$xCol, $this->y,'UTF-8');

        $this->y -= 15;
        $page->drawText($orderItems['project_name'],$xCol, $this->y,'UTF-8');
        $this->y -= 15;
        $yText = $this->y - 20;
//        $yText -= 15;
        $style = new \Zend_Pdf_Style();

        /* $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);


        $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 + 71) - $wlast;
                $xLast = ($xCol + 90) - $wlast - 2;
                $page->drawText($header,$xLast, $yText + 5,'UTF-8');
            }
            else {
//                $page->drawText($header,$xCol + 5, $yText + 5,'UTF-8');
                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;
                $txtDiscount = $discount > 0 ? $discount .'%' : '-';
                $cols = [
                    $k,
                    $qty,
                    'stk',
                    'test',
                    $this->convertNumberToPrice($colPrice),
                    $txtDiscount,
                    $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);
//                            $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 printing costs',$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,'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 + 65) - $wlast;
                        $xLast = ($xCol + 90) - $wlast;
                        $page->drawText($col,$xLast, $yText + 5,'UTF-8');
                    }
                    elseif($m == 0 || $m == 2) {
                      /*  $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        $xCol += 30;*/
                        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) {
                     /*   $page->drawText($col,$xCol + 5, $yText + 5,'UTF-8');
                        $xCol += 60;*/
                        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);
            $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 -= 20;
            $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 -= 20;
            $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 + 560,$yText + 10);
            $style->setFillColor(new \Zend_Pdf_Color_Rgb(0,0,0)); //red
            $page->setStyle($style);
            $txtGrandTotalPriceTax = $this->convertNumberToPrice($grandTotalPriceTax);
            $wgrandTotalPriceTax = $this->widthForStringUsingFontSize($txtGrandTotalPriceTax,$font,$this->font_small);
            $xGrandTotalPriceTax = 580 - $wgrandTotalPriceTax - 1;
			$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 -= 40;
            $y = $yText;
            $x = $this->x;
//            $this->y = $yText;
            if($y < 400) {
               /* $pdf = new \Zend_Pdf();
                $this->setPreviewPdf($pdf,true);
                $this->number_page++;
                $numberPage = $this->number_page;*/
             /*   $page = $this->getPreviewPdf()->pages[$numberPage];
                $this->y = 800;*/
//                $this->y = $y;
            }

            $y -= 40;
            $this->y = $y;
        }
    }
    function  renderProductDetail($page, $product) {
        $style = new \Zend_Pdf_Style();
        $x = $this->x;
        $y = $this->y;
        $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 -= 20;
        $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 -= 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('Standard-PU',$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);
        $wPu = $this->widthForStringUsingFontSize('Standard-PU',$font,$this->font_small) + 5;
        $page->drawText(strip_tags($product->getData('pdf_packaging')),$x + $wPu,$y,'UTF-8');
        $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('Best before:',$x,$y,'UTF-8');
        $y -= 20;
        $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'));
//        $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 -= 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('Ingredients',$x,$y,'UTF-8');

        $y -= 20;
        $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 -= 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('Customs tariff number',$x,$y,'UTF-8');

        $y -= 20;

        $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').' - '. $y,$x,$y,'UTF-8');
		$lastRules =  $this->previewHelper->getOpdSetting('advancepreview/pdf_template_offer/button_rule_4');
        $lastRules = trim($lastRules) != '' ? explode("\n", str_replace("\r", "", $lastRules)) : [];
        $y -= 30;
        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');
            }
        }
        $y -= 40;
        $this->y = $y;
    }
    function renderFoolterKafu($page) {
        $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);
        $x = $this->x;
        $page->drawLine($this->x,115,580,115);
        $y = 100;
//        $page->drawText('Registergericht Königstein, Registernummer HRB 7085 Umsatzsteuer-ID-Nr./VAT No. DE258262425 ',$x,$y,'UTF-8');
        $this->addBlockText($page,$x,$x,280,$y,'Registergericht Königstein, Registernummer HRB 7085 Umsatzsteuer-ID-Nr./VAT No. DE258262425 Bankverbindung: Commerzbank Mainz BLZ: 550 400 22, Geschäftsführer/CEO L. Shcherbina, O. Shcherbina Web: www.myfitmix.de, E-Mail: info@myfitmix.de',$font);
        $y = 100;
        $this->addBlockText($page,300,300,545,$y,'Konto-Nr.: 2316420, BIC/Swift: COBADEFF550, IBAN: DE02550400220231642000, Wir sind Bio-zertifiziert: DE-ÖKO-005,',$font);

//        $page->drawText('Konto-Nr.: 2316420,',$x,$y,'UTF-8');
      /*  $x = 280;
        $this->addBlockText($page,$x,$x,545,$y,'Konto-Nr.: 2316420',$font);
        $y -= 15;
//        $page->drawText(',',$x,$y,'UTF-8');
        $this->addBlockText($page,$x,$x,545,$y,'BIC/Swift: COBADEFF550, IBAN: DE02550400220231642000',$font);
        $y -= 15;
//        $page->drawText('Wir sind Bio-zertifiziert: DE-ÖKO-005,',$x,$y,'UTF-8');
        $this->addBlockText($page,$x,$x,545,$y,'Wir sind Bio-zertifiziert: DE-ÖKO-005,',$font);*/
    }
    protected function renderFoolter(
        \Zend_Pdf_Page &$page
    ) {
        $buttonLefts = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_order/order_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);
        $page->setStyle($style);
        $yFoot = 75;
        $page->drawLine($this->x,90,580,90);
        if(count($buttonLefts)) {
            $yl = $yFoot; //$yText - 10;
            foreach ($buttonLefts as $buttonLeft) {
                $page->drawText($buttonLeft,$this->x,$yl,'UTF-8');
                $yl -= 15;
            }
        }
        $buttonRights = $this->previewHelper->getOpdSetting('advancepreview/pdf_template_order/order_rule_right');
        $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
    ) {
        $x = 25;
        $y = $this->y;
        $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->getOpdSetting('advancepreview/pdf_template_offer/button_rule_2');
        $page->drawText($rule2,$x,$y,'UTF-8');
        $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('Quanitiy 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->getOpdSetting('advancepreview/pdf_template_offer/button_rule_2');
        $page->drawText($rule3,$x + 90,$y,'UTF-8');
        $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('Delivery time:',$x,$y,'UTF-8');
        $y -= 20;
        $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 -= 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('Standard-PU',$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);
        $page->drawText(strip_tags($product->getData('pdf_packaging')),$x + 80,$y,'UTF-8');
        $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('Best before:',$x,$y,'UTF-8');
        $y -= 20;
        $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 -= 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('Ingredients',$x,$y,'UTF-8');

        $y -= 20;
        $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 -= 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('Customs tariff number',$x,$y,'UTF-8');

        $y -= 20;

        $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 -= 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);
        $lastRules =  $this->previewHelper->getOpdSetting('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 -= 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($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 -= 20;
                $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 -= 20;
        /*   $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);*/
        $this->y = $y;
    }
    public function getAdditionPriceByIds($ids = []) {
        $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');
                    $titles[] = trim($item->getData('title'));
                }
            }
        }
        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 ) / 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 getCustomItemDetail(
        \Magento\Sales\Model\Order\Item $item
    ) {
        // $infoRequest = $item->getProductOptionByCode('info_buyRequest');
        $itemId = $item->getId();
        $previewOrderItem = $this->getPreviewItemByItemId($itemId);
        $infoRequest = [];
        if($previewOrderItem && $previewOrderItem->getId()) {
            $txt = $previewOrderItem->getData('info_request');
            if(trim($txt) != '') {
                $infoRequest = (array)json_decode($txt);
            }
        }
        return $infoRequest;
    }
    protected function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }


    /**
     * @param int $invoiceId
     * @return array|int|mixed|null
     */
    public function getItemIdByInvoiceId($invoiceId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('item_id'))
            ->addFieldToFilter('invoice_id',$invoiceId);
        $itemId = $collection && $collection->getSize() > 0 ? $collection->getFirstItem()->getData('item_id') : 0;
        return $itemId;
    }
    public function getInvoiceDetails($invoiceId){

        return $this->invoice->load($invoiceId);

    }
    protected function getCustomerGroupByCustomerId($customerId) {
        $customer = $this->customerFactory->create()->load($customerId);
        return $customer->getGroupId();
    }
}
